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): 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.py
index 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 ExternalDataSourceTy
class 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 = True
def _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.py
index 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, cast
from uuid import UUID
import pytest
@@ -30,6 +30,7 @@ from posthog.hogql.database.models import (
from posthog.hogql.database.schema.events import EventsTable
from posthog.hogql.database.schema.persons import PersonsTable
from posthog.hogql.errors import QueryError
+from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast, print_prepared_ast
from 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.py
index c66a68c7eb06..ed780feb045c 100644
--- a/posthog/models/activity_logging/signal_handlers.py
+++ b/posthog/models/activity_logging/signal_handlers.py
@@ -1,5 +1,5 @@
+import sys
import time
-import inspect
import dataclasses
from collections.abc import Callable
from 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:
pass
return True, user, str(user.id), "impersonation"
+ frame = frame.f_back
if has_impersonation_session:
try:
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 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.ini
index 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-ai
markers =
ee