: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
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.pyindex 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 Callablefrom posthog.test.base import BaseTestfrom unittest.mock import Mock, patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom posthog.clickhouse.client.execute import KillSwitchLevel@@ -13,9 +15,12 @@ from posthog.clickhouse.query_tagging import Product, QueryTags, query_tags, resfrom 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):passdiff --git a/posthog/clickhouse/test/test_deletion_coverage.py b/posthog/clickhouse/test/test_deletion_coverage.pyindex 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, ClickhouseTestMixinfrom django.conf import settings+from django.test import SimpleTestCasefrom posthog.clickhouse.client import sync_executefrom 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.pyindex 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 = SharingAccessTokenAreturn 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 == 1diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 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::TestDeadLetterQueueee/clickhouse/models/test/test_property.py::TestPropDenormalizedposthog/api/oauth/test_cimd.py::TestAuthorizationServerMetadata-posthog/clickhouse/client/test/test_limit.py::TestRateLimitposthog/clickhouse/test/test_deletion_coverage.py::TestDeletionCoverageposthog/hogql/database/test/test_postgres_table.py::TestPostgresTablePrimaryKeyposthog/hogql/printer/test/test_sql_injection_defenses.py::TestEscapePreservationOnParserOutputposthog/hogql/printer/test/test_sql_injection_defenses.py::TestPrintTimeOnlyAllowlistsposthog/hogql/printer/test/test_sql_injection_defenses.py::TestVerbatimFieldPrinterDefenseInDepthposthog/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::TestTierAwareListingThrottleposthog/tasks/test/test_usage_report.py::TestSendNoUsageposthog/test/activity_logging/test_feature_flag_activity_logging.py::TestChangesBetweenFeatureFlags-posthog/test/test_api_queries_budget.py::TestTokenBucketposthog/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::TestGetDagIdproducts/posthog_ai/eval_harness/test/test_acp_log.py::TestSandboxedTraceCaptureParserproducts/posthog_ai/scripts/hogql_example/test/test_hogql_example.py::TestRenderHogQLExample-products/revenue_analytics/backend/test/test_joins.py::TestGetCustomerRevenueViewNameproducts/streamlit_apps/backend/tests/test_tasks.py::TestAutoRestartCrashedStreamlitSandboxesproducts/streamlit_apps/backend/tests/test_tasks.py::TestStopIdleStreamlitSandboxesproducts/surveys/backend/api/test/test_external_surveys.py::TestExternalSurveysURLs-products/tasks/backend/tests/test_api.py::TestUsageLimitResponseproducts/web_analytics/dags/tests/test_cache_warming.py::TestFleetQuerySelectionproducts/web_analytics/dags/tests/test_cache_warming.py::TestSplitWarmableQueriesproducts/web_analytics/dags/tests/test_cache_warming.py::TestWarmableQueriesCachingdiff --git a/posthog/test/test_api_queries_budget.py b/posthog/test/test_api_queries_budget.pyindex 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.0def 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.0def 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.0assert seconds_until_positive(remaining, SPEC) == 1800assert seconds_until_positive(5.0, SPEC) == 0assert seconds_until_positive(0.0, SPEC) == 1def 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.0assert 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.0def 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 Nonedef 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 Noneassert API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="read")._value.get() == read_before + 1assert API_QUERIES_BUDGET_ERRORS_COUNTER.labels(op="debit")._value.get() == debit_before + 1diff --git a/products/alerts/backend/tests/api/test_alert.py b/products/alerts/backend/tests/api/test_alert.pyindex 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, QueryMatchingTestfrom unittest import mockfrom django.core.cache import cache+from django.test import SimpleTestCasefrom parameterized import parameterizedfrom 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.pyindex 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 pytestfrom posthog.test.base import BaseTestfrom unittest import mock+from django.test import SimpleTestCase+from parameterized import parameterizedfrom posthog.hogql.database.database import Database@@ -30,8 +32,7 @@ from products.data_modeling.backend.models.node import NodeTypefrom 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.pyindex 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 pytestfrom posthog.test.base import BaseTest+from django.test import SimpleTestCase+from parameterized import parameterizedfrom 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.pyindex 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 Noneself.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)