: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): speed up backend python test runs (#68799)
Paul D'Ambra832a734648b1
diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.pyindex 82620a7fb90f..fec8e5d6e08d 100644--- a/posthog/hogql/test/test_metadata.py+++ b/posthog/hogql/test/test_metadata.py@@ -29,6 +29,10 @@ from products.warehouse_sources.backend.facade.types import ExternalDataSourceTyclass TestMetadata(ClickhouseTestMixin, APIBaseTest):maxDiff = None+ # No test here writes per-team ClickHouse data, so the per-test team isolation+ # that ClickhouseTestMixin defaults to (CLASS_DATA_LEVEL_SETUP = False) only adds+ # ~100ms of org/team/user creation to every test.+ CLASS_DATA_LEVEL_SETUP = Truedef _expr(self, query: str, table: str = "events", debug=True) -> HogQLMetadataResponse:return get_hogql_metadata(diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.pyindex 84d5e8dc304c..9d6b1cbbedc9 100644--- a/posthog/hogql/test/test_resolver.py+++ b/posthog/hogql/test/test_resolver.py@@ -1,5 +1,5 @@from datetime import UTC, date, datetime-from typing import Any, Optional, cast+from typing import Any, ClassVar, Optional, castfrom uuid import UUIDimport pytest@@ -30,6 +30,7 @@ from posthog.hogql.database.models import (from posthog.hogql.database.schema.events import EventsTablefrom posthog.hogql.database.schema.persons import PersonsTablefrom posthog.hogql.errors import QueryError+from posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_ast, print_prepared_astfrom posthog.hogql.resolver import ResolutionError, resolve_types@@ -56,8 +57,20 @@ class TestResolver(BaseTest):"hogql",)[0]+ # _fetch_sources hits Postgres a dozen times and its inputs never change within this class+ # (fixed team, no warehouse objects), so cache the fetched sources per effective modifiers —+ # the only input that varies (via @override_settings). Building the Database stays per-test+ # because several tests mutate their instance's tables.+ _sources_cache: ClassVar[dict[str, Any]] = {}+def setUp(self):- self.database = Database.create_for(team=self.team)+ modifiers = create_default_modifiers_for_team(self.team)+ cache_key = modifiers.model_dump_json()+ sources = TestResolver._sources_cache.get(cache_key)+ if sources is None:+ sources = Database._fetch_sources(team=self.team, modifiers=modifiers)+ TestResolver._sources_cache[cache_key] = sources+ self.database = Database._build_from_sources(sources)self.context = HogQLContext(database=self.database, team_id=self.team.pk, enable_select_queries=True)@pytest.mark.usefixtures("unittest_snapshot")diff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex c66a68c7eb06..ed780feb045c 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -1,5 +1,5 @@+import sysimport time-import inspectimport dataclassesfrom collections.abc import Callablefrom datetime import timedelta@@ -94,18 +94,22 @@ def _detect_impersonation_for_login(user, request):hasattr(request, "session") and request.session and la_settings.USER_SESSION_FLAG in request.session)- for frame in inspect.stack():- if "loginas" in frame.filename:+ # Walk raw frames instead of inspect.stack(): the latter resolves source context for+ # every frame (linecache + sys.modules scans), which costs ~200ms per login.+ frame = sys._getframe().f_back+ while frame is not None:+ if "loginas" in frame.f_code.co_filename:try:- if "original_user_pk" in frame.frame.f_locals:+ if "original_user_pk" in frame.f_locals:User = get_user_model()- original_user_pk = frame.frame.f_locals["original_user_pk"]+ original_user_pk = frame.f_locals["original_user_pk"]admin_user = User.objects.get(pk=original_user_pk)return True, admin_user, str(user.id), "impersonation"except Exception:passreturn True, user, str(user.id), "impersonation"+ frame = frame.f_backif has_impersonation_session:try:diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 1c5818a394d8..eb6dca799176 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -344,6 +344,12 @@ AUTH_PASSWORD_VALIDATORS = [{"NAME": "posthog.auth.ZxcvbnValidator"},]+if TEST:+ # PBKDF2 is deliberately slow (~150ms per hash), which adds up because every+ # per-test user creation hashes a password. MD5 keeps the same hasher API with+ # none of the cost. Never used outside tests.+ PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]+PASSWORD_RESET_TIMEOUT = 86_400 # 1 day####diff --git a/pytest.ini b/pytest.iniindex 4b248ff108b4..b521fcdc6451 100644--- a/pytest.ini+++ b/pytest.ini@@ -7,7 +7,9 @@ DJANGO_SETTINGS_MODULE = posthog.settings# --pytest-durations=0 disables the pytest-durations plugin by default; CI shard steps re-enable it explicitly# -p no:tach disables tach's pytest plugin: without --tach it builds the full import graph (~5-10s# per invocation) only to print a "could be skipped" hint. Opt back in with: pytest -p tach --tach-addopts = -p no:warnings -p no:tach --reuse-db --pytest-durations=0 --ignore=posthog/user_scripts --ignore=services/llm-gateway --ignore=services/stripe-mock --ignore=common/ingestion/acceptance_tests --ignore=tools/hogli --ignore=tools/hogli-commands --ignore=tools/traffic-sim --ignore=tools/query-performance-ai+# -p no:langsmith skips the langsmith pytest plugin (auto-registered by a transitive dependency,+# ~0.8s of imports per invocation); nothing in this repo uses langsmith's pytest integration+addopts = -p no:warnings -p no:tach -p no:langsmith --reuse-db --pytest-durations=0 --ignore=posthog/user_scripts --ignore=services/llm-gateway --ignore=services/stripe-mock --ignore=common/ingestion/acceptance_tests --ignore=tools/hogli --ignore=tools/hogli-commands --ignore=tools/traffic-sim --ignore=tools/query-performance-aimarkers =ee