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(tests): remove unused database setup from more tests (#116844)

Paul D'Ambra1b4d02ee47a7
diff --git a/posthog/clickhouse/client/test/test_limit.py b/posthog/clickhouse/client/test/test_limit.py
index 68c0329b94c7..645fbe49bf80 100644
--- a/posthog/clickhouse/client/test/test_limit.py
+++ b/posthog/clickhouse/client/test/test_limit.py
@@ -5,6 +5,8 @@ from collections.abc import Callable
from posthog.test.base import BaseTest
from unittest.mock import Mock, patch
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from posthog.clickhouse.client.execute import KillSwitchLevel
@@ -13,9 +15,12 @@ from posthog.clickhouse.query_tagging import Product, QueryTags, query_tags, res
from posthog.constants import AvailableFeature
-class TestRateLimit(BaseTest):
+class TestRateLimit(SimpleTestCase):
def setUp(self) -> None:
super().setUp()
+ team_bypass_patcher = patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False)
+ team_bypass_patcher.start()
+ self.addCleanup(team_bypass_patcher.stop)
self.limit = RateLimit(
max_concurrency=1,
applicable=lambda *args, **kwargs: kwargs.get("is_api") if "is_api" in kwargs else args[0],
@@ -42,6 +47,13 @@ class TestRateLimit(BaseTest):
with self.assertRaises(ConcurrencyLimitExceeded):
self.cancels.append(self.limit.use(True, 8, 18))
+ @patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=True)
+ def test_team_bypass_uses_default(self, bypass: Mock) -> None:
+ self.cancels.append(self.limit.use(is_api=True, team_id=8, task_id=17))
+
+ assert self.limit.use(is_api=True, team_id=8, task_id=18) is None
+ bypass.assert_called_once_with(8)
+
@patch("posthog.clickhouse.client.limit.TEST", False)
@patch("posthog.clickhouse.client.execute.get_kill_switch_level", return_value=KillSwitchLevel.FULL)
@patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=True)
@@ -210,7 +222,9 @@ class TestRateLimit(BaseTest):
pass
# Second task should retry and eventually fail due to timeout
- retry_limit.use(task_id=2)
+ slot = retry_limit.use(task_id=2)
+ assert slot is not None
+ self.addCleanup(retry_limit.release, slot)
with self.assertRaises(ConcurrencyLimitExceeded):
with retry_limit.run(task_id=2):
pass
diff --git a/posthog/clickhouse/test/test_deletion_coverage.py b/posthog/clickhouse/test/test_deletion_coverage.py
index 0c88b562b613..48d9e41e8d9b 100644
--- a/posthog/clickhouse/test/test_deletion_coverage.py
+++ b/posthog/clickhouse/test/test_deletion_coverage.py
@@ -1,6 +1,7 @@
from posthog.test.base import BaseTest, ClickhouseTestMixin
from django.conf import settings
+from django.test import SimpleTestCase
from posthog.clickhouse.client import sync_execute
from posthog.models.deletion_targets import (
@@ -49,30 +50,6 @@ class TestDeletionCoverage(ClickhouseTestMixin, BaseTest):
"See docs/internal/clickhouse-deletion-coverage.md."
)
- def test_every_personal_data_target_is_squashed_or_exempt(self):
- # A merge moves a distinct_id to another person, and a later deletion names only the
- # survivor, so a target the squash skips keeps its rows on the absorbed person until the
- # TTL drops them (#93035). The test above cannot catch that, because it checks only that the
- # deletion sweep reaches a table, and only for a table that declares person_properties. This
- # test reads the registered targets instead, because a target need not declare that column.
- skipped = {target.data_table for target in PERSONAL_DATA_TARGETS if not target.accepts_person_id_rewrite}
- unaccounted = sorted(skipped - PERSON_ID_REWRITE_EXEMPT)
-
- assert not unaccounted, (
- f"{unaccounted} are swept for person deletion, but squash_person_overrides never rewrites "
- "their person_id, so a merge strands rows on the person it absorbed. Set "
- "accepts_person_id_rewrite=True on each (posthog/models/deletion_targets.py), or add it to "
- "PERSON_ID_REWRITE_EXEMPT with the window you are accepting. "
- "See docs/internal/clickhouse-deletion-coverage.md."
- )
-
- stale = sorted(PERSON_ID_REWRITE_EXEMPT - skipped)
- assert not stale, (
- f"{stale} are in PERSON_ID_REWRITE_EXEMPT but are not registered targets the squash skips. "
- "Remove each entry: either the target now sets accepts_person_id_rewrite=True, or it is no "
- "longer in PERSONAL_DATA_TARGETS."
- )
-
def test_squash_targets_accept_an_alter_update_on_person_id(self):
# The squash rewrites person_id with ALTER UPDATE, and ClickHouse refuses one on a column in
# the sorting key or the partition key. A target marked accepts_person_id_rewrite whose key
@@ -119,3 +96,29 @@ class TestDeletionCoverage(ClickhouseTestMixin, BaseTest):
"so the squash cannot assign it. Both are fixed once the table holds data, so this "
"needs a new table rather than an ALTER."
)
+
+
+class TestDeletionTargetRegistration(SimpleTestCase):
+ def test_every_personal_data_target_is_squashed_or_exempt(self):
+ # A merge moves a distinct_id to another person, and a later deletion names only the
+ # survivor, so a target the squash skips keeps its rows on the absorbed person until the
+ # TTL drops them (#93035). The test above cannot catch that, because it checks only that the
+ # deletion sweep reaches a table, and only for a table that declares person_properties. This
+ # test reads the registered targets instead, because a target need not declare that column.
+ skipped = {target.data_table for target in PERSONAL_DATA_TARGETS if not target.accepts_person_id_rewrite}
+ unaccounted = sorted(skipped - PERSON_ID_REWRITE_EXEMPT)
+
+ assert not unaccounted, (
+ f"{unaccounted} are swept for person deletion, but squash_person_overrides never rewrites "
+ "their person_id, so a merge strands rows on the person it absorbed. Set "
+ "accepts_person_id_rewrite=True on each (posthog/models/deletion_targets.py), or add it to "
+ "PERSON_ID_REWRITE_EXEMPT with the window you are accepting. "
+ "See docs/internal/clickhouse-deletion-coverage.md."
+ )
+
+ stale = sorted(PERSON_ID_REWRITE_EXEMPT - skipped)
+ assert not stale, (
+ f"{stale} are in PERSON_ID_REWRITE_EXEMPT but are not registered targets the squash skips. "
+ "Remove each entry: either the target now sets accepts_person_id_rewrite=True, or it is no "
+ "longer in PERSONAL_DATA_TARGETS."
+ )
diff --git a/posthog/session_recordings/test/test_session_recording_throttle.py b/posthog/session_recordings/test/test_session_recording_throttle.py
index 040c4f244350..ed20d21c865b 100644
--- a/posthog/session_recordings/test/test_session_recording_throttle.py
+++ b/posthog/session_recordings/test/test_session_recording_throttle.py
@@ -237,7 +237,13 @@ class TestListingRatesConfig(SimpleTestCase):
assert throttle.rate == expected_rate
-class TestTierAwareListingThrottle(BaseTest):
+class TestTierAwareListingThrottle(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ rate_limit_patcher = patch("posthog.rate_limit.is_rate_limit_enabled", return_value=False)
+ rate_limit_patcher.start()
+ self.addCleanup(rate_limit_patcher.stop)
+
@patch("posthog.session_recordings.session_recording_api.get_cached_org_tier", side_effect=Exception("db gone"))
def test_tier_lookup_error_falls_back_to_default_rates(self, _mock_tier: object) -> None:
throttle = ListingBurstRateThrottle()
@@ -320,7 +326,7 @@ def _fake_sharing_token_request(token: str, auth_cls: type = SharingAccessTokenA
return type("FakeRequest", (), {"META": {}, "auth": None, "successful_authenticator": auth})()
-class TestSharingTokenReplayThrottle(BaseTest):
+class TestSharingTokenReplayThrottle(SimpleTestCase):
def setUp(self) -> None:
super().setUp()
cache.clear()
@@ -413,9 +419,16 @@ class TestSharingTokenReplayThrottle(BaseTest):
before = _counter_value("replay_sharing_token", "sharing_token")
# Burn the bucket then attempt one more — only the rejected one bumps the counter.
- for _ in range(2):
+ with (
+ patch(
+ "posthog.session_recordings.session_recording_api.team_is_allowed_to_bypass_throttle",
+ return_value=False,
+ ),
+ patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False),
+ ):
+ for _ in range(2):
+ throttle.allow_request(_fake_sharing_token_request("token-counted"), view=view)
throttle.allow_request(_fake_sharing_token_request("token-counted"), view=view)
- throttle.allow_request(_fake_sharing_token_request("token-counted"), view=view)
after = _counter_value("replay_sharing_token", "sharing_token")
assert after - before == 1
diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
index 30e6709c59e9..b3e361ab29ad 100644
--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
@@ -1,28 +1,20 @@
ee/clickhouse/models/test/test_dead_letter_queue.py::TestDeadLetterQueue
ee/clickhouse/models/test/test_property.py::TestPropDenormalized
posthog/api/oauth/test_cimd.py::TestAuthorizationServerMetadata
-posthog/clickhouse/client/test/test_limit.py::TestRateLimit
posthog/clickhouse/test/test_deletion_coverage.py::TestDeletionCoverage
posthog/hogql/database/test/test_postgres_table.py::TestPostgresTablePrimaryKey
posthog/hogql/printer/test/test_sql_injection_defenses.py::TestEscapePreservationOnParserOutput
posthog/hogql/printer/test/test_sql_injection_defenses.py::TestPrintTimeOnlyAllowlists
posthog/hogql/printer/test/test_sql_injection_defenses.py::TestVerbatimFieldPrinterDefenseInDepth
posthog/models/tophog/test/test_tophog_queries.py::TestTopHogQueries
-posthog/session_recordings/test/test_session_recording_throttle.py::TestSharingTokenReplayThrottle
-posthog/session_recordings/test/test_session_recording_throttle.py::TestTierAwareListingThrottle
posthog/tasks/test/test_usage_report.py::TestSendNoUsage
posthog/test/activity_logging/test_feature_flag_activity_logging.py::TestChangesBetweenFeatureFlags
-posthog/test/test_api_queries_budget.py::TestTokenBucket
posthog/test/test_check_product_migrations.py::TestCheckProductMigrations
-products/alerts/backend/tests/api/test_alert.py::TestAlertEventProperties
-products/data_modeling/backend/test/test_saved_query_dag_sync.py::TestGetDagId
products/posthog_ai/eval_harness/test/test_acp_log.py::TestSandboxedTraceCaptureParser
products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py::TestRenderHogQLExample
-products/revenue_analytics/backend/test/test_joins.py::TestGetCustomerRevenueViewName
products/streamlit_apps/backend/tests/test_tasks.py::TestAutoRestartCrashedStreamlitSandboxes
products/streamlit_apps/backend/tests/test_tasks.py::TestStopIdleStreamlitSandboxes
products/surveys/backend/api/test/test_external_surveys.py::TestExternalSurveysURLs
-products/tasks/backend/tests/test_api.py::TestUsageLimitResponse
products/web_analytics/dags/tests/test_cache_warming.py::TestFleetQuerySelection
products/web_analytics/dags/tests/test_cache_warming.py::TestSplitWarmableQueries
products/web_analytics/dags/tests/test_cache_warming.py::TestWarmableQueriesCaching
diff --git a/posthog/test/test_api_queries_budget.py b/posthog/test/test_api_queries_budget.py
index a31c92bcc219..ba61d73b91a4 100644
--- a/posthog/test/test_api_queries_budget.py
+++ b/posthog/test/test_api_queries_budget.py
@@ -65,10 +65,22 @@ class TestBudgetSpecFor(SimpleTestCase):
@override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=70, API_QUERIES_BUDGET_CAPACITY_HOURS=24)
-class TestTokenBucket(BaseTest):
+class TestTokenBucket(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team_id = str(uuid4())
+ self.fresh_team_id = str(uuid4())
+
+ def tearDown(self) -> None:
+ get_client().delete(
+ f"{BUDGET_KEY_PREFIX}team/{self.team_id}",
+ f"{BUDGET_KEY_PREFIX}team/{self.fresh_team_id}",
+ )
+ super().tearDown()
+
def test_budget_redis_calls_use_a_one_second_timeout(self):
with patch("posthog.api_queries_budget.get_client") as get_client:
- refill_and_read("team-a", SPEC)
+ refill_and_read(self.team_id, SPEC)
get_client.assert_called_once_with(
socket_timeout=BUDGET_REDIS_TIMEOUT_SECONDS,
@@ -76,43 +88,43 @@ class TestTokenBucket(BaseTest):
)
def test_fresh_bucket_starts_full(self):
- assert refill_and_read("team-a", SPEC, now=1000.0) == 7200.0
+ assert refill_and_read(self.team_id, SPEC, now=1000.0) == 7200.0
def test_debit_then_refill_at_rate_capped_at_capacity(self):
- refill_and_read("team-a", SPEC, now=1000.0)
- assert debit("team-a", 5000) == 2200.0
- assert refill_and_read("team-a", SPEC, now=1001.0) == 2201.0
- assert refill_and_read("team-a", SPEC, now=99999.0) == 7200.0
+ refill_and_read(self.team_id, SPEC, now=1000.0)
+ assert debit(self.team_id, 5000) == 2200.0
+ assert refill_and_read(self.team_id, SPEC, now=1001.0) == 2201.0
+ assert refill_and_read(self.team_id, SPEC, now=99999.0) == 7200.0
def test_negative_balance_reports_seconds_until_positive(self):
- refill_and_read("team-a", SPEC, now=1000.0)
- remaining = debit("team-a", 9000)
+ refill_and_read(self.team_id, SPEC, now=1000.0)
+ remaining = debit(self.team_id, 9000)
assert remaining == -1800.0
assert seconds_until_positive(remaining, SPEC) == 1800
assert seconds_until_positive(5.0, SPEC) == 0
assert seconds_until_positive(0.0, SPEC) == 1
def test_balance_floors_at_minus_one_hour_of_refill(self):
- refill_and_read("team-a", SPEC, now=1000.0)
- assert debit("team-a", 50_000) == -3600.0
+ refill_and_read(self.team_id, SPEC, now=1000.0)
+ assert debit(self.team_id, 50_000) == -3600.0
assert seconds_until_positive(-3600.0, SPEC) == 3600
- assert refill_and_read("team-a", SPEC, now=1000.0 + 3600) == 0.0
+ assert refill_and_read(self.team_id, SPEC, now=1000.0 + 3600) == 0.0
def test_debit_before_any_read_uses_the_free_capacity_and_floor(self):
- assert debit("team-new", 100) == 1580.0
- assert debit("team-new", 100) == 1480.0
- assert debit("team-new", 5000) == -70.0
+ assert debit(self.fresh_team_id, 100) == 1580.0
+ assert debit(self.fresh_team_id, 100) == 1480.0
+ assert debit(self.fresh_team_id, 5000) == -70.0
@override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=0)
def test_disabled_budget_does_not_debit(self):
- assert debit("team-a", 1000) is None
+ assert debit(self.team_id, 1000) is None
def test_redis_errors_fail_open_and_count(self):
read_before = API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="read")._value.get()
debit_before = API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="debit")._value.get()
with patch("posthog.api_queries_budget.get_client", side_effect=Exception("redis down")):
- assert refill_and_read("team-a", SPEC) is None
- assert debit("team-a", 1) is None
+ assert refill_and_read(self.team_id, SPEC) is None
+ assert debit(self.team_id, 1) is None
assert API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="read")._value.get() == read_before + 1
assert API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="debit")._value.get() == debit_before + 1
diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.py
index 2793d95af0e5..4909b9bb2bae 100644
--- a/products/alerts/backend/tests/api/test_alert.py
+++ b/products/alerts/backend/tests/api/test_alert.py
@@ -8,6 +8,7 @@ from posthog.test.base import APIBaseTest, QueryMatchingTest
from unittest import mock
from django.core.cache import cache
+from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
@@ -2112,7 +2113,7 @@ class TestAlertTestDelivery(TrendsInsightAPITest):
cache.clear()
-class TestAlertEventProperties(APIBaseTest):
+class TestAlertEventProperties(SimpleTestCase):
@parameterized.expand(
[
(
@@ -2219,6 +2220,7 @@ class TestAlertEventProperties(APIBaseTest):
expected_detector_fields: dict,
) -> None:
alert = AlertConfiguration(
+ id=None,
name="test alert",
condition=condition,
detector_config=detector_config,
@@ -2271,6 +2273,7 @@ class TestAlertEventProperties(APIBaseTest):
)
def test_event_properties_capture_alert_config_adoption(self, _name: str, config: dict, expected: dict) -> None:
alert = AlertConfiguration(
+ id=None,
name="test alert",
condition={"type": "absolute_value"},
config=config,
@@ -2281,6 +2284,18 @@ class TestAlertEventProperties(APIBaseTest):
assert props[key] == value, f"{key} expected {value}, got {props[key]}"
+class TestPersistedAlertEventProperties(APIBaseTest):
+ def test_event_properties_include_alert_id_and_subscriber_count(self) -> None:
+ insight = Insight.objects.create(team=self.team, name="Signups", created_by=self.user)
+ alert = AlertConfiguration.objects.create(team=self.team, insight=insight, name="test alert")
+ AlertSubscription.objects.create(alert_configuration=alert, user=self.user)
+
+ props = alert._get_event_properties()
+
+ assert props["alert_id"] == alert.id
+ assert props["subscribed_users_count"] == 1
+
+
class TestAlertListFilters(TrendsInsightAPITest):
def setUp(self):
super().setUp()
diff --git a/products/data_modeling/backend/test/test_saved_query_dag_sync.py b/products/data_modeling/backend/test/test_saved_query_dag_sync.py
index b370f2f20e8f..f9063b2ebd22 100644
--- a/products/data_modeling/backend/test/test_saved_query_dag_sync.py
+++ b/products/data_modeling/backend/test/test_saved_query_dag_sync.py
@@ -4,6 +4,8 @@ import pytest
from posthog.test.base import BaseTest
from unittest import mock
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from posthog.hogql.database.database import Database
@@ -30,8 +32,7 @@ from products.data_modeling.backend.models.node import NodeType
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
-class TestGetDagId(BaseTest):
+class TestGetDagId(SimpleTestCase):
def test_get_dag_id_returns_expected_format(self):
self.assertEqual(get_dag_id(123), "posthog_123")
self.assertEqual(get_dag_id(1), "posthog_1")
diff --git a/products/revenue_analytics/backend/test/test_joins.py b/products/revenue_analytics/backend/test/test_joins.py
index aa97d3116476..cc51b5f6944e 100644
--- a/products/revenue_analytics/backend/test/test_joins.py
+++ b/products/revenue_analytics/backend/test/test_joins.py
@@ -1,6 +1,7 @@
-import pytest
from posthog.test.base import BaseTest
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from products.data_tools.backend.models.join import DataWarehouseJoin
@@ -10,10 +11,8 @@ from products.revenue_analytics.backend.joins import (
remove_person_join,
)
-pytestmark = [pytest.mark.django_db]
-
-class TestGetCustomerRevenueViewName(BaseTest):
+class TestGetCustomerRevenueViewName(SimpleTestCase):
@parameterized.expand(
[
("", "stripe.customer_revenue_view"),
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 2bcac8c9fc84..21dbd3008bbd 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -16691,14 +16691,17 @@ class TestGetPosthogCodeUsage(TestCase):
self.assertIsNone(get_posthog_code_usage(self.team.id + 10_000))
-class TestUsageLimitResponse(TestCase):
+class TestUsageLimitResponse(SimpleTestCase):
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_over_limit_response_is_structured(self, mock_usage):
mock_usage.return_value = CodeUsageStatus(
is_rate_limited=True, limit_type="burst", reset_at="2026-06-09T00:00:00Z", is_pro=False
)
- response = usage_limit_response(MagicMock(), 1)
+ with patch(
+ "products.tasks.backend.logic.services.code_usage_gate.organization_deactivated", return_value=False
+ ):
+ response = usage_limit_response(MagicMock(), 1)
assert response is not None
self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)