: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): avoid database setup in shared test utility tests (part 1) (#116222)
Paul D'Ambrafebd56b04c4f
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex 19dee683009a..809b7e87d063 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -13,7 +13,7 @@ from unittest.mock import patchfrom django.db import transactionfrom django.db.utils import IntegrityErrorfrom django.http import HttpRequest-from django.test import override_settings+from django.test import SimpleTestCase, override_settingsfrom django.utils import timezonefrom parameterized import parameterized@@ -786,7 +786,7 @@ class TestActivityLogVisibilityManager(BaseTest):self.assertEqual(filtered.count(), 4)-class TestActivityTriggerContext(BaseTest):+class TestActivityTriggerContext(SimpleTestCase):def tearDown(self):activity_storage.clear_trigger()super().tearDown()diff --git a/posthog/test/activity_logging/test_user_activity_logging.py b/posthog/test/activity_logging/test_user_activity_logging.pyindex 54b8741760f3..aadaa3888dca 100644--- a/posthog/test/activity_logging/test_user_activity_logging.py+++ b/posthog/test/activity_logging/test_user_activity_logging.py@@ -1,5 +1,6 @@from posthog.test.base import BaseTest+from django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized@@ -18,7 +19,7 @@ from posthog.models.signals import model_activity_signalfrom posthog.test.activity_log_utils import ActivityLogTestHelper-class TestUserActivityLoggingConfiguration(BaseTest):+class TestUserActivityLoggingConfiguration(SimpleTestCase):"""Tests for User activity logging configuration dictionaries."""@parameterized.expand(diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 607f46dd6651..8e8655e2f05d 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -69,35 +69,9 @@ posthog/tasks/test/test_auth_token_cache_verification.py::TestVerifyAndFixAuthToposthog/tasks/test/test_usage_report.py::TestSendNoUsageposthog/temporal/proxy_service/test/monitor_test.py::TestCheckCloudflareCertificateStatusposthog/temporal/proxy_service/test/test_cloudflare.py::TestCloudflareAPIErrorIsRateLimited-posthog/test/activity_logging/test_activity_logging.py::TestActivityTriggerContextposthog/test/activity_logging/test_feature_flag_activity_logging.py::TestChangesBetweenFeatureFlags-posthog/test/activity_logging/test_user_activity_logging.py::TestUserActivityLoggingConfigurationposthog/test/test_api_queries_budget.py::TestTokenBucket-posthog/test/test_cache_utils.py::TestCacheUtilsposthog/test/test_check_product_migrations.py::TestCheckProductMigrations-posthog/test/test_dbrouter.py::TestReplicaRouter-posthog/test/test_domain_connect.py::TestBuildSyncApplyUrl-posthog/test/test_domain_connect.py::TestDiscoverDomainConnect-posthog/test/test_domain_connect.py::TestExtractRootDomainAndHost-posthog/test/test_domain_connect.py::TestGenerateApplyUrl-posthog/test/test_domain_connect.py::TestGetAvailableProviders-posthog/test/test_domain_connect.py::TestGetServiceIdForRegion-posthog/test/test_domain_connect.py::TestSignQueryString-posthog/test/test_element_model.py::TestElement-posthog/test/test_event_usage.py::TestGetEventSource-posthog/test/test_event_usage.py::TestIsWizardSelfDrivingProgram-posthog/test/test_event_usage.py::TestSanitizeHeaderValue-posthog/test/test_feature_flag_analytics.py::TestEnrichedFlagKeyExprSQL-posthog/test/test_feature_flag_analytics.py::TestFindFlagsWithEnrichedAnalyticsTask-posthog/test/test_feature_flag_analytics.py::TestFlagKeyFilterSQL-posthog/test/test_geoip.py::TestGeoipLocation-posthog/test/test_middleware.py::TestPerRequestLoggingContextMiddlewareMcpHeaders-posthog/test/test_middleware.py::TestSocialAuthExceptionMiddleware-posthog/test/test_products.py::TestProducts-posthog/test/test_rate_limit.py::TestPersonalOrProjectSecretApiKeyRateThrottle-posthog/test/test_rate_limit.py::TestProjectSecretApiKeyTeamRateThrottle-posthog/test/test_renderers.py::TestCleanDataForJSON-posthog/test/test_sampling.py::TestSamplingproducts/access_control/backend/tests/test_property_access_control.py::TestGetDefaultAccessLevelproducts/ai_observability/backend/api/test/test_personal_spend.py::TestPersonalSpendEuRedirectproducts/ai_observability/backend/models/test/test_taggers.py::TestLLMTaggerConfigdiff --git a/posthog/test/test_cache_utils.py b/posthog/test/test_cache_utils.pyindex 7d0702a694bc..18afd7dd6ddf 100644--- a/posthog/test/test_cache_utils.py+++ b/posthog/test/test_cache_utils.py@@ -2,9 +2,10 @@ from datetime import timedeltafrom time import sleepfrom typing import Optional-from posthog.test.base import APIBaseTestfrom unittest.mock import Mock+from django.test import SimpleTestCase+from posthog.cache_utils import cache_formocked_dependency = Mock()@@ -29,7 +30,7 @@ def fn_background(number: float) -> int:return value-class TestCacheUtils(APIBaseTest):+class TestCacheUtils(SimpleTestCase):def setUp(self):mocked_dependency.reset_mock()mocked_dependency.return_value = 1diff --git a/posthog/test/test_dbrouter.py b/posthog/test/test_dbrouter.pyindex 4cbffb2ca427..e31734faabdb 100644--- a/posthog/test/test_dbrouter.py+++ b/posthog/test/test_dbrouter.py@@ -1,11 +1,11 @@-from posthog.test.base import BaseTest+from django.test import SimpleTestCasefrom posthog.dbrouter import ReplicaRouterfrom posthog.models.team import Teamfrom posthog.models.user import User-class TestReplicaRouter(BaseTest):+class TestReplicaRouter(SimpleTestCase):def test_opted_in_models_are_replica_routed(self) -> None:router = ReplicaRouter(["User"])diff --git a/posthog/test/test_domain_connect.py b/posthog/test/test_domain_connect.pyindex ae726bdeba9e..0d1cc5b72fbb 100644--- a/posthog/test/test_domain_connect.py+++ b/posthog/test/test_domain_connect.py@@ -8,6 +8,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.core.cache import cache+from django.test import SimpleTestCaseimport dns.resolverfrom cryptography.hazmat.primitives import hashes as crypto_hashes@@ -52,7 +53,7 @@ def _extract_template_variables(template: dict) -> set[str]:return variables-class TestExtractRootDomainAndHost(BaseTest):+class TestExtractRootDomainAndHost(SimpleTestCase):@parameterized.expand([("simple subdomain", "ph.example.com", ("example.com", "ph")),@@ -72,7 +73,7 @@ class TestExtractRootDomainAndHost(BaseTest):self.assertEqual(domain_parts.host, expected[1], f"Failed host for {name}: {full_domain}")-class TestGetServiceIdForRegion(BaseTest):+class TestGetServiceIdForRegion(SimpleTestCase):@parameterized.expand([("US deployment", "US", "email-verification-us"),@@ -87,7 +88,7 @@ class TestGetServiceIdForRegion(BaseTest):self.assertEqual(get_service_id_for_region("email-verification"), expected)-class TestBuildSyncApplyUrl(BaseTest):+class TestBuildSyncApplyUrl(SimpleTestCase):def test_basic_url(self) -> None:url = build_sync_apply_url(url_sync_ux="https://dns.provider.example/sync",@@ -169,7 +170,7 @@ class TestBuildSyncApplyUrl(BaseTest):self.assertNotIn("key=", url)-class TestSignQueryString(BaseTest):+class TestSignQueryString(SimpleTestCase):def test_sign_and_verify(self) -> None:private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)public_key = private_key.public_key()@@ -187,7 +188,7 @@ class TestSignQueryString(BaseTest):)-class TestDiscoverDomainConnect(BaseTest):+class TestDiscoverDomainConnect(SimpleTestCase):def setUp(self) -> None:super().setUp()cache.clear()@@ -235,7 +236,7 @@ class TestDiscoverDomainConnect(BaseTest):self.assertIsNone(result)-class TestGetAvailableProviders(BaseTest):+class TestGetAvailableProviders(SimpleTestCase):def test_returns_all_providers(self) -> None:with patch.dict(DOMAIN_CONNECT_PROVIDERS,@@ -256,7 +257,7 @@ class TestGetAvailableProviders(BaseTest):self.assertEqual(providers, [])-class TestGenerateApplyUrl(BaseTest):+class TestGenerateApplyUrl(SimpleTestCase):def test_rejects_unknown_provider_endpoint(self) -> None:with self.assertRaises(ValueError, msg="Unsupported provider endpoint"):generate_apply_url(diff --git a/posthog/test/test_element_model.py b/posthog/test/test_element_model.pyindex 66c1b0dd316d..04484af12805 100644--- a/posthog/test/test_element_model.py+++ b/posthog/test/test_element_model.py@@ -1,6 +1,8 @@from typing import cast-from posthog.test.base import BaseTest, ClickhouseTestMixin+from posthog.test.base import ClickhouseTestMixin++from django.test import SimpleTestCasefrom parameterized import parameterized@@ -9,7 +11,7 @@ from posthog.models.element import Element, chain_to_elements, elements_to_strinfrom posthog.models.element.element import build_attributes_filter, chain_to_element_dicts-class TestElement(ClickhouseTestMixin, BaseTest):+class TestElement(ClickhouseTestMixin, SimpleTestCase):def test_elements_to_string(self) -> None:self.maxDiff = Noneelements_string = elements_to_string(diff --git a/posthog/test/test_event_usage.py b/posthog/test/test_event_usage.pyindex f969b3d70bf0..93b164797da8 100644--- a/posthog/test/test_event_usage.py+++ b/posthog/test/test_event_usage.py@@ -5,6 +5,8 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework.test import APIRequestFactory@@ -284,7 +286,7 @@ class TestReportUserAction(BaseTest):)-class TestGetEventSource(BaseTest):+class TestGetEventSource(SimpleTestCase):@parameterized.expand([("terraform", "posthog/terraform-provider 1.0", EventSource.TERRAFORM),@@ -481,7 +483,7 @@ class TestGetEventSource(BaseTest):assert get_event_source(request) == expected-class TestIsWizardSelfDrivingProgram(BaseTest):+class TestIsWizardSelfDrivingProgram(SimpleTestCase):@parameterized.expand([# Direct wizard → Django: the marker rides on the User-Agent itself.@@ -581,7 +583,7 @@ class TestSignupCrmExclusion(BaseTest):mock_group_identify.assert_not_called()-class TestSanitizeHeaderValue(BaseTest):+class TestSanitizeHeaderValue(SimpleTestCase):@parameterized.expand([("passthrough", "posthog/wizard 1.0", "posthog/wizard 1.0"),diff --git a/posthog/test/test_feature_flag_analytics.py b/posthog/test/test_feature_flag_analytics.pyindex 31ccdf2bad3f..8d1bf2318665 100644--- a/posthog/test/test_feature_flag_analytics.py+++ b/posthog/test/test_feature_flag_analytics.py@@ -17,6 +17,7 @@ from posthog.test.base import (from unittest.mock import MagicMock, patchfrom django.core.cache import cache+from django.test import SimpleTestCasefrom parameterized import parameterized@@ -354,7 +355,6 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):)@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_no_interference_between_different_types_of_new_incoming_increments(self):-mock_capture = MagicMock()team_id = 3other_team_id = 1243@@ -452,7 +452,6 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):)@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_locking_works_for_capture_team_decide_usage(self):-mock_capture = MagicMock()team_id = 3other_team_id = 1243@@ -540,7 +539,6 @@ class TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):)@patch("products.feature_flags.backend.flag_analytics.CACHE_BUCKET_SIZE", 10)def test_locking_in_redis_doesnt_block_new_incoming_increments(self):-mock_capture = MagicMock()team_id = 3other_team_id = 1243@@ -1108,7 +1106,7 @@ class TestEnrichedAnalytics(BaseTest):self.assertEqual(flag.has_enriched_analytics, True)-class TestFindFlagsWithEnrichedAnalyticsTask(BaseTest):+class TestFindFlagsWithEnrichedAnalyticsTask(SimpleTestCase):@patch("products.feature_flags.backend.flag_analytics.find_flags_with_enriched_analytics")def test_logs_and_captures_on_failure_without_reraising(self, mock_find_flags: MagicMock) -> None:mock_find_flags.side_effect = Exception("boom")@@ -1239,7 +1237,7 @@ class TestCachedCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):assert counts == {self.team.id: 2}-class TestFlagKeyFilterSQL(BaseTest):+class TestFlagKeyFilterSQL(SimpleTestCase):def test_falls_back_to_json_extract_when_not_materialized(self):with patch("products.feature_flags.backend.flag_analytics.get_materialized_column_for_property",@@ -1260,7 +1258,7 @@ class TestFlagKeyFilterSQL(BaseTest):assert "JSONExtractString" not in sql-class TestEnrichedFlagKeyExprSQL(BaseTest):+class TestEnrichedFlagKeyExprSQL(SimpleTestCase):def test_falls_back_to_json_extract_when_not_materialized(self):with patch("products.feature_flags.backend.flag_analytics.get_materialized_column_for_property",diff --git a/posthog/test/test_geoip.py b/posthog/test/test_geoip.pyindex 07285f9d2372..3a941002d9f0 100644--- a/posthog/test/test_geoip.py+++ b/posthog/test/test_geoip.py@@ -1,12 +1,13 @@-from posthog.test.base import BaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom posthog.geoip import _lookup_location, get_geoip_location-class TestGeoipLocation(BaseTest):+class TestGeoipLocation(SimpleTestCase):def setUp(self):super().setUp()# Lookups are memoized per process, so results would otherwise leak across tests that mockdiff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex b74aa7d27459..dfd971818e71 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -2367,7 +2367,7 @@ class TestActivityLoggingMiddleware(APIBaseTest):assert verification_counts() == expected_counts-class TestSocialAuthExceptionMiddleware(APIBaseTest):+class TestSocialAuthExceptionMiddleware(SimpleTestCase):CONFIG_AUTO_LOGIN = Falsedef setUp(self):@@ -2808,7 +2808,7 @@ def test_query_time_counting_middleware_should_instrument(path, expected) -> Nonassert middleware._should_instrument(request) is expected-class TestPerRequestLoggingContextMiddlewareMcpHeaders(APIBaseTest):+class TestPerRequestLoggingContextMiddlewareMcpHeaders(SimpleTestCase):"""Covers MCP session header binding inside `per_request_logging_context_middleware`."""def _run_middleware(self, **headers):diff --git a/posthog/test/test_products.py b/posthog/test/test_products.pyindex b0fe54358b70..f1b74c9d0558 100644--- a/posthog/test/test_products.py+++ b/posthog/test/test_products.py@@ -1,11 +1,11 @@-from posthog.test.base import BaseTest+from django.test import SimpleTestCasefrom posthog.schema import ProductKeyfrom posthog.products import Products-class TestProducts(BaseTest):+class TestProducts(SimpleTestCase):def test_products_returns_list(self):products = Products.products()assert isinstance(products, list)diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.pyindex ca3391e1040a..53ee6990fc67 100644--- a/posthog/test/test_rate_limit.py+++ b/posthog/test/test_rate_limit.py@@ -906,7 +906,7 @@ class _PSAKThrottleForTest(rate_limit.PersonalOrProjectSecretApiKeyRateThrottle)rate = "100/minute"-class TestPersonalOrProjectSecretApiKeyRateThrottle(APIBaseTest):+class TestPersonalOrProjectSecretApiKeyRateThrottle(SimpleTestCase):def _psak_request(self, key_id=1):auth = ProjectSecretAPIKeyAuthentication()auth.project_secret_api_key = Mock(id=key_id)@@ -1026,7 +1026,7 @@ class _PSAKTeamThrottleForTest(rate_limit.ProjectSecretApiKeyTeamRateThrottle):rate = "100/minute"-class TestProjectSecretApiKeyTeamRateThrottle(APIBaseTest):+class TestProjectSecretApiKeyTeamRateThrottle(SimpleTestCase):def _psak_request(self, team_id=7):auth = ProjectSecretAPIKeyAuthentication()auth.project_secret_api_key = Mock(team_id=team_id)diff --git a/posthog/test/test_renderers.py b/posthog/test/test_renderers.pyindex 3e6522081ac5..5a616bde265a 100644--- a/posthog/test/test_renderers.py+++ b/posthog/test/test_renderers.py@@ -1,11 +1,11 @@import json-from django.test import TestCase+from django.test import SimpleTestCasefrom posthog.renderers import SafeJSONRenderer-class TestCleanDataForJSON(TestCase):+class TestCleanDataForJSON(SimpleTestCase):def test_cleans_dict_with_nan_and_inf_scalars(self):response = {"control": 1.0,diff --git a/posthog/test/test_sampling.py b/posthog/test/test_sampling.pyindex d1f15e72743d..f15a11a942ea 100644--- a/posthog/test/test_sampling.py+++ b/posthog/test/test_sampling.py@@ -1,9 +1,9 @@-from django.test import TestCase+from django.test import SimpleTestCasefrom posthog.sampling import clamp_to_range, sample_on_property, simple_hash-class TestSampling(TestCase):+class TestSampling(SimpleTestCase):def test_simple_hash_function(self):assert simple_hash("test") == simple_hash("test")assert simple_hash("test1") != simple_hash("test2")