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(tasks): drop per-test DB flush from backend tests (#62738)

Raúl Negrón-Otero345bfff4188f
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index d8b4f6951803..1af373932c77 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -5,8 +5,9 @@ from collections.abc import Sequence
from unittest.mock import patch
-from django.test import TransactionTestCase, override_settings
+from django.test import TestCase, override_settings
+from asgiref.sync import async_to_sync
from parameterized import parameterized
from posthog.models import Organization, Team
@@ -37,7 +38,7 @@ from products.tasks.backend.stream.redis_stream import (
from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
-class TestTaskRunEventIngest(TransactionTestCase):
+class TestTaskRunEventIngest(TestCase):
def setUp(self) -> None:
super().setUp()
TEST_clear_clients()
@@ -129,7 +130,9 @@ class TestTaskRunEventIngest(TransactionTestCase):
body = json.loads(sent[1]["body"])
return status, body
- return asyncio.run(_call())
+ # async_to_sync (not asyncio.run) so the handler's thread_sensitive DB
+ # access runs on the test thread's connection and sees uncommitted rows.
+ return async_to_sync(_call)()
def _read_stream_events(self) -> list[dict]:
async def _read() -> list[dict]:
@@ -252,7 +255,7 @@ class TestTaskRunEventIngest(TransactionTestCase):
return sent[0]["status"], json.loads(sent[1]["body"])
with patch("products.tasks.backend.stream.event_ingest._heartbeat_workflow", side_effect=blocking_heartbeat):
- status, body = asyncio.run(_call())
+ status, body = async_to_sync(_call)()
self.assertEqual(status, 200)
self.assertEqual(body["accepted"], 1)
diff --git a/products/tasks/backend/tests/test_presence.py b/products/tasks/backend/tests/test_presence.py
index c12b38825b71..0ee35948ca34 100644
--- a/products/tasks/backend/tests/test_presence.py
+++ b/products/tasks/backend/tests/test_presence.py
@@ -3,7 +3,7 @@ from datetime import timedelta
from unittest.mock import patch
from django.core.cache import cache
-from django.test import TestCase, TransactionTestCase
+from django.test import TestCase
from django.utils import timezone
from parameterized import parameterized
@@ -166,9 +166,10 @@ class PresenceAPITestCase(TestCase):
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-class PresenceFanoutSuppressionTestCase(TransactionTestCase):
- """``send_user_push`` is dispatched via ``transaction.on_commit``; we need a
- TransactionTestCase so the callback actually fires.
+class PresenceFanoutSuppressionTestCase(TestCase):
+ """``send_user_push`` is dispatched via ``transaction.on_commit``; the test
+ wraps dispatch in ``captureOnCommitCallbacks(execute=True)`` so the callback
+ fires despite TestCase's rolled-back transaction.
The contract under test: any non-expired presence row for this user/task
suppresses fanout to ALL of that user's push tokens — including the
@@ -239,7 +240,8 @@ class PresenceFanoutSuppressionTestCase(TransactionTestCase):
)
self._present(self.device_a, on_task=other_task, expires_in=timedelta(seconds=30))
- notify_task_run_completed(self.task_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_run_completed(self.task_run)
mock_delay.assert_called_once()
suppressed = mock_delay.call_args.args[4]
diff --git a/products/tasks/backend/tests/test_push_dispatcher.py b/products/tasks/backend/tests/test_push_dispatcher.py
index 36d78bb17b29..6be5495cf63a 100644
--- a/products/tasks/backend/tests/test_push_dispatcher.py
+++ b/products/tasks/backend/tests/test_push_dispatcher.py
@@ -2,7 +2,7 @@ from unittest.mock import patch
from django.core.cache import cache
from django.db import InterfaceError, OperationalError
-from django.test import TransactionTestCase
+from django.test import TestCase
from parameterized import parameterized
from prometheus_client import REGISTRY
@@ -18,9 +18,11 @@ from products.tasks.backend.push_dispatcher import (
)
-# TransactionTestCase so transaction.on_commit callbacks (which we use to defer
-# the Celery dispatch) actually fire during the test instead of being rolled back.
-class TestPushDispatcher(TransactionTestCase):
+# The Celery dispatch is deferred via transaction.on_commit, which never fires
+# inside TestCase's rolled-back transaction — tests wrap notify calls in
+# captureOnCommitCallbacks(execute=True) to run the deferred callback (or assert
+# none was registered) without TransactionTestCase's per-test full-DB flush.
+class TestPushDispatcher(TestCase):
def setUp(self) -> None:
cache.clear()
self.organization = Organization.objects.create(name="Test Org")
@@ -49,7 +51,8 @@ class TestPushDispatcher(TransactionTestCase):
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
def test_notify_enqueues_push(self, _name, notify_fn, expected_body_fragment, mock_delay, _flag):
- notify_fn(self.task_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_fn(self.task_run)
mock_delay.assert_called_once()
user_id, title, body, data, suppressed = mock_delay.call_args.args
self.assertEqual(user_id, self.user.id)
@@ -63,7 +66,8 @@ class TestPushDispatcher(TransactionTestCase):
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=False)
@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
def test_feature_flag_off_skips_dispatch(self, mock_delay, _flag):
- notify_task_run_completed(self.task_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_run_completed(self.task_run)
mock_delay.assert_not_called()
@patch(
@@ -72,23 +76,26 @@ class TestPushDispatcher(TransactionTestCase):
)
@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
def test_flag_error_fails_closed(self, mock_delay, _flag):
- notify_task_run_completed(self.task_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_run_completed(self.task_run)
mock_delay.assert_not_called()
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
def test_cooldown_collapses_duplicates(self, mock_delay, _flag):
- notify_task_run_completed(self.task_run)
- notify_task_run_completed(self.task_run)
- notify_task_run_completed(self.task_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_run_completed(self.task_run)
+ notify_task_run_completed(self.task_run)
+ notify_task_run_completed(self.task_run)
self.assertEqual(mock_delay.call_count, 1)
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
@patch("products.tasks.backend.push_dispatcher.send_user_push.delay")
def test_cooldown_is_per_kind(self, mock_delay, _flag):
# Different push kinds on the same run shouldn't share a cooldown key.
- notify_task_run_completed(self.task_run)
- notify_task_run_awaiting_input(self.task_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_run_completed(self.task_run)
+ notify_task_run_awaiting_input(self.task_run)
self.assertEqual(mock_delay.call_count, 2)
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
@@ -106,7 +113,8 @@ class TestPushDispatcher(TransactionTestCase):
)
outsider_run = TaskRun.objects.create(task=outsider_task, team=self.team)
- notify_task_run_completed(outsider_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_run_completed(outsider_run)
mock_delay.assert_not_called()
@patch("products.tasks.backend.push_dispatcher.posthoganalytics.feature_enabled", return_value=True)
@@ -120,7 +128,8 @@ class TestPushDispatcher(TransactionTestCase):
created_by=None,
)
anonymous_run = TaskRun.objects.create(task=anonymous_task, team=self.team)
- notify_task_run_completed(anonymous_run)
+ with self.captureOnCommitCallbacks(execute=True):
+ notify_task_run_completed(anonymous_run)
mock_delay.assert_not_called()
@patch("products.tasks.backend.push_dispatcher._enqueue_inner", side_effect=RuntimeError("redis is down"))
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index c3cd90d4bad5..0a3d1aec94e2 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -1,6 +1,6 @@
from unittest.mock import AsyncMock, Mock, patch
-from django.test import TransactionTestCase, override_settings
+from django.test import TestCase, override_settings
from asgiref.sync import async_to_sync
from parameterized import parameterized
@@ -17,7 +17,7 @@ from products.tasks.backend.temporal.client import (
@override_settings(DEBUG=False)
-class TestExecuteTaskProcessingWorkflow(TransactionTestCase):
+class TestExecuteTaskProcessingWorkflow(TestCase):
def setUp(self) -> None:
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")