Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(metrics): split pure checks from storage-backed test files (#111278)

posthog[bot]222825ae1ac3
diff --git a/products/metrics/backend/tests/test_api.py b/products/metrics/backend/tests/test_api.py
index 7b8b37f9d273..0e14687a3245 100644
--- a/products/metrics/backend/tests/test_api.py
+++ b/products/metrics/backend/tests/test_api.py
@@ -4,8 +4,6 @@ import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
-from django.apps import apps
-from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
@@ -17,24 +15,12 @@ from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
-from products.access_control.backend.facade.user_access_control import (
- ACCESS_CONTROL_RESOURCES,
- AccessControlLevelResource,
-)
+from products.access_control.backend.facade.user_access_control import AccessControlLevelResource
from products.access_control.backend.models.access_control import AccessControl
from products.error_tracking.backend.facade.testing import create_issue, create_spike_event
from products.metrics.backend.facade.contracts import METRICS_FUNDAMENTALS_FEATURE_FLAG
-def test_metrics_app_is_installed():
- assert apps.is_installed("products.metrics.backend")
-
-
-class TestMetricsResourceRegistration(SimpleTestCase):
- def test_metrics_is_a_controllable_resource(self) -> None:
- assert "metrics" in ACCESS_CONTROL_RESOURCES
-
-
class TestMetricsValuesApi(APIBaseTest):
@parameterized.expand(
[
diff --git a/products/metrics/backend/tests/test_api_unit.py b/products/metrics/backend/tests/test_api_unit.py
new file mode 100644
index 000000000000..7baf99f5f339
--- /dev/null
+++ b/products/metrics/backend/tests/test_api_unit.py
@@ -0,0 +1,13 @@
+from django.apps import apps
+from django.test import SimpleTestCase
+
+from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES
+
+
+def test_metrics_app_is_installed():
+ assert apps.is_installed("products.metrics.backend")
+
+
+class TestMetricsResourceRegistration(SimpleTestCase):
+ def test_metrics_is_a_controllable_resource(self) -> None:
+ assert "metrics" in ACCESS_CONTROL_RESOURCES
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index 59eab4933ee1..d708550ea969 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -2,7 +2,6 @@ import datetime as dt
from typing import Any
from zoneinfo import ZoneInfo
-import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -21,14 +20,10 @@ from posthog.clickhouse.client.connection import Workload
from products.metrics.backend.facade.api import run_metric_query
from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
-from products.metrics.backend.formula import evaluate, parse_formula
from products.metrics.backend.metric_query_runner import (
_INTERVAL_LADDER,
MetricQueryRunner,
- _active_since_expr,
_align_to_interval,
- _histogram_quantile,
- _pick_interval,
attribute_field,
)
from products.metrics.backend.metric_samples_query_runner import MetricSamplesQueryRunner, build_metric_query_runner
@@ -36,33 +31,6 @@ from products.metrics.backend.metrics4_samples import METRICS4_CUTOVER
from products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables
-class TestPickInterval:
- @parameterized.expand(
- [
- # 60 one-minute buckets.
- ("1h_range_picks_minute", dt.timedelta(hours=1), "minute"),
- # 24 buckets are below the target.
- ("1d_range_picks_hour", dt.timedelta(days=1), "hour"),
- # Finer intervals exceed the target.
- ("30d_range_picks_day", dt.timedelta(days=30), "day"),
- ]
- )
- def test_pick_interval(self, _name: str, delta: dt.timedelta, expected: str) -> None:
- start = dt.datetime(2026, 9, 15, 0, 0, 0, tzinfo=dt.UTC)
- assert _pick_interval(start, start + delta) == expected
-
-
-class TestActiveSinceExpr:
- def test_keeps_series_within_the_last_seen_buffer(self) -> None:
- date_from = dt.datetime(2026, 9, 15, 12, tzinfo=dt.UTC)
-
- expr = _active_since_expr(date_from)
-
- assert isinstance(expr, ast.CompareOperation)
- assert isinstance(expr.right, ast.Constant)
- assert expr.right.value == date_from - dt.timedelta(hours=1)
-
-
class TestAlignToInterval(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
@@ -1287,23 +1255,6 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):
)
-class TestHistogramQuantileInterpolation:
- @parameterized.expand(
- [
- # p50 is 0.3 in the second bucket.
- ("p50_mid_bucket", 0.5, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.3),
- # p25 is 0.075 in the first bucket.
- ("p25_first_bucket", 0.25, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.075),
- # Clamp overflow ranks to the highest bound.
- ("overflow_clamps", 0.99, [0.1, 0.5, 1.0], [1.0, 1.0, 1.0, 10.0], 1.0),
- ("empty_counts", 0.5, [0.1, 0.5], [0.0, 0.0, 0.0], 0.0),
- ("no_bounds", 0.5, [], [10.0], 0.0),
- ]
- )
- def test_interpolation(self, _name, q, bounds, counts, expected):
- assert abs(_histogram_quantile(q, bounds, counts) - expected) < 1e-9
-
-
class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):
runner_class: type[MetricQueryRunner] = MetricQueryRunner
@@ -1474,37 +1425,6 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
-class TestFormulaParser:
- @parameterized.expand(
- [
- ("add", "a + b", {"a": 3.0, "b": 4.0}, 7.0),
- ("precedence", "a + b * 2", {"a": 1.0, "b": 2.0}, 5.0),
- ("parens", "(a - b) / a", {"a": 10.0, "b": 4.0}, 0.6),
- ("unary_minus", "-a + 5", {"a": 2.0}, 3.0),
- ("division_by_zero_yields_zero", "a / b", {"a": 5.0, "b": 0.0}, 0.0),
- ("number_only_arithmetic", "a * 0 + 1.5", {"a": 9.0}, 1.5),
- ]
- )
- def test_evaluate(self, _name, formula, values, expected):
- node = parse_formula(formula, frozenset(values))
- assert abs(evaluate(node, values) - expected) < 1e-9
-
- @parameterized.expand(
- [
- ("unknown_clause", "a + zz", frozenset({"a", "b"})),
- ("unbalanced_parens", "(a + b", frozenset({"a", "b"})),
- ("trailing_garbage", "a + b )", frozenset({"a", "b"})),
- ("empty", " ", frozenset({"a"})),
- ("bad_char", "a ^ b", frozenset({"a", "b"})),
- ("nesting_too_deep_parens", "(" * 40 + "a" + ")" * 40, frozenset({"a"})),
- ("nesting_too_deep_unary", "-" * 40 + "a", frozenset({"a"})),
- ]
- )
- def test_rejects(self, _name, formula, names):
- with pytest.raises(ValueError):
- parse_formula(formula, names)
-
-
class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):
CLASS_DATA_LEVEL_SETUP = True
diff --git a/products/metrics/backend/tests/test_metric_query_runner_unit.py b/products/metrics/backend/tests/test_metric_query_runner_unit.py
new file mode 100644
index 000000000000..d7e39a2c2fe6
--- /dev/null
+++ b/products/metrics/backend/tests/test_metric_query_runner_unit.py
@@ -0,0 +1,79 @@
+import datetime as dt
+
+import pytest
+
+from parameterized import parameterized
+
+from posthog.hogql import ast
+
+from products.metrics.backend.formula import evaluate, parse_formula
+from products.metrics.backend.metric_query_runner import _active_since_expr, _histogram_quantile, _pick_interval
+
+
+class TestPickInterval:
+ @parameterized.expand(
+ [
+ ("1h_range_picks_minute", dt.timedelta(hours=1), "minute"),
+ ("1d_range_picks_hour", dt.timedelta(days=1), "hour"),
+ ("30d_range_picks_day", dt.timedelta(days=30), "day"),
+ ]
+ )
+ def test_pick_interval(self, _name: str, delta: dt.timedelta, expected: str) -> None:
+ start = dt.datetime(2026, 9, 15, 0, 0, 0, tzinfo=dt.UTC)
+ assert _pick_interval(start, start + delta) == expected
+
+
+class TestActiveSinceExpr:
+ def test_keeps_series_within_the_last_seen_buffer(self) -> None:
+ date_from = dt.datetime(2026, 9, 15, 12, tzinfo=dt.UTC)
+
+ expr = _active_since_expr(date_from)
+
+ assert isinstance(expr, ast.CompareOperation)
+ assert isinstance(expr.right, ast.Constant)
+ assert expr.right.value == date_from - dt.timedelta(hours=1)
+
+
+class TestHistogramQuantileInterpolation:
+ @parameterized.expand(
+ [
+ ("p50_mid_bucket", 0.5, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.3),
+ ("p25_first_bucket", 0.25, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.075),
+ ("overflow_clamps", 0.99, [0.1, 0.5, 1.0], [1.0, 1.0, 1.0, 10.0], 1.0),
+ ("empty_counts", 0.5, [0.1, 0.5], [0.0, 0.0, 0.0], 0.0),
+ ("no_bounds", 0.5, [], [10.0], 0.0),
+ ]
+ )
+ def test_interpolation(self, _name, q, bounds, counts, expected):
+ assert abs(_histogram_quantile(q, bounds, counts) - expected) < 1e-9
+
+
+class TestFormulaParser:
+ @parameterized.expand(
+ [
+ ("add", "a + b", {"a": 3.0, "b": 4.0}, 7.0),
+ ("precedence", "a + b * 2", {"a": 1.0, "b": 2.0}, 5.0),
+ ("parens", "(a - b) / a", {"a": 10.0, "b": 4.0}, 0.6),
+ ("unary_minus", "-a + 5", {"a": 2.0}, 3.0),
+ ("division_by_zero_yields_zero", "a / b", {"a": 5.0, "b": 0.0}, 0.0),
+ ("number_only_arithmetic", "a * 0 + 1.5", {"a": 9.0}, 1.5),
+ ]
+ )
+ def test_evaluate(self, _name, formula, values, expected):
+ node = parse_formula(formula, frozenset(values))
+ assert abs(evaluate(node, values) - expected) < 1e-9
+
+ @parameterized.expand(
+ [
+ ("unknown_clause", "a + zz", frozenset({"a", "b"})),
+ ("unbalanced_parens", "(a + b", frozenset({"a", "b"})),
+ ("trailing_garbage", "a + b )", frozenset({"a", "b"})),
+ ("empty", " ", frozenset({"a"})),
+ ("bad_char", "a ^ b", frozenset({"a", "b"})),
+ ("nesting_too_deep_parens", "(" * 40 + "a" + ")" * 40, frozenset({"a"})),
+ ("nesting_too_deep_unary", "-" * 40 + "a", frozenset({"a"})),
+ ]
+ )
+ def test_rejects(self, _name, formula, names):
+ with pytest.raises(ValueError):
+ parse_formula(formula, names)