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(messaging): run pure messaging tests without database setup (#110663)

posthog[bot]24b27aaa6e6e
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 3f18d17c5465..acbf9fc175dd 100644
--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt
@@ -325,7 +325,6 @@ products/marketing_analytics/backend/test_max_tools.py::TestFormatTimestampForLl
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/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
diff --git a/products/messaging/backend/api/test/test_message_suppression.py b/products/messaging/backend/api/test/test_message_suppression.py
index bce4af96182c..4eccebff7756 100644
--- a/products/messaging/backend/api/test/test_message_suppression.py
+++ b/products/messaging/backend/api/test/test_message_suppression.py
@@ -1,34 +1,13 @@
from posthog.test.base import APIBaseTest
-from django.test import SimpleTestCase
-
from parameterized import parameterized
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
-from products.messaging.backend.api.message_suppression import MessageSuppressionViewSet
from products.messaging.backend.models.message_suppression import MessageSuppression, SuppressionSource
-class TestMessageSuppressionViewSetScope(SimpleTestCase):
- """
- Guards against the viewset silently reverting to scope_object='INTERNAL', which would bypass
- hog_flow RBAC and let any project member manage suppressions regardless of workflow permissions.
- """
-
- def test_scope_object_is_hog_flow(self) -> None:
- assert MessageSuppressionViewSet.scope_object == "hog_flow"
-
- def test_mutating_actions_are_declared_as_writes(self) -> None:
- # `add_suppression` and `remove_suppression` are custom @action endpoints; without being
- # listed here they'd default to a read scope and slip past hog_flow:write enforcement.
- assert set(MessageSuppressionViewSet.scope_object_write_actions) == {
- "add_suppression",
- "remove_suppression",
- }
-
-
class TestSuppressionListPersonalAPIKeyAccess(APIBaseTest):
"""
Guards the token scopes on the read action. It needs both hog_flow:read and person:read, so
diff --git a/products/messaging/backend/api/test/test_message_suppression_unit.py b/products/messaging/backend/api/test/test_message_suppression_unit.py
new file mode 100644
index 000000000000..202292017057
--- /dev/null
+++ b/products/messaging/backend/api/test/test_message_suppression_unit.py
@@ -0,0 +1,21 @@
+from django.test import SimpleTestCase
+
+from products.messaging.backend.api.message_suppression import MessageSuppressionViewSet
+
+
+class TestMessageSuppressionViewSetScope(SimpleTestCase):
+ """
+ Guards against the viewset silently reverting to scope_object='INTERNAL', which would bypass
+ hog_flow RBAC and let any project member manage suppressions regardless of workflow permissions.
+ """
+
+ def test_scope_object_is_hog_flow(self) -> None:
+ assert MessageSuppressionViewSet.scope_object == "hog_flow"
+
+ def test_mutating_actions_are_declared_as_writes(self) -> None:
+ # `add_suppression` and `remove_suppression` are custom @action endpoints; without being
+ # listed here they'd default to a read scope and slip past hog_flow:write enforcement.
+ assert set(MessageSuppressionViewSet.scope_object_write_actions) == {
+ "add_suppression",
+ "remove_suppression",
+ }
diff --git a/products/messaging/backend/services/test_customerio_import_service.py b/products/messaging/backend/services/test_customerio_import_service.py
index dae300ccacd8..ff5a89758c00 100644
--- a/products/messaging/backend/services/test_customerio_import_service.py
+++ b/products/messaging/backend/services/test_customerio_import_service.py
@@ -3,8 +3,6 @@ from io import StringIO
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
-from parameterized import parameterized
-
from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryType
from products.messaging.backend.models.message_preferences import MessageRecipientPreference, PreferenceStatus
@@ -17,85 +15,6 @@ class TestCustomerIOImportService(BaseTest):
self.api_key = "test-api-key"
self.service = CustomerIOImportService(self.team, self.api_key, self.user)
- @parameterized.expand(
- [
- # Test case 1: Valid preferences with topic_ prefix
- (
- {
- "email": "[email protected]",
- "id": "cio_123",
- "cio_subscription_preferences": '{"topics": {"topic_1": false, "topic_2": true}}',
- },
- {"status": "success", "email": "[email protected]", "opted_out_categories": ["cat_1"]},
- ),
- # Test case 2: Valid preferences without topic_ prefix
- (
- {
- "email": "[email protected]",
- "id": "cio_456",
- "cio_subscription_preferences": '{"topics": {"1": false, "2": false}}',
- },
- {"status": "success", "email": "[email protected]", "opted_out_categories": ["cat_1", "cat_2"]},
- ),
- # Test case 3: Empty preferences
- (
- {"email": "[email protected]", "id": "cio_789", "cio_subscription_preferences": ""},
- {"status": "success", "email": "[email protected]", "opted_out_categories": []},
- ),
- # Test case 4: Missing email - should use Customer.io ID
- (
- {"email": "", "id": "cio_999", "cio_subscription_preferences": '{"topics": {"1": false}}'},
- {"status": "error", "email": "Customer.io ID: cio_999", "error": "Missing email"},
- ),
- # Test case 5: Missing both email and ID
- (
- {"email": "", "id": "", "cio_subscription_preferences": '{"topics": {"1": false}}'},
- {"status": "error", "email": "unknown", "error": "Missing email"},
- ),
- # Test case 6: Invalid JSON in preferences
- (
- {"email": "[email protected]", "id": "cio_111", "cio_subscription_preferences": "invalid json"},
- {
- "status": "error",
- "email": "[email protected]",
- "error": "Invalid JSON: Expecting value: line 1 column 1 (char 0)",
- },
- ),
- # Test case 7: All topics subscribed (no opt-outs)
- (
- {
- "email": "[email protected]",
- "id": "cio_222",
- "cio_subscription_preferences": '{"topics": {"topic_1": true, "topic_2": true}}',
- },
- {"status": "success", "email": "[email protected]", "opted_out_categories": []},
- ),
- ]
- )
- def test_process_csv_row(self, row, expected_result):
- """Test CSV row processing with various input formats"""
- # Set up topic mapping
- self.service.topic_mapping = {
- "topic_1": "cat_1",
- "1": "cat_1",
- "topic_2": "cat_2",
- "2": "cat_2",
- }
-
- result = self.service._process_csv_row(row)
-
- # Check status and email
- assert result["status"] == expected_result["status"]
- assert result.get("email") == expected_result.get("email")
-
- # Check opted out categories (order doesn't matter)
- if "opted_out_categories" in expected_result:
- assert set(result.get("opted_out_categories", [])) == set(expected_result["opted_out_categories"])
-
- # Check error message (partial match for JSON errors)
- if "error" in expected_result:
- assert expected_result["error"][:20] in result.get("error", "")
-
def test_process_preferences_csv_complete_flow(self):
"""Test complete CSV processing flow with batching"""
# Create categories first
@@ -261,23 +180,6 @@ [email protected],cio_6,"{""topics"": {""topic_1"": true, ""topic_2"": true}}"
new_pref = MessageRecipientPreference.objects.get(team_id=self.team.id, identifier="[email protected]")
assert new_pref.preferences[str(cat1.id)] == PreferenceStatus.OPTED_OUT.value
- @patch("products.messaging.backend.services.customerio_import_service.CustomerIOClient")
- def test_api_import_with_invalid_credentials(self, mock_client_class):
- """Test API import handling of invalid credentials"""
- mock_client = MagicMock()
- mock_client_class.return_value = mock_client
-
- # Mock failed validation
- mock_client.validate_credentials.return_value = False
-
- # Run import
- result = self.service.import_api_data()
-
- # Check error handling
- assert result["status"] == "failed"
- assert len(result["errors"]) == 1
- assert "Invalid Customer.io API credentials" in result["errors"][0]
-
def test_process_csv_without_categories(self):
"""Test CSV processing when no categories exist"""
csv_content = """email,id,cio_subscription_preferences
@@ -293,18 +195,6 @@ [email protected],cio_1,"{""topics"": {""topic_1"": false}}"
assert result["status"] == "failed"
assert "No categories found" in result["details"]
- def test_api_import_without_api_key(self):
- """Test API import fails when API key is None"""
- service = CustomerIOImportService(self.team, api_key=None, user=self.user)
-
- # Run import without API key
- result = service.import_api_data()
-
- # Should fail with appropriate error
- assert result["status"] == "failed"
- assert len(result["errors"]) == 1
- assert "API key is required" in result["errors"][0]
-
def test_unique_user_tracking_across_api_and_csv(self):
"""Test that unique users are tracked correctly across API and CSV imports"""
# Simulate API import adding users
diff --git a/products/messaging/backend/services/test_customerio_import_service_unit.py b/products/messaging/backend/services/test_customerio_import_service_unit.py
new file mode 100644
index 000000000000..c7421f07d2c3
--- /dev/null
+++ b/products/messaging/backend/services/test_customerio_import_service_unit.py
@@ -0,0 +1,124 @@
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from .customerio_import_service import CustomerIOImportService
+
+
+class TestCustomerIOImportServiceUnit(SimpleTestCase):
+ def setUp(self):
+ super().setUp()
+ self.team = MagicMock()
+ self.user = MagicMock()
+ self.api_key = "test-api-key"
+ self.service = CustomerIOImportService(self.team, self.api_key, self.user)
+
+ @parameterized.expand(
+ [
+ # Test case 1: Valid preferences with topic_ prefix
+ (
+ {
+ "email": "[email protected]",
+ "id": "cio_123",
+ "cio_subscription_preferences": '{"topics": {"topic_1": false, "topic_2": true}}',
+ },
+ {"status": "success", "email": "[email protected]", "opted_out_categories": ["cat_1"]},
+ ),
+ # Test case 2: Valid preferences without topic_ prefix
+ (
+ {
+ "email": "[email protected]",
+ "id": "cio_456",
+ "cio_subscription_preferences": '{"topics": {"1": false, "2": false}}',
+ },
+ {"status": "success", "email": "[email protected]", "opted_out_categories": ["cat_1", "cat_2"]},
+ ),
+ # Test case 3: Empty preferences
+ (
+ {"email": "[email protected]", "id": "cio_789", "cio_subscription_preferences": ""},
+ {"status": "success", "email": "[email protected]", "opted_out_categories": []},
+ ),
+ # Test case 4: Missing email - should use Customer.io ID
+ (
+ {"email": "", "id": "cio_999", "cio_subscription_preferences": '{"topics": {"1": false}}'},
+ {"status": "error", "email": "Customer.io ID: cio_999", "error": "Missing email"},
+ ),
+ # Test case 5: Missing both email and ID
+ (
+ {"email": "", "id": "", "cio_subscription_preferences": '{"topics": {"1": false}}'},
+ {"status": "error", "email": "unknown", "error": "Missing email"},
+ ),
+ # Test case 6: Invalid JSON in preferences
+ (
+ {"email": "[email protected]", "id": "cio_111", "cio_subscription_preferences": "invalid json"},
+ {
+ "status": "error",
+ "email": "[email protected]",
+ "error": "Invalid JSON: Expecting value: line 1 column 1 (char 0)",
+ },
+ ),
+ # Test case 7: All topics subscribed (no opt-outs)
+ (
+ {
+ "email": "[email protected]",
+ "id": "cio_222",
+ "cio_subscription_preferences": '{"topics": {"topic_1": true, "topic_2": true}}',
+ },
+ {"status": "success", "email": "[email protected]", "opted_out_categories": []},
+ ),
+ ]
+ )
+ def test_process_csv_row(self, row, expected_result):
+ """Test CSV row processing with various input formats"""
+ # Set up topic mapping
+ self.service.topic_mapping = {
+ "topic_1": "cat_1",
+ "1": "cat_1",
+ "topic_2": "cat_2",
+ "2": "cat_2",
+ }
+
+ result = self.service._process_csv_row(row)
+
+ # Check status and email
+ assert result["status"] == expected_result["status"]
+ assert result.get("email") == expected_result.get("email")
+
+ # Check opted out categories (order doesn't matter)
+ if "opted_out_categories" in expected_result:
+ assert set(result.get("opted_out_categories", [])) == set(expected_result["opted_out_categories"])
+
+ # Check error message (partial match for JSON errors)
+ if "error" in expected_result:
+ assert expected_result["error"][:20] in result.get("error", "")
+
+ @patch("products.messaging.backend.services.customerio_import_service.CustomerIOClient")
+ def test_api_import_with_invalid_credentials(self, mock_client_class):
+ """Test API import handling of invalid credentials"""
+ mock_client = MagicMock()
+ mock_client_class.return_value = mock_client
+
+ # Mock failed validation
+ mock_client.validate_credentials.return_value = False
+
+ # Run import
+ result = self.service.import_api_data()
+
+ # Check error handling
+ assert result["status"] == "failed"
+ assert len(result["errors"]) == 1
+ assert "Invalid Customer.io API credentials" in result["errors"][0]
+
+ def test_api_import_without_api_key(self):
+ """Test API import fails when API key is None"""
+ service = CustomerIOImportService(self.team, api_key=None, user=self.user)
+
+ # Run import without API key
+ result = service.import_api_data()
+
+ # Should fail with appropriate error
+ assert result["status"] == "failed"
+ assert len(result["errors"]) == 1
+ assert "API key is required" in result["errors"][0]
diff --git a/products/messaging/backend/services/test_customerio_track_client.py b/products/messaging/backend/services/test_customerio_track_client.py
index 0b97c2a53b2b..3a1ac80e435b 100644
--- a/products/messaging/backend/services/test_customerio_track_client.py
+++ b/products/messaging/backend/services/test_customerio_track_client.py
@@ -1,11 +1,11 @@
from unittest.mock import MagicMock, patch
-from django.test import TestCase
+from django.test import SimpleTestCase
from products.messaging.backend.services.customerio_client import CustomerIOAPIError, CustomerIOTrackClient
-class TestCustomerIOTrackClient(TestCase):
+class TestCustomerIOTrackClient(SimpleTestCase):
def setUp(self):
self.track_client = CustomerIOTrackClient(site_id="site_abc", api_key="key_123", region="us")