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): ratchet test classes that take a database they never use (#97837)

Paul D'Ambrad704897147ac
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
index ae7c84536340..7cfdc9930b8d 100644
--- a/.agents/skills/writing-tests/SKILL.md
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -3,7 +3,7 @@ name: writing-tests
description: >
Gates whether a new test should exist and forces it to be efficient, protecting CI from low-value test bloat.
Use before any change to what a pytest, Jest, or Playwright test asserts or sets up, down to one fixture or one assertion added to an existing block.
- Front-loads the value bar (every test must catch a realistic regression no existing test already catches; extend the nearest existing test before writing a new standalone one; test behavior through the public interface, not implementation details; collapse near-duplicates into parameterized cases) and the efficiency bar (deterministic, isolated, fast; pick the cheapest test level; Django TestCase over TransactionTestCase; no sleeps, no real network; no time bombs from absolute dates left to age against the real clock).
+ Front-loads the value bar (every test must catch a realistic regression no existing test already catches; extend the nearest existing test before writing a new standalone one; test behavior through the public interface, not implementation details; collapse near-duplicates into parameterized cases) and the efficiency bar (deterministic, isolated, fast; pick the cheapest test level; Django TestCase over TransactionTestCase; no sleeps, no real network; no time bombs from absolute dates left to age against the real clock; no database a test never uses).
Includes a "don't write it" decision tree. For fixing an existing flaky test use `/fixing-flaky-tests`; after this gate says a Playwright test is warranted, use `/playwright-test` for mechanics.
---
@@ -112,6 +112,7 @@ Escalating to the next rung is the last resort, not the default.
- testing `transaction.on_commit` side effects → use `TestCase` + `self.captureOnCommitCallbacks(execute=True)`.
- needing a connection visible across a real separate thread (`thread_sensitive`) → `async_to_sync(...)`, not `asyncio.run(...)`.
Use `TransactionTestCase` only when the regression genuinely requires committed transaction boundaries that `TestCase` hides.
+- **A test class only takes a database it uses.** `BaseTest` and `APIBaseTest` inherit Django `TestCase`, so a class on either one needs a database to run: `setUpTestData` writes an organization, a project, a team and a user for it, and every test method runs inside a transaction. A class of pure assertions pays all of that and reads no row. Put those cases on `django.test.SimpleTestCase`, which refuses database access and therefore proves they never needed one. The `posthog/test/repo_invariants/test_database_free_test_classes.py` ratchet enforces it: it holds the frozen list of the classes already here, and fails the pull request that adds another. When it trips, [references/database-free-test-classes.md](references/database-free-test-classes.md) covers what the failure means, the three ways to answer it, and how to regenerate the baseline.
- **Dedicated data migration tests are temporary.** Remove a dedicated test after every supported environment has applied the migration, the rollback window has closed, and no supported upgrade relies on the old data state. Delete the expired test instead of marking it skipped. Keep the migration file and tests for migration tooling, safety checks, reusable backfill systems, and backfills people can still run. Use `/django-migrations` for the migration safety workflow.
- **DRF input-validation belongs in a `SimpleTestCase`, not an `APIBaseTest` round-trip.**
A test that posts a malformed body to an endpoint and asserts a 400 pays for `APIBaseTest` to build an Organization + Team + User in Postgres and wrap the test in a transaction — just to exercise validation that runs entirely in memory.
diff --git a/.agents/skills/writing-tests/references/database-free-test-classes.md b/.agents/skills/writing-tests/references/database-free-test-classes.md
new file mode 100644
index 000000000000..6f6cd379b335
--- /dev/null
+++ b/.agents/skills/writing-tests/references/database-free-test-classes.md
@@ -0,0 +1,74 @@
+# A test class that takes a database it never uses
+
+`BaseTest`, `APIBaseTest`, and `NonAtomicBaseTest` inherit Django `TestCase`.
+A class on one of them needs a database to run.
+`setUpTestData` writes an organization, a project, a team and a user for the class, and every test method runs inside a transaction that is rolled back afterwards.
+A class that only asserts on constants and pure functions pays all of that and reads no row.
+The base class is the whole difference: on `django.test.SimpleTestCase` the same assertions need no database at all, so the file runs anywhere, including a checkout with no test database.
+
+## The check
+
+`posthog/test/repo_invariants/test_database_free_test_classes.py`, with its list in `database_free_test_classes_baseline.txt`.
+
+It scans the repo on every backend pull request in the `repo-checks` job and compares what it finds against the frozen list, so the count can fall but never rise.
+
+It reads each class body for any name that reaches the database, so it cannot see a call several helper levels down.
+A class it misses stays missed, which is the safe error.
+It also leaves out two kinds of class, because the fix below would be wrong for them: a class the repo inherits from somewhere, whose own body names nothing while every subclass reaches the database, and a class with no test method of its own, which is infrastructure rather than a test.
+
+What a failure looks like: `database_free_test_classes_baseline.txt no longer matches the repo`, followed by `+` lines for classes the branch added and `-` lines for classes it removed.
+
+## What to do when it trips
+
+Work out which of three cases you are in.
+
+**The class really needs no database.**
+This is the common case, and the fix is the base class:
+
+```python
+from django.test import SimpleTestCase
+
+class TestScopeRules(SimpleTestCase):
+ def test_write_downgrades_to_read(self) -> None:
+ assert downgrade_scopes_to_read_only("x:write") == "x:read"
+```
+
+`SimpleTestCase` refuses database access outright, so a passing run is proof the class never needed one.
+Run the class before you believe it.
+
+**The class needs a database through a helper the check cannot see.**
+It reads the class body only, so a fixture built inside an imported helper is invisible to it.
+Keep the base class and keep the class's baseline line, in the same change.
+
+Say what the helper does when you explain it in review.
+"It needs the database" repeats the code; "`seed_billing_fixtures()` writes the plan rows" tells the next reader where to look.
+
+**The class only touches the database in part of its cases.**
+Split it.
+Move the pure cases to a `SimpleTestCase` class and leave the rest on `BaseTest`.
+That takes the pure cases off the database without weakening the rest, and it is usually the honest shape when a class has grown two jobs.
+
+## Regenerating the baseline
+
+Only to ratchet down, or after a rename or a move:
+
+```sh
+python posthog/test/repo_invariants/test_database_free_test_classes.py
+```
+
+The file records removals as well as additions, so a class you fixed has to leave the list in the same change.
+That is what stops the file going stale behind the code.
+
+## Writing a new test class
+
+Pick the base from what the test actually reads:
+
+| The class needs | Base |
+| ------------------------------------ | ------------------------------- |
+| nothing from Django but its settings | `django.test.SimpleTestCase` |
+| no framework at all | `unittest.TestCase` |
+| an org, team, or user fixture | `posthog.test.base.BaseTest` |
+| an authenticated API round trip | `posthog.test.base.APIBaseTest` |
+
+Reach up that list only when the regression you named in the gate genuinely lives there.
+A serializer's field validation, a pure transformation, and a set of constants all belong on the first two rows.
diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
new file mode 100644
index 000000000000..f74a94883167
--- /dev/null
+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
@@ -0,0 +1,418 @@
+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_salesforce_enrichment.py::TestDomainExclusion
+ee/billing/test/test_salesforce_enrichment.py::TestExtractDomain
+ee/billing/test/test_salesforce_enrichment.py::TestHarmonicDataTransformation
+ee/billing/test/test_salesforce_enrichment.py::TestSalesforceAccountQuery
+ee/billing/test/test_salesforce_enrichment.py::TestSpecificDomainEnrichment
+ee/billing/test/test_salesforce_enrichment.py::TestValuesMatch
+ee/billing/test/test_salesforce_enrichment.py::TestYCCompanyDetection
+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
+ee/hogai/chat_agent/funnels/test/test_toolkit.py::TestFunnelToolkit
+ee/hogai/chat_agent/memory/test/test_parsers.py::TestParsers
+ee/hogai/chat_agent/query_planner/test/test_toolkit.py::TestFinalAnswerTool
+ee/hogai/chat_agent/retention/test/test_toolkit.py::TestRetentionToolkit
+ee/hogai/chat_agent/taxonomy/test/test_nodes.py::TestPropertyTypesPrompt
+ee/hogai/chat_agent/taxonomy/test/test_tools.py::TestDynamicEntityTools
+ee/hogai/chat_agent/taxonomy/test/test_tools.py::TestFinalAnswerModel
+ee/hogai/chat_agent/trends/test/test_toolkit.py::TestTrendsToolkit
+ee/hogai/context/insight/format/test/test_lifecycle.py::TestLifecycleResultsFormatter
+ee/hogai/context/insight/format/test/test_paths.py::TestPathsResultsFormatter
+ee/hogai/context/insight/format/test/test_retention.py::TestRetentionResultsFormatter
+ee/hogai/context/insight/format/test/test_sql.py::TestSQLResultsFormatter
+ee/hogai/context/insight/format/test/test_stickiness.py::TestStickinessResultsFormatter
+ee/hogai/context/insight/format/test/test_utils.py::TestFormatUtils
+ee/hogai/context/insight/test/test_query_executor.py::TestValidateAssistantQuery
+ee/hogai/core/plan_mode/test/test_executables.py::TestSupermodeReducer
+ee/hogai/core/test/test_artifacts.py::TestDocumentArtifactContent
+ee/hogai/core/test/test_artifacts.py::TestDocumentBlocks
+ee/hogai/core/test/test_artifacts.py::TestVisualizationArtifactContent
+ee/hogai/core/test/test_base_callback_handlers.py::TestSubagentCallbackHandler
+ee/hogai/core/test/test_dispatcher_integration.py::TestDispatcherIntegration
+ee/hogai/research_agent/test/test_runner.py::TestResearchAgentRunnerConfiguration
+ee/hogai/stream/test/test_redis_stream.py::TestGetSubagentStreamKey
+ee/hogai/summarizers/test/test_property_filters.py::TestPropertyFilterCollectionDescriber
+ee/hogai/summarizers/test/test_property_filters.py::TestPropertyFilterDescriber
+ee/hogai/test/test_registry.py::TestToolRegistry
+ee/hogai/test/test_schema.py::TestSchema
+ee/hogai/test/test_tool.py::TestMaxToolAccessDeniedError
+ee/hogai/test/test_tool.py::TestMaxToolErrorHierarchy
+ee/hogai/test/test_utils.py::TestTrendsUtils
+ee/hogai/tools/create_notebook/test/test_parsing.py::TestParseNotebookContentForStorageWithTitle
+ee/hogai/tools/create_notebook/test/test_parsing.py::TestStripIncompleteInsightTags
+ee/hogai/tools/create_notebook/test/test_parsing.py::TestStripTitleHeading
+ee/hogai/tools/test/test_todo_write.py::TestTodoWriteTool
+ee/hogai/utils/test/test_anthropic.py::TestAnthropicUtils
+ee/hogai/utils/test/test_assistant_helpers.py::TestAssistantHelpers
+ee/hogai/utils/test/test_assistant_helpers.py::TestConvertToolMessagesToDict
+ee/hogai/utils/test/test_assistant_helpers.py::TestExtractThinkingFromAIMessage
+ee/hogai/utils/test/test_assistant_helpers.py::TestNormalizeAIMessage
+ee/hogai/utils/test/test_assistant_helpers.py::TestNormalizeAIMessageWebSearch
+ee/hogai/utils/test/test_assistant_helpers.py::TestNormalizeAiMessageStripsHandles
+ee/hogai/utils/test/test_assistant_types.py::TestAssistantTypes
+ee/hogai/utils/test/test_assistant_types.py::TestIsVisualizationArtifactMessage
+ee/hogai/utils/test/test_assistant_types.py::TestUnwrapVisualizationArtifactContent
+ee/hogai/utils/test/test_dispatcher.py::TestDispatcherIntegration
+ee/hogai/utils/test/test_openai.py::TestOpenAIUtils
+ee/partners/stripe/api/provisioning/test/test_services_catalog.py::TestServicesCatalog
+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_comment_slack_sync.py::TestDiscussionCardBlocks
+posthog/api/test/test_comment_slack_sync.py::TestEscapeSlackMrkdwn
+posthog/api/test/test_comments.py::TestCommentHelperFunctions
+posthog/api/test/test_csp.py::TestCSPModule
+posthog/api/test/test_event_definition_base.py::TestEventDefinitionGeneratorBase
+posthog/api/test/test_event_definition_typescript.py::TestTypeScriptGeneratorOptionalInTypes
+posthog/api/test/test_github.py::TestRelayToEu
+posthog/api/test/test_mixins.py::TestValidatedRequestDecorator
+posthog/api/test/test_organization_domain.py::TestOrganizationDomains
+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_team_project_parity.py::TestTeamProjectParity
+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/api/test/test_user_integration.py::TestGithubUserFromCode
+posthog/caching/test/test_redis_cluster_keys.py::TestRedisClusterKeySlots
+posthog/caching/test/test_zstd_compressor.py::TestZstdCompressor
+posthog/cdp/templates/avo/test_template_avo.py::TestTemplateMigration
+posthog/cdp/templates/customerio/test_template_customerio.py::TestTemplateMigration
+posthog/cdp/templates/hubspot/test_template_hubspot.py::TestTemplateMigration
+posthog/cdp/templates/posthog/test_template_posthog.py::TestTemplateMigration
+posthog/cdp/templates/rudderstack/test_template_rudderstack.py::TestTemplateMigration
+posthog/cdp/templates/salesforce/test_template_salesforce.py::TestTemplateMigration
+posthog/cdp/templates/sendgrid/test_template_sendgrid.py::TestTemplateMigration
+posthog/clickhouse/client/test/test_limit.py::TestRateLimit
+posthog/clickhouse/test/test_deletion_coverage.py::TestDeletionCoverage
+posthog/clickhouse/test/test_query_tagging.py::TestAddFallbackQueryTags
+posthog/helpers/test_markdown_safety.py::TestStripExternalLinks
+posthog/helpers/tests/test_email_utils.py::TestEmailNormalizer
+posthog/helpers/tests/test_encrypted_fields.py::TestEncryptedFields
+posthog/helpers/tests/test_geoip.py::TestGeoIPDBError
+posthog/helpers/tests/test_geoip.py::TestGeoIPError
+posthog/hogql/compiler/test/test_javascript.py::TestSanitizeIdentifier
+posthog/hogql/database/schema/test/test_information_schema.py::TestInformationSchemaPushdown
+posthog/hogql/database/schema/test/test_web_analytics_s3.py::TestWebAnalyticsS3
+posthog/hogql/database/test/test_argmax.py::TestArgmax
+posthog/hogql/database/test/test_postgres_table.py::TestPostgresTablePrimaryKey
+posthog/hogql/database/test/test_s3_table_clickhouse.py::TestS3ParquetTimezoneConversion
+posthog/hogql/functions/test/test_typegen.py::TestTypegen
+posthog/hogql/printer/test/test_sql_injection_defenses.py::TestEscapePreservationOnParserOutput
+posthog/hogql/printer/test/test_sql_injection_defenses.py::TestParserPathProducesOnlyAllowlistedVerbatimValues
+posthog/hogql/printer/test/test_sql_injection_defenses.py::TestPrintTimeOnlyAllowlists
+posthog/hogql/printer/test/test_sql_injection_defenses.py::TestVerbatimFieldConstructionRejection
+posthog/hogql/printer/test/test_sql_injection_defenses.py::TestVerbatimFieldPrinterDefenseInDepth
+posthog/hogql/test/_test_parse_string.py::TestParseString
+posthog/hogql/test/test_escape_sql.py::TestClickHouseIdentifierExecution
+posthog/hogql/test/test_escape_sql.py::TestPrintString
+posthog/hogql/test/test_hogqlx.py::TestHogQLX
+posthog/hogql/test/test_log_query_settings.py::TestTooManyBytesError
+posthog/hogql/test/test_parser_cache.py::TestParserCache
+posthog/hogql/test/test_placeholders.py::TestParser
+posthog/hogql/test/test_timings.py::TestHogQLTimings
+posthog/hogql/test/test_utils.py::TestUtils
+posthog/hogql/test/test_visitor.py::TestVisitor
+posthog/hogql/test/test_warehouse_warnings.py::TestWarehouseWarningsAccumulator
+posthog/hogql_queries/ai/test/test_utils.py::TestFilledPropertyFilters
+posthog/hogql_queries/ai/test/test_utils.py::TestMergeHeavyProperties
+posthog/hogql_queries/endpoints/test/test_endpoints_usage_query_runners.py::TestSafeFloat
+posthog/hogql_queries/legacy_compatibility/test/test_clean_properties.py::TestCleanEntityProperties
+posthog/hogql_queries/legacy_compatibility/test/test_clean_properties.py::TestCleanGlobalProperties
+posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py::TestDashboardTemplateConversion
+posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py::TestFilterToQuery
+posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py::TestHiddenLegendKeysToBreakdowns
+posthog/hogql_queries/legacy_compatibility/test/test_filter_to_query.py::TestHiddenLegendKeysToIndexes
+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_backfill_workflows_slack_integration.py::TestRewriteSlackWorkspaceInActions
+posthog/management/commands/test/test_base_hypercache_command.py::TestVerificationResultsErrorReporting
+posthog/management/commands/test/test_survey_cohort_bytecode_stl.py::TestBytecodeWalker
+posthog/models/filters/test/test_filter_mixins.py::TestFilterMixins
+posthog/models/filters/test/test_path_filter.py::TestPathFilter
+posthog/models/property/test/test_property_behavioral_validation.py::TestBehavioralPropertyBytecodeCondition
+posthog/models/property/test/test_property_behavioral_validation.py::TestBehavioralPropertyDateRangeValidation
+posthog/models/property/test/test_property_behavioral_validation.py::TestBehavioralPropertyValueAlias
+posthog/models/property/test/test_property_parse_value.py::TestPropertyParseValue
+posthog/models/resource_transfer/test/test_visitors.py::TestCohortExtractActionIds
+posthog/models/resource_transfer/test/test_visitors.py::TestCohortExtractCohortIds
+posthog/models/resource_transfer/test/test_visitors.py::TestCohortRewriteActionIdInFilters
+posthog/models/resource_transfer/test/test_visitors.py::TestCohortRewriteCohortIdInFilters
+posthog/models/resource_transfer/test/test_visitors.py::TestExtractActionIds
+posthog/models/resource_transfer/test/test_visitors.py::TestExtractCohortIds
+posthog/models/resource_transfer/test/test_visitors.py::TestRewriteActionIdInFilters
+posthog/models/resource_transfer/test/test_visitors.py::TestRewriteActionIdInQuery
+posthog/models/resource_transfer/test/test_visitors.py::TestRewriteCohortIdInFilters
+posthog/models/resource_transfer/test/test_visitors.py::TestRewriteCohortIdInQuery
+posthog/models/resource_transfer/test/test_visitors.py::TestSurveyVisitorConditionsCohorts
+posthog/models/scoping/test_scoping.py::TestContextVar
+posthog/models/scoping/test_scoping.py::TestTeamScopeContextManager
+posthog/models/scoping/test_scoping.py::TestUnscopedContextManager
+posthog/models/scoping/test_scoping.py::TestWithTeamScopeDecorator
+posthog/models/test/integration/test_oauth.py::TestYouTubeAnalyticsIntegrationModel
+posthog/models/test/test_activity_logging.py::TeatActivityLog
+posthog/models/test/test_entity_model.py::TestEntity
+posthog/models/test/test_event_model.py::TestSelectors
+posthog/models/test/test_missing_person_model.py::TestMissingPersonModel
+posthog/models/test/test_utils.py::TestUUIDv7
+posthog/models/test/test_utils.py::TestValidateRateLimit
+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/plugins/test/test_utils.py::TestPluginsUtils
+posthog/session/test/test_risk.py::TestSignalsAndTiers
+posthog/session/test/test_risk.py::TestUaSignature
+posthog/session_recordings/queries/test/test_session_replay_events.py::TestUuidv7SessionLowerBound
+posthog/session_recordings/test/recordings/test_recording_s3_client.py::TestAsyncRecordingS3Client
+posthog/session_recordings/test/recordings/test_recording_s3_client.py::TestRecordingS3Client
+posthog/session_recordings/test/test_session_recording_throttle.py::TestListingRatesConfig
+posthog/session_recordings/test/test_session_recording_throttle.py::TestListingRatesFromSettings
+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/storage/test/test_hypercache_manager.py::TestPushHypercacheStatsMetrics
+posthog/storage/test/test_hypercache_manager.py::TestPushHypercacheTeamsProcessedMetrics
+posthog/storage/test/test_hypercache_verifier.py::TestVerificationResult
+posthog/storage/test/test_team_access_cache_signal_handlers.py::TestUpdateTeamAuthenticationCacheOnDelete
+posthog/storage/test/test_team_metadata_cache.py::TestLLMGatewayFieldsNotInSharedProjection
+posthog/tasks/test/test_auth_token_cache_verification.py::TestVerifyAndFixAuthTokenCacheTask
+posthog/tasks/test/test_auth_token_cache_verification.py::TestVerifyAndFixAuthTokenCacheTaskDisabled
+posthog/tasks/test/test_hypercache_verification.py::TestVerifyAndFixFlagsCacheTask
+posthog/tasks/test/test_hypercache_verification.py::TestVerifyAndFixFlagsCacheTaskDisabled
+posthog/tasks/test/test_hypercache_verification.py::TestVerifyAndFixTeamMetadataCacheTask
+posthog/tasks/test/test_hypercache_verification.py::TestVerifyAndFixTeamMetadataCacheTaskDisabled
+posthog/tasks/test/test_remote_config.py::TestRemoteConfigCacheTasks
+posthog/tasks/test/test_scheduled.py::TestScheduledTasks
+posthog/tasks/test/test_team_access_cache_tasks.py::TestInvalidateTokenSync
+posthog/tasks/test/test_team_access_cache_tasks.py::TestInvalidateUserTokensSync
+posthog/tasks/test/test_team_access_cache_tasks.py::TestInvalidateUserTokensTask
+posthog/tasks/test/test_team_access_cache_tasks.py::TestInvalidationFailureMetrics
+posthog/tasks/test/test_usage_report.py::TestHasNonZeroUsage
+posthog/tasks/test/test_usage_report.py::TestSendNoUsage
+posthog/tasks/test/test_usage_report.py::TestTrimOversizeUsageReportPayload
+posthog/temporal/proxy_service/test/monitor_test.py::TestCheckCloudflareCertificateStatus
+posthog/temporal/proxy_service/test/test_cloudflare.py::TestCloudflareAPIErrorIsRateLimited
+posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py::TestPrepareSalesforceUpdateRecord
+posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py::TestProductionModeContinueAsNew
+posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py::TestUsageEnrichmentInputs
+posthog/temporal/tests/salesforce_enrichment/test_usage_workflow.py::TestWorkflowParseInputs
+posthog/test/activity_logging/test_activity_logging.py::TestActivityTriggerContext
+posthog/test/activity_logging/test_feature_flag_activity_logging.py::TestChangesBetweenFeatureFlags
+posthog/test/activity_logging/test_user_activity_logging.py::TestUserActivityLoggingConfiguration
+posthog/test/test_api_queries_budget.py::TestTokenBucket
+posthog/test/test_cache_utils.py::TestCacheUtils
+posthog/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::TestSampling
+posthog/test/test_schema_helpers.py::TestSchemaHelpers
+posthog/test/test_scoped_service_jwt.py::TestScopedServiceJwtPurpose
+posthog/test/test_templatetags.py::TestTemplateTags
+posthog/test/test_turnstile.py::TestVerifyTurnstileToken
+posthog/test/test_utils.py::TestAbsoluteUrls
+posthog/test/test_utils.py::TestFlatten
+posthog/test/test_utils.py::TestFormatUrls
+posthog/test/test_utils.py::TestGeneralUtils
+posthog/test/test_utils.py::TestGetIpAddress
+posthog/test/test_utils.py::TestGetJsUrl
+posthog/test/test_utils.py::TestGetShortUserAgent
+posthog/test/test_utils.py::TestRelativeDateParse
+posthog/test/test_utils.py::TestSharingOverrideProtection
+posthog/test/test_utils.py::TestShouldRefresh
+posthog/test/test_utils.py::TestStrToIntSet
+posthog/test/test_utils.py::TestTemplateContextHistogram
+posthog/test/test_utils.py::TestUtilities
+posthog/test/test_utils_cors.py::TestCorsResponse
+posthog/test/test_version_requirement.py::TestServiceVersionRequirement
+posthog/test/test_workos_radar.py::TestEvaluateAuthAttempt
+posthog/test/test_workos_radar.py::TestRadarApiCall
+posthog/test/test_workos_radar.py::TestRadarEventLogging
+posthog/test/test_workos_radar.py::TestRadarHelpers
+products/access_control/backend/tests/test_property_access_control.py::TestGetDefaultAccessLevel
+products/ai_observability/backend/api/test/test_personal_spend.py::TestPersonalSpendEuRedirect
+products/ai_observability/backend/models/test/test_taggers.py::TestLLMTaggerConfig
+products/alerts/backend/test/test_destinations.py::TestSerializeDeliveries
+products/alerts/backend/tests/api/test_alert.py::TestAlertEventProperties
+products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py::TestComputationExecutor
+products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py::TestComputeQueryHash
+products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py::TestMaxWindowDaysCap
+products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py::TestParseTtlSchedule
+products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py::TestSplitRangesByTtl
+products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py::TestWrittenRows
+products/approvals/backend/tests/test_update_feature_flag_action.py::TestUpdateFeatureFlagActionDisplayData
+products/autoresearch/backend/dataset/test_labeling.py::TestBuildInferenceFeaturesSql
+products/autoresearch/backend/dataset/test_labeling.py::TestStripSqlComments
+products/autoresearch/backend/dataset/test_labeling.py::TestSubstituteAnchors
+products/business_knowledge/backend/tests/test_api.py::TestDeriveScopeGlobs
+products/business_knowledge/backend/tests/test_background_refresh.py::TestHostSerializedBatches
+products/business_knowledge/backend/tests/test_crawl_ingest.py::TestDiscoverSSRF
+products/business_knowledge/backend/tests/test_crawl_ingest.py::TestDiscoverSameOrigin
+products/business_knowledge/backend/tests/test_crawl_ingest.py::TestDiscoverSitemap
+products/business_knowledge/backend/tests/test_hybrid_search.py::TestRRFFusion
+products/business_knowledge/backend/tests/test_logic.py::TestChunker
+products/business_knowledge/backend/tests/test_url_ingest.py::TestFetchUrl
+products/business_knowledge/backend/tests/test_url_ingest.py::TestNormalizeUrl
+products/business_knowledge/backend/tests/test_url_ingest.py::TestParseHtml
+products/cohorts/backend/models/test/test_cohort_membership.py::TestDeleteCohortMembersBulkMaxIterations
+products/cohorts/backend/models/test/test_util.py::TestGetFriendlyErrorMessage
+products/conversations/backend/api/tests/test_cache.py::TestCacheKeyGeneration
+products/conversations/backend/api/tests/test_cache.py::TestMessagesCacheOperations
+products/conversations/backend/api/tests/test_cache.py::TestTicketsCacheOperations
+products/conversations/backend/api/tests/test_cache.py::TestUnreadCountCacheOperations
+products/conversations/backend/api/tests/test_email_endpoints.py::TestBuildProxyKwargs
+products/conversations/backend/api/tests/test_restore.py::TestBuildRestoreUrl
+products/conversations/backend/api/tests/test_slack_multi_channel.py::TestConfiguredSupportChannels
+products/conversations/backend/api/tests/test_teams_multi_channel.py::TestConfiguredSupportChannelIds
+products/conversations/backend/api/tests/test_teams_shared_channel_polling.py::TestGraphMessageToActivity
+products/conversations/backend/api/tests/test_teams_shared_channel_polling.py::TestGraphReplyToActivity
+products/conversations/backend/api/tests/test_teams_token_storage.py::TestTrustedTeamsServiceUrl
+products/dashboards/backend/api/test/test_experiment_widgets.py::TestExperimentWidgetConfigs
+products/dashboards/backend/api/test/test_run_widgets.py::TestWidgetRegistry
+products/dashboards/backend/api/test/test_survey_widgets.py::TestSurveyResultsWidgetConfig
+products/dashboards/backend/api/test/test_widget_config_schema_parity.py::TestWidgetConfigSchemaParity
+products/dashboards/backend/test/test_widget_filters.py::TestWidgetFilters
+products/data_modeling/backend/test/test_incremental_eligibility.py::TestIncrementalEligibility
+products/data_modeling/backend/test/test_incremental_filter.py::TestInjectIncrementalFilter
+products/data_modeling/backend/test/test_saved_query_dag_sync.py::TestGetDagId
+products/endpoints/backend/tests/test_rate_limit.py::TestMaterializationCache
+products/engineering_analytics/backend/tests/test_logic_workflows.py::TestCostPerMergeSeries
+products/error_tracking/backend/hogql_queries/test/test_error_tracking_pending_fingerprint_issue_state_updates.py::TestPendingUpdateUnionBuilder
+products/error_tracking/backend/test_notifications.py::TestAssignerExcludingResolver
+products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.py::TestHogQLAggregationIntegration
+products/experiments/backend/hogql_queries/test/test_hogql_aggregation_utils.py::TestHogQLAggregationUtils
+products/experiments/backend/hogql_queries/test/test_hogql_injection.py::TestHogQLInjectionPrevention
+products/experiments/backend/hogql_queries/test/test_metric_source.py::TestMetricSourceInfo
+products/experiments/backend/hogql_queries/test/test_stats_config.py::TestSequentialStatsConfig
+products/experiments/backend/test/test_experiment_summary_tool.py::TestExperimentSummaryToolHelpers
+products/exports/backend/tasks/test/test_csv_exporter_url_sanitising.py::TestCSVExporterURLSanitization
+products/exports/backend/tasks/test/test_export_utils.py::TestSiteURLReachability
+products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py::TestCleanupStaleFlagDefinitionsExpiryTrackingTask
+products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py::TestRefreshExpiringFlagDefinitionsCacheEntries
+products/feature_flags/backend/test/test_flags_cache.py::TestExtractCohortIdsFromFlagFilters
+products/feature_flags/backend/test/test_local_evaluation.py::TestExtractCohortIdsFromFilters
+products/growth/backend/temporal/signup_enrichment/tests/test_harmonic_status_poll.py::TestReportStatusPollRunActivity
+products/legal_documents/backend/tests/test_admin.py::TestLegalDocumentInlineRegistration
+products/logs/backend/test/test_logs_url_params.py::TestBuildLogsUrlParams
+products/marketing_analytics/backend/services/test_utm_matching.py::TestSharedMatchHelpers
+products/marketing_analytics/backend/test_api_serializer_parity.py::TestSerializerFieldParity
+products/marketing_analytics/backend/test_max_tools.py::TestFormatAuditUtmForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestFormatConversionGoalsForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestFormatDataSourcesForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestFormatDiagnosticForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestFormatEventSuggestionsForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestFormatExplainGoalForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestFormatGoalLine
+products/marketing_analytics/backend/test_max_tools.py::TestFormatTimestampForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestFormatUtmMappingSuggestionsForLlm
+products/marketing_analytics/backend/test_max_tools.py::TestSanitizeForPrompt
+products/mcp_store/backend/test/test_api.py::TestIsValidPosthogCodeCallbackUrl
+products/mcp_store/backend/test/test_oauth.py::TestAuthServerMetadataDiscoveryChain
+products/mcp_store/backend/test/test_oauth.py::TestResolveIssuer
+products/mcp_store/backend/test/test_oauth.py::TestSSRFProtection
+products/mcp_store/backend/test/test_oauth.py::TestValidateEndpointsBoundToIssuer
+products/messaging/backend/services/test_customerio_track_client.py::TestCustomerIOTrackClient
+products/metrics/backend/tests/test_metric_query_runner.py::TestAlignToInterval
+products/posthog_ai/eval_harness/test/test_acp_log.py::TestSandboxedTraceCaptureParser
+products/posthog_ai/scripts/hogql_example/test/test_hogql_example.py::TestRenderHogQLExample
+products/product_analytics/backend/hogql_queries/paths/test/test_paths_query_runner_ee.py::TestClickhousePathsEdgeValidation
+products/product_analytics/backend/hogql_queries/trends/test/test_breakdown_limits.py::TestBreakdownValueTruncation
+products/revenue_analytics/backend/test/test_joins.py::TestGetCustomerRevenueViewName
+products/skills/backend/api/test/test_community_skills.py::TestSkillTemplateRendering
+products/slack_app/backend/tests/test_followup_forwarding.py::TestEventLevelDedupe
+products/slack_app/backend/tests/test_fork_thread.py::TestForkMenuBlock
+products/slack_app/backend/tests/test_posthog_code_interactivity.py::TestExtractAlertSnoozeHints
+products/slack_app/backend/tests/test_validate_slack_request.py::TestValidateSlackRequest
+products/slack_app/backend/tests/test_workspace_claims.py::TestDoesOtherRegionClaimWorkspace
+products/streamlit_apps/backend/tests/test_app_runtime.py::TestGetOtelLogsConfig
+products/streamlit_apps/backend/tests/test_app_runtime.py::TestSandboxCallbackUrl
+products/streamlit_apps/backend/tests/test_app_runtime.py::TestWaitForHealth
+products/streamlit_apps/backend/tests/test_tasks.py::TestAutoRestartCrashedStreamlitSandboxes
+products/streamlit_apps/backend/tests/test_tasks.py::TestStopIdleStreamlitSandboxes
+products/streamlit_apps/backend/tests/test_zip_validator.py::TestValidateZip
+products/surveys/backend/api/test/test_external_surveys.py::TestExternalSurveysURLs
+products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py::TestGetStopReason
+products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py::TestSteerDeclineReason
+products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py::TestExtractTextFromMessagePayload
+products/tasks/backend/temporal/process_task/tests/test_utils.py::TestBuildImportedMcpServerConfigs
+products/tasks/backend/temporal/process_task/tests/test_utils.py::TestBuildSandboxEnvironmentVariablesGateway
+products/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetImportedMcpServerConfigs
+products/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetRelayedMcpServerNames
+products/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetSandboxGitHubToken
+products/tasks/backend/temporal/process_task/tests/test_utils.py::TestGetSandboxMcpConfigs
+products/tasks/backend/temporal/process_task/tests/test_utils.py::TestMcpServerConfigToDict
+products/tasks/backend/temporal/slack_relay/tests/test_activities.py::TestSplitTextForSlack
+products/tasks/backend/tests/test_agentsh.py::TestBuildAuditQueryCommand
+products/tasks/backend/tests/test_agentsh.py::TestBuildExecPrefix
+products/tasks/backend/tests/test_agentsh.py::TestGenerateConfigYaml
+products/tasks/backend/tests/test_ai_run_defaults.py::TestRunCreateSerializerModeWithoutAdapter
+products/tasks/backend/tests/test_api.py::TestTaskRunRedisStreamKeepalive
+products/tasks/backend/tests/test_api.py::TestUsageLimitResponse
+products/tasks/backend/tests/test_facade.py::TestAppendLogAgentActivity
+products/tasks/backend/tests/test_facade.py::TestFacadeImports
+products/tasks/backend/tests/test_repository_readiness.py::TestApplicableCapabilities
+products/tasks/backend/tests/test_repository_readiness.py::TestCandidatePathScore
+products/tasks/backend/tests/test_repository_readiness.py::TestClassifyRepository
+products/tasks/backend/tests/test_repository_readiness.py::TestSelectCandidatePaths
+products/tasks/backend/tests/test_repository_readiness.py::TestShouldScanPath
+products/tasks/backend/tests/test_webhooks.py::TestAccountType
+products/user_interviews/backend/test_facade.py::TestParseIntervieweeIdentifier
+products/warehouse_sources/backend/tests/api/test_external_data_source.py::TestGetOAuthIntegrationKinds
+products/warehouse_sources/backend/tests/api/test_external_data_source.py::TestSensitiveFieldClassification
+products/web_analytics/backend/hogql_queries/test/test_custom_bot_definitions.py::TestPatternsCompile
+products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py::TestComputeFiltersEligibilityHash
+products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py::TestComputeShapeCapKey
+products/web_analytics/backend/test/test_max_tools.py::TestWebAnalyticsAssistantFilters
+products/web_analytics/backend/test/test_path_cleaning_suggestions.py::TestExtractJson
+products/web_analytics/backend/test/test_path_cleaning_suggestions.py::TestValidateAndAnnotateRules
+products/web_analytics/dags/tests/test_cache_warming.py::TestCanonicalizeLazyReplay
+products/web_analytics/dags/tests/test_cache_warming.py::TestDeepenToWidestWarmableRange
+products/web_analytics/dags/tests/test_cache_warming.py::TestFleetQuerySelection
+products/web_analytics/dags/tests/test_cache_warming.py::TestMaybeExpandWarmingDateRange
+products/web_analytics/dags/tests/test_cache_warming.py::TestMaybeOptIntoLazyPrecompute
+products/web_analytics/dags/tests/test_cache_warming.py::TestSplitWarmableQueries
+products/web_analytics/dags/tests/test_cache_warming.py::TestWarmableQueriesCaching
+products/workflows/backend/test/test_email_sending_tier.py::TestEmailSendingTierDecision
diff --git a/posthog/test/repo_invariants/test_database_free_test_classes.py b/posthog/test/repo_invariants/test_database_free_test_classes.py
new file mode 100644
index 000000000000..b3d1ed60fcc3
--- /dev/null
+++ b/posthog/test/repo_invariants/test_database_free_test_classes.py
@@ -0,0 +1,310 @@
+"""Ratchet on test classes that take a database they never use.
+
+The failure message says what a reported class means, how to confirm it, and how to
+regenerate the list. `.agents/skills/writing-tests/references/database-free-test-classes.md`
+carries the long form.
+"""
+
+import re
+import ast
+import warnings
+from pathlib import Path
+
+from parameterized import parameterized
+
+REPO_ROOT = Path(__file__).parents[3]
+BASELINE_PATH = Path(__file__).parent / "database_free_test_classes_baseline.txt"
+SCANNED_ROOTS = ("posthog", "ee", "products", "common")
+SKIPPED_DIRS = {"node_modules", ".venv", "venv", "__pycache__", ".git", ".mypy_cache"}
+REGENERATE = "python posthog/test/repo_invariants/test_database_free_test_classes.py"
+
+# Must reach a signature split over several lines and a nested class: a base it does
+# not see is one that gets reported as a candidate.
+CLASS_BASES = re.compile(r"^\s*class\s+\w+\s*\(([^)]*)\)", re.MULTILINE)
+
+# Bases that bring Django `TestCase` with them. Reaching one through a project-specific
+# subclass is out of scope.
+POSTHOG_BASES = {
+ "APIBaseTest",
+ "BaseTest",
+ "NonAtomicBaseTest",
+ "NonAtomicBaseTestKeepIdentities",
+}
+# Only from django.test: a class on `unittest.TestCase` is already where this wants it.
+DJANGO_BASES = {"TestCase", "TransactionTestCase"}
+DATABASE_BASES = POSTHOG_BASES | DJANGO_BASES
+
+# Any of these in the class body reads as "may reach the database". Keep it broad: an
+# extra token hides a candidate, a missing one reports a class that needs its database.
+DATABASE_TOKENS = (
+ ".objects",
+ "_create",
+ "assertNumQueries",
+ "bulk_create",
+ "capture_db_queries",
+ "connection",
+ "create_",
+ "cursor",
+ "django_db",
+ "flush_",
+ "get_or_create",
+ "refresh_from_db",
+ "self.client",
+ "self.demo_team",
+ "self.organization",
+ "self.other_team",
+ "self.project",
+ "self.team",
+ "self.user",
+ "snapshot",
+ "transaction",
+ ".delete(",
+ ".exists(",
+ ".filter(",
+ ".save(",
+)
+
+
+def _django_test_names(tree: ast.Module) -> set[str]:
+ """Local names bound to a django.test database base, under whatever alias.
+
+ `from django.test import TestCase as DjangoTestCase` binds the base to a name this
+ scan would otherwise not recognise, so record the local name and not the imported one.
+ """
+ names: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ImportFrom) or not (node.module or "").startswith("django.test"):
+ continue
+ names.update(alias.asname or alias.name for alias in node.names if alias.name in DJANGO_BASES)
+ return names
+
+
+def _dotted(node: ast.expr) -> str | None:
+ if isinstance(node, ast.Name):
+ return node.id
+ if isinstance(node, ast.Attribute):
+ base = _dotted(node.value)
+ return f"{base}.{node.attr}" if base else None
+ return None
+
+
+def _takes_a_database(node: ast.ClassDef, django_names: set[str]) -> bool:
+ for base in node.bases:
+ dotted = _dotted(base)
+ if dotted is None:
+ continue
+ # `django.test.TestCase` written out in full reaches no import alias.
+ if dotted.startswith("django.test.") and dotted.rsplit(".", 1)[-1] in DJANGO_BASES:
+ return True
+ if dotted in POSTHOG_BASES or dotted in django_names:
+ return True
+ return False
+
+
+def _runs_tests(node: ast.ClassDef) -> bool:
+ """A class with no test method of its own is infrastructure, not a test."""
+ return any(
+ isinstance(statement, ast.FunctionDef | ast.AsyncFunctionDef) and statement.name.startswith("test")
+ for statement in node.body
+ )
+
+
+def _base_names_in_source(source: str) -> set[str]:
+ return {
+ base_name.strip().split("[")[0].split(".")[-1]
+ for match in CLASS_BASES.finditer(source)
+ for base_name in match.group(1).split(",")
+ }
+
+
+def _candidates_in_source(source: str) -> list[str]:
+ tree = ast.parse(source)
+ django_names = _django_test_names(tree)
+ lines = source.splitlines()
+ names = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ClassDef):
+ continue
+ if not _takes_a_database(node, django_names) or not _runs_tests(node):
+ continue
+ # Raw source, so a comment naming a table counts as a sign too.
+ body = "\n".join(lines[node.lineno - 1 : node.end_lineno])
+ if not any(token in body for token in DATABASE_TOKENS):
+ names.append(node.name)
+ return names
+
+
+def collect_candidates() -> list[str]:
+ # Reporting a class other tests inherit would ask for `BaseTest` itself to move to
+ # `SimpleTestCase`, so gather the inherited names first and drop them at the end.
+ # That gather reads every file, and has to: production code inherits from test bases,
+ # so limiting it to test paths knows a fraction of the names and reports those bases.
+ inherited: set[str] = set()
+ found: list[tuple[str, str]] = []
+ for root in SCANNED_ROOTS:
+ for path in (REPO_ROOT / root).rglob("*.py"):
+ if SKIPPED_DIRS.intersection(path.parts):
+ continue
+ source = path.read_text(encoding="utf-8", errors="ignore")
+ inherited.update(_base_names_in_source(source))
+ if not any(base in source for base in DATABASE_BASES):
+ continue
+ # A bad escape sequence in some other file is that file's problem, not a
+ # warning this test should print.
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ names = _candidates_in_source(source)
+ except SyntaxError:
+ continue
+ found.extend((path.relative_to(REPO_ROOT).as_posix(), name) for name in names)
+ return sorted(f"{path}::{name}" for path, name in found if name not in inherited)
+
+
+# Each case below is a bug this scan actually had. The baseline test cannot catch a
+# detection regression on its own: a class that stops being detected leaves as a '-'
+# line, which reads as a class someone fixed, and the advertised remedy is to
+# regenerate the baseline.
+DETECTION_CASES = [
+ (
+ "pure_class_on_a_posthog_base_is_reported",
+ "from posthog.test.base import BaseTest\n"
+ "class ExamplePure(BaseTest):\n"
+ " def test_adds(self) -> None:\n"
+ " assert 1 + 1 == 2\n",
+ ["ExamplePure"],
+ ),
+ (
+ "class_reading_a_fixture_is_left_alone",
+ "from posthog.test.base import BaseTest\n"
+ "class ExampleReadsTeam(BaseTest):\n"
+ " def test_named(self) -> None:\n"
+ " assert self.team.name\n",
+ [],
+ ),
+ (
+ "class_querying_a_model_is_left_alone",
+ "from posthog.test.base import BaseTest\n"
+ "class ExampleQueries(BaseTest):\n"
+ " def test_empty(self) -> None:\n"
+ " assert Insight.objects.count() == 0\n",
+ [],
+ ),
+ (
+ "unittest_testcase_takes_no_database",
+ "from unittest import TestCase\n"
+ "class ExampleUnittest(TestCase):\n"
+ " def test_adds(self) -> None:\n"
+ " assert 1 + 1 == 2\n",
+ [],
+ ),
+ (
+ "django_testcase_does_take_one",
+ "from django.test import TestCase\n"
+ "class ExampleDjango(TestCase):\n"
+ " def test_adds(self) -> None:\n"
+ " assert 1 + 1 == 2\n",
+ ["ExampleDjango"],
+ ),
+ (
+ "django_testcase_under_an_alias",
+ "from django.test import TestCase as DjangoTestCase\n"
+ "class ExampleAliased(DjangoTestCase):\n"
+ " def test_adds(self) -> None:\n"
+ " assert 1 + 1 == 2\n",
+ ["ExampleAliased"],
+ ),
+ (
+ "django_testcase_written_out_in_full",
+ "import django.test\n"
+ "class ExampleDotted(django.test.TestCase):\n"
+ " def test_adds(self) -> None:\n"
+ " assert 1 + 1 == 2\n",
+ ["ExampleDotted"],
+ ),
+ (
+ "class_with_no_test_method_is_infrastructure",
+ "from posthog.test.base import BaseTest\n"
+ "class ExampleHelpers(BaseTest):\n"
+ " def assert_ok(self, response) -> None:\n"
+ " assert response\n",
+ [],
+ ),
+ (
+ "simpletestcase_is_already_where_this_wants_it",
+ "from django.test import SimpleTestCase\n"
+ "class ExampleAlreadyFree(SimpleTestCase):\n"
+ " def test_adds(self) -> None:\n"
+ " assert 1 + 1 == 2\n",
+ [],
+ ),
+]
+
+
[email protected](DETECTION_CASES)
+def test_detection(_name: str, source: str, expected: list[str]) -> None:
+ assert _candidates_in_source(source) == expected
+
+
+BASE_NAME_CASES = [
+ ("plain", "class ExampleChild(ExampleParent):\n pass\n", "ExampleParent"),
+ (
+ "signature_split_over_lines",
+ "class ExampleChild(\n ExampleParent,\n ExampleOther,\n):\n pass\n",
+ "ExampleParent",
+ ),
+ ("nested_in_another_class", "class Outer:\n class Inner(ExampleParent):\n pass\n", "ExampleParent"),
+ ("dotted", "class ExampleChild(module.ExampleParent):\n pass\n", "ExampleParent"),
+]
+
+
[email protected](BASE_NAME_CASES)
+def test_base_names_seen(_name: str, source: str, expected: str) -> None:
+ assert expected in _base_names_in_source(source)
+
+
+def test_a_base_other_tests_inherit_is_dropped() -> None:
+ shared = (
+ "from posthog.test.base import BaseTest\n"
+ "class ExampleSharedBase(BaseTest):\n"
+ " def test_inherited_by_others(self) -> None:\n"
+ " assert self.helper()\n"
+ )
+ assert _candidates_in_source(shared) == ["ExampleSharedBase"]
+ assert "ExampleSharedBase" in _base_names_in_source("class ExampleUser(ExampleSharedBase):\n pass\n")
+
+
+def read_baseline() -> list[str]:
+ return sorted(line for line in BASELINE_PATH.read_text().splitlines() if line.strip())
+
+
+def write_baseline(candidates: list[str]) -> None:
+ BASELINE_PATH.write_text("\n".join(candidates) + "\n")
+
+
+def test_database_free_test_classes_match_the_baseline() -> None:
+ scanned = collect_candidates()
+ recorded = read_baseline()
+ if scanned == recorded:
+ return
+
+ added = [line for line in scanned if line not in recorded]
+ removed = [line for line in recorded if line not in scanned]
+ report = "\n".join([*(f" + {line}" for line in added), *(f" - {line}" for line in removed)])
+ raise AssertionError(
+ f"{BASELINE_PATH.name} no longer matches the repo.\n"
+ "A '+' line is a test class that inherits a database base class but never names "
+ "anything that reaches the database, so it needs a database it never reads. "
+ "Confirm it by swapping the base for django.test.SimpleTestCase and running "
+ "the class: SimpleTestCase refuses database access, so a passing run means the class "
+ "never needed one, and that base is the fix. If the class does need a database through "
+ "a helper this scan cannot see, add the baseline line back in the same change.\n"
+ f"A '-' line means a candidate went away — good, but the file must record that too. Run: {REGENERATE}\n"
+ f"{report}"
+ )
+
+
+if __name__ == "__main__":
+ candidates = collect_candidates()
+ write_baseline(candidates)
+ print(f"baseline written: {len(candidates)} candidates") # noqa: T201