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): avoid database setup in auth, billing, and related tests (part 1) (#116237)

Paul D'Ambracd7050720297
diff --git a/ee/api/agentic_provisioning/test/test_region_proxy.py b/ee/api/agentic_provisioning/test/test_region_proxy.py
index 71a744578b98..9d0a46124ec7 100644
--- a/ee/api/agentic_provisioning/test/test_region_proxy.py
+++ b/ee/api/agentic_provisioning/test/test_region_proxy.py
@@ -1,9 +1,8 @@
-from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.http import JsonResponse
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework.parsers import JSONParser
@@ -28,7 +27,7 @@ def _make_drf_request(data=None):
return Request(raw, parsers=[JSONParser()])
-class TestShouldProxyBodyRegion(BaseTest):
+class TestShouldProxyBodyRegion(SimpleTestCase):
def test_proxies_on_region_mismatch(self):
request = _make_drf_request({"configuration": {"region": "EU"}})
assert _should_proxy_body_region(request, "US") is True
@@ -55,7 +54,7 @@ class TestShouldProxyBodyRegion(BaseTest):
assert _should_proxy_body_region(request2, "US") is False
-class TestShouldProxyTokenLookup(BaseTest):
+class TestShouldProxyTokenLookup(SimpleTestCase):
def setUp(self):
super().setUp()
cache.clear()
@@ -89,7 +88,7 @@ class TestShouldProxyTokenLookup(BaseTest):
assert _should_proxy_token_lookup(request, "US") is False
-class TestShouldProxyBearerLookup(BaseTest):
+class TestShouldProxyBearerLookup(SimpleTestCase):
def setUp(self):
super().setUp()
cache.clear()
@@ -155,7 +154,7 @@ class TestShouldProxyBearerLookup(BaseTest):
assert _should_proxy_bearer_lookup(req_unknown, "US") is True
-class TestProxyHeaderAllowlist(BaseTest):
+class TestProxyHeaderAllowlist(SimpleTestCase):
@patch("ee.api.agentic_provisioning.region_proxy.requests")
def test_strips_cookies_and_carries_the_caller_address(self, mock_requests):
mock_response = MagicMock()
@@ -333,7 +332,7 @@ class TestRegionProxyThrottle(ProvisioningTestBase):
assert body["error"]["code"] == "rate_limited"
-class TestRegionProxyCoverageContract(BaseTest):
+class TestRegionProxyCoverageContract(SimpleTestCase):
"""Catches forgotten ``region_proxy_strategy`` on bearer-auth endpoints.
If you add a new endpoint that accepts a bearer access token, either declare
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.py
index 4313d7fd0fa5..9d78af867698 100644
--- a/ee/api/test/test_billing.py
+++ b/ee/api/test/test_billing.py
@@ -2699,7 +2699,7 @@ class TestBillingPermissionDeniedForMembers(APILicensedTest):
)
-class TestResolveTeamLabels(APIBaseTest):
+class TestResolveTeamLabels(SimpleTestCase):
"""Project names are put into labels on the way out, not sent in with the request.
Billing keys usage by project id. An id-to-name map on every request would be about 16KB
@@ -2825,7 +2825,7 @@ class TestExportGzip(APILicensedTest):
upstream.close.assert_called_once()
-class TestExportStreaming(APIBaseTest):
+class TestExportStreaming(SimpleTestCase):
"""Django 5 under ASGI consumes a synchronous streaming body in full before it sends a byte,
so a large export would arrive all at once at the end. The proxy hands Django an
asynchronous iterator, so the first chunk goes out before the last is read from billing."""
@@ -2862,7 +2862,7 @@ class TestExportStreaming(APIBaseTest):
upstream.close.assert_called_once()
-class TestRewriteCsvLabels(APIBaseTest):
+class TestRewriteCsvLabels(SimpleTestCase):
"""Project names go into an exported CSV as it streams past, in place of ids.
Billing has no names, so its Project column carries the id, and the proxy substitutes the
diff --git a/ee/billing/test/test_billing_consumer.py b/ee/billing/test/test_billing_consumer.py
index 82aa9d7b6fe7..7787a212960d 100644
--- a/ee/billing/test/test_billing_consumer.py
+++ b/ee/billing/test/test_billing_consumer.py
@@ -1,6 +1,8 @@
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from posthog.models import Organization, User
@@ -11,7 +13,7 @@ from ee.billing.queue.BillingConsumer import POSTHOG_SELF_TEAM_ID, BillingConsum
CONSUMER = "ee.billing.queue.BillingConsumer"
-class TestBillingConsumerUsageSpike(BaseTest):
+class TestBillingConsumerUsageSpike(SimpleTestCase):
def _build_consumer(self) -> BillingConsumer:
with patch("ee.sqs.SQSConsumer.boto3"):
return BillingConsumer(queue_url="http://example/queue", region_name="us-east-1")
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index d983b390fb89..d3503218d3c9 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -1676,7 +1676,7 @@ class TestUserUpdateBillingOrganizationUsers(BaseTest):
assert capture_kwargs["properties"]["target_email"] == member.email
-class TestParamSerialization(BaseTest):
+class TestParamSerialization(SimpleTestCase):
@parameterized.expand(
[
("teams_map", {"1": "Team A", "2": "Team B"}, '{"1": "Team A", "2": "Team B"}'),
diff --git a/ee/billing/test/test_quota_limiting.py b/ee/billing/test/test_quota_limiting.py
index b014a4d2605f..bdc6c65313ae 100644
--- a/ee/billing/test/test_quota_limiting.py
+++ b/ee/billing/test/test_quota_limiting.py
@@ -8,7 +8,7 @@ from unittest.mock import patch
from django.apps import apps
from django.db import DatabaseError
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
from django.utils.timezone import now
@@ -2383,7 +2383,7 @@ _PERIOD = ["2021-01-01T00:00:00Z", "2021-01-31T23:59:59Z"]
@override_settings(CLOUD_DEPLOYMENT="US")
-class TestIdentifyRefreshCandidates(BaseTest):
+class TestIdentifyRefreshCandidates(SimpleTestCase):
"""Isolated unit coverage for `_identify_refresh_candidates`. The cron-loop
integration tests above also exercise this function but conflate it with the rest
of the run; these cases cover each candidate-selection branch in isolation."""
diff --git a/ee/billing/test/test_usage_signals.py b/ee/billing/test/test_usage_signals.py
index 4c81e89f022b..ad31e430c4c1 100644
--- a/ee/billing/test/test_usage_signals.py
+++ b/ee/billing/test/test_usage_signals.py
@@ -1,7 +1,7 @@
from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import patch
-from django.test import TestCase
+from django.test import SimpleTestCase, TestCase
from posthog.models import Organization
from posthog.models.group.util import create_group
@@ -13,7 +13,7 @@ from ee.billing.salesforce_enrichment.usage_signals import (
)
-class TestUsageSignalsDataClass(TestCase):
+class TestUsageSignalsDataClass(SimpleTestCase):
def test_default_values(self):
signals = UsageSignals()
@@ -48,7 +48,7 @@ class TestUsageSignalsDataClass(TestCase):
assert signals.events_30d_momentum == -5.0
-class TestFetchUsageSignalsFromGroups(TestCase):
+class TestFetchUsageSignalsFromGroups(SimpleTestCase):
@patch("ee.billing.salesforce_enrichment.usage_signals.query_with_columns")
def test_returns_parsed_signals(self, mock_query):
mock_query.return_value = [
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index 700d4fd76b7e..c2b06c8dacd6 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -180,7 +180,7 @@ def test_validate_cimd_url_ssrf_blocked(mock_return, url, expected_error):
@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("93.184.216.34")})
-class TestFetchCimdMetadata(APIBaseTest):
+class TestFetchCimdMetadata(SimpleTestCase):
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_success(self, mock_get, _url_mock):
metadata = _make_metadata()
diff --git a/posthog/api/test/test_csp.py b/posthog/api/test/test_csp.py
index 3b8f76075dee..2c240375af65 100644
--- a/posthog/api/test/test_csp.py
+++ b/posthog/api/test/test_csp.py
@@ -5,7 +5,7 @@ from html import escape
import time_machine
from unittest.mock import patch
-from django.test import SimpleTestCase, TestCase
+from django.test import SimpleTestCase
from django.test.client import RequestFactory
from parameterized import parameterized
@@ -20,7 +20,7 @@ from posthog.api.csp import (
from posthog.sampling import sample_on_property
-class TestCSPModule(TestCase):
+class TestCSPModule(SimpleTestCase):
def setUp(self):
self.factory = RequestFactory()
diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.py
index fbef59736716..8f1d2bc559bf 100644
--- a/posthog/api/test/test_proxy_record_diagnostics.py
+++ b/posthog/api/test/test_proxy_record_diagnostics.py
@@ -3,7 +3,7 @@ from dataclasses import replace
from unittest.mock import MagicMock, patch
-from django.test import TestCase, override_settings
+from django.test import SimpleTestCase, TestCase, override_settings
import requests
import dns.resolver
@@ -66,7 +66,7 @@ def _caa_rdata(tag: bytes, issuer: str):
return rd
-class TestCheckCname(TestCase):
+class TestCheckCname(SimpleTestCase):
@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
def test_pass_when_cname_matches(self, ResolverMock):
cname = MagicMock()
@@ -101,7 +101,7 @@ class TestCheckCname(TestCase):
self.assertIn("doesn't have a CNAME", result.detail)
-class TestCheckCloudflare(TestCase):
+class TestCheckCloudflare(SimpleTestCase):
@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
def test_pass_when_ssl_active(self, get_mock):
get_mock.return_value = _hostname_info(ssl_status=CustomHostnameSSLStatus.ACTIVE)
@@ -179,7 +179,7 @@ class TestCheckCloudflare(TestCase):
self.assertIn("domain", props)
-class TestCheckCaa(TestCase):
+class TestCheckCaa(SimpleTestCase):
@patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
def test_pass_when_no_caa_records(self, ResolverMock):
ResolverMock.return_value.resolve.side_effect = dns.resolver.NoAnswer()
@@ -215,7 +215,7 @@ class TestCheckCaa(TestCase):
self.assertIn("letsencrypt.org", result.detail)
-class TestCheckHttpChallenge(TestCase):
+class TestCheckHttpChallenge(SimpleTestCase):
@patch("posthog.api.proxy_record_diagnostics.requests.get")
def test_pass_when_body_matches(self, get_mock):
get_mock.return_value = MagicMock(status_code=200, text="tok.body")
@@ -245,7 +245,7 @@ class TestCheckHttpChallenge(TestCase):
self.assertIn("404", result.detail)
-class TestCheckLiveEvent(TestCase):
+class TestCheckLiveEvent(SimpleTestCase):
@parameterized.expand(
[
("ssl_error", requests.exceptions.SSLError("bad cert"), "failed", "tls"),
@@ -366,7 +366,7 @@ class TestCheckCertExpiry(TestCase):
self.assertEqual(result.status, "warned")
-class TestIsValidProxyDomain(TestCase):
+class TestIsValidProxyDomain(SimpleTestCase):
@parameterized.expand(
[
("plain", "e.example.com"),
@@ -408,7 +408,7 @@ class TestIsValidProxyDomain(TestCase):
self.assertFalse(is_valid_proxy_domain(domain))
-class TestIsReservedProxyDomain(TestCase):
+class TestIsReservedProxyDomain(SimpleTestCase):
@parameterized.expand(
[
("apex", "posthog.com"),
diff --git a/posthog/api/test/test_toolbar_oauth_endpoint_auth.py b/posthog/api/test/test_toolbar_oauth_endpoint_auth.py
index 490d284ed71f..7b106a00d17e 100644
--- a/posthog/api/test/test_toolbar_oauth_endpoint_auth.py
+++ b/posthog/api/test/test_toolbar_oauth_endpoint_auth.py
@@ -13,6 +13,7 @@ from datetime import timedelta
from posthog.test.base import APIBaseTest
from django.conf import settings
+from django.test import SimpleTestCase
from django.utils import timezone
from parameterized import parameterized
@@ -337,7 +338,7 @@ class TestHedgehogConfigOAuthAuth(APIBaseTest):
assert response.status_code in (401, 403)
-class TestToolbarOAuthScopesConfig(APIBaseTest):
+class TestToolbarOAuthScopesConfig(SimpleTestCase):
"""Verify TOOLBAR_OAUTH_SCOPES covers every toolbar endpoint scope."""
EXPECTED_SCOPES = [
diff --git a/posthog/api/test/test_toolbar_oauth_primitives.py b/posthog/api/test/test_toolbar_oauth_primitives.py
index f2336bafd023..2d23f56da054 100644
--- a/posthog/api/test/test_toolbar_oauth_primitives.py
+++ b/posthog/api/test/test_toolbar_oauth_primitives.py
@@ -6,7 +6,8 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.conf import settings
-from django.test import override_settings
+from django.core.cache import cache
+from django.test import SimpleTestCase, override_settings
import requests
from parameterized import parameterized
@@ -106,7 +107,11 @@ class TestToolbarOAuthPrimitives(APIBaseTest):
assert first.client_id == second.client_id
-class TestToolbarOAuthStateCache(APIBaseTest):
+class TestToolbarOAuthStateCache(SimpleTestCase):
+ def setUp(self):
+ super().setUp()
+ cache.clear()
+
def test_mark_pending_then_claim_succeeds(self):
nonce = "test-nonce-claim-ok"
toolbar_oauth_state_cache.mark_pending(nonce)
@@ -281,7 +286,7 @@ class TestToolbarOAuthRefresh(APIBaseTest):
assert response.status_code == 429
-class TestTokenEndpointStatusRemapping(APIBaseTest):
+class TestTokenEndpointStatusRemapping(SimpleTestCase):
@parameterized.expand(
[
("401_becomes_400", 401, 400),
diff --git a/posthog/management/commands/test/test_analyze_migration_risk.py b/posthog/management/commands/test/test_analyze_migration_risk.py
index 503cc1da58dc..e23d31b2c864 100644
--- a/posthog/management/commands/test/test_analyze_migration_risk.py
+++ b/posthog/management/commands/test/test_analyze_migration_risk.py
@@ -2,10 +2,10 @@ from io import StringIO
from unittest.mock import patch
-from django.test import TestCase
+from django.test import SimpleTestCase
-class TestAnalyzeMigrationRisk(TestCase):
+class TestAnalyzeMigrationRisk(SimpleTestCase):
def test_check_missing_migrations_when_none_needed(self):
"""Should return empty string when no migrations are needed."""
from posthog.management.commands.analyze_migration_risk import Command
diff --git a/posthog/models/test/integration/test_oauth.py b/posthog/models/test/integration/test_oauth.py
index 52c8b35ad349..0395171b3e6c 100644
--- a/posthog/models/test/integration/test_oauth.py
+++ b/posthog/models/test/integration/test_oauth.py
@@ -15,7 +15,7 @@ from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.db import connection
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
import jwt
import requests
@@ -1645,7 +1645,7 @@ class TestPardotIntegrationModel(BaseTest):
YOUTUBE_ANALYTICS_APP_CLIENT_ID="youtube-client-id",
YOUTUBE_ANALYTICS_APP_CLIENT_SECRET="youtube-client-secret",
)
-class TestYouTubeAnalyticsIntegrationModel(BaseTest):
+class TestYouTubeAnalyticsIntegrationModel(SimpleTestCase):
def test_oauth_config(self):
config = OauthIntegration.oauth_config_for_kind("youtube-analytics")
diff --git a/posthog/storage/test/test_gateway_credential_cache.py b/posthog/storage/test/test_gateway_credential_cache.py
index 6119fc4fb366..4dbf3cd7de44 100644
--- a/posthog/storage/test/test_gateway_credential_cache.py
+++ b/posthog/storage/test/test_gateway_credential_cache.py
@@ -10,7 +10,7 @@ from unittest.mock import patch
from django.conf import settings
from django.db import IntegrityError, transaction
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -245,7 +245,7 @@ class TestGatewayCredentialWireShape(GatewayCredentialTestMixin):
self.assertEqual(GATEWAY_KNOWN_TIERS, {"free", "pro", "enterprise"})
-class TestOverspendAllowanceFormatting(BaseTest):
+class TestOverspendAllowanceFormatting(SimpleTestCase):
@parameterized.expand(
[
("whole", Decimal("5"), "5.000000"),
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 8e8655e2f05d..83f97b8804bb 100644
--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
@@ -1,17 +1,4 @@
-ee/api/agentic_provisioning/test/test_region_proxy.py::TestProxyHeaderAllowlist
-ee/api/agentic_provisioning/test/test_region_proxy.py::TestRegionProxyCoverageContract
-ee/api/agentic_provisioning/test/test_region_proxy.py::TestShouldProxyBearerLookup
-ee/api/agentic_provisioning/test/test_region_proxy.py::TestShouldProxyBodyRegion
-ee/api/agentic_provisioning/test/test_region_proxy.py::TestShouldProxyTokenLookup
-ee/api/test/test_billing.py::TestExportStreaming
-ee/api/test/test_billing.py::TestResolveTeamLabels
-ee/api/test/test_billing.py::TestRewriteCsvLabels
ee/api/vercel/test/test_vercel_connect.py::TestValidateNextUrl
-ee/billing/test/test_billing_consumer.py::TestBillingConsumerUsageSpike
-ee/billing/test/test_billing_manager.py::TestParamSerialization
-ee/billing/test/test_quota_limiting.py::TestIdentifyRefreshCandidates
-ee/billing/test/test_usage_signals.py::TestFetchUsageSignalsFromGroups
-ee/billing/test/test_usage_signals.py::TestUsageSignalsDataClass
ee/clickhouse/materialized_columns/test/test_analyze.py::TestMaterializedColumnsAnalyze
ee/clickhouse/models/test/test_dead_letter_queue.py::TestDeadLetterQueue
ee/clickhouse/models/test/test_property.py::TestPropDenormalized
@@ -22,18 +9,6 @@ posthog/admin/test_admin.py::TestOAuthSidebarRegrouping
posthog/admin/test_admin.py::TestOrganizationMemberInlineConfig
posthog/admin/test_admin.py::TestPluginAttachmentInline
posthog/api/oauth/test_cimd.py::TestAuthorizationServerMetadata
-posthog/api/oauth/test_cimd.py::TestFetchCimdMetadata
-posthog/api/test/test_csp.py::TestCSPModule
-posthog/api/test/test_proxy_record_diagnostics.py::TestCheckCaa
-posthog/api/test/test_proxy_record_diagnostics.py::TestCheckCloudflare
-posthog/api/test/test_proxy_record_diagnostics.py::TestCheckCname
-posthog/api/test/test_proxy_record_diagnostics.py::TestCheckHttpChallenge
-posthog/api/test/test_proxy_record_diagnostics.py::TestCheckLiveEvent
-posthog/api/test/test_proxy_record_diagnostics.py::TestIsReservedProxyDomain
-posthog/api/test/test_proxy_record_diagnostics.py::TestIsValidProxyDomain
-posthog/api/test/test_toolbar_oauth_endpoint_auth.py::TestToolbarOAuthScopesConfig
-posthog/api/test/test_toolbar_oauth_primitives.py::TestTokenEndpointStatusRemapping
-posthog/api/test/test_toolbar_oauth_primitives.py::TestToolbarOAuthStateCache
posthog/caching/test/test_redis_cluster_keys.py::TestRedisClusterKeySlots
posthog/clickhouse/client/test/test_limit.py::TestRateLimit
posthog/clickhouse/test/test_deletion_coverage.py::TestDeletionCoverage
@@ -53,17 +28,14 @@ posthog/hogql_queries/legacy_compatibility/test/test_clean_properties.py::TestCl
posthog/hogql_queries/utils/test/test_formula_ast.py::TestFormulaAST
posthog/hogql_queries/utils/test/test_sampling.py::TestQueriesUtil
posthog/kafka_client/test/test_client.py::KafkaClientRoundtripTestCase
-posthog/management/commands/test/test_analyze_migration_risk.py::TestAnalyzeMigrationRisk
posthog/management/commands/test/test_base_hypercache_command.py::TestVerificationResultsErrorReporting
posthog/management/commands/test/test_survey_cohort_bytecode_stl.py::TestBytecodeWalker
-posthog/models/test/integration/test_oauth.py::TestYouTubeAnalyticsIntegrationModel
posthog/models/tophog/test/test_tophog_queries.py::TestTopHogQueries
posthog/personhog_client/test_interceptor.py::TestClientNameInterceptor
posthog/personhog_client/test_interceptor.py::TestConsistencyHeaderInterceptor
posthog/personhog_client/test_interceptor.py::TestWithMetadata
posthog/session_recordings/test/test_session_recording_throttle.py::TestSharingTokenReplayThrottle
posthog/session_recordings/test/test_session_recording_throttle.py::TestTierAwareListingThrottle
-posthog/storage/test/test_gateway_credential_cache.py::TestOverspendAllowanceFormatting
posthog/tasks/test/test_auth_token_cache_verification.py::TestVerifyAndFixAuthTokenCacheTask
posthog/tasks/test/test_auth_token_cache_verification.py::TestVerifyAndFixAuthTokenCacheTaskDisabled
posthog/tasks/test/test_usage_report.py::TestSendNoUsage