|
| 1 | +import importlib |
1 | 2 | import unittest |
2 | 3 |
|
3 | 4 | import mock |
| 5 | +import posthog |
4 | 6 |
|
5 | 7 | from posthog.client import Client |
6 | 8 | from posthog.test.test_utils import FAKE_TEST_API_KEY |
@@ -216,3 +218,58 @@ def scrub_pii(event): |
216 | 218 | self.assertEqual(enqueued_msg["properties"]["email"], "***@example.com") |
217 | 219 | self.assertNotIn("credit_card", enqueued_msg["properties"]) |
218 | 220 | self.assertEqual(enqueued_msg["properties"]["form_name"], "contact") |
| 221 | + |
| 222 | + |
| 223 | +class TestModuleLevelBeforeSend(unittest.TestCase): |
| 224 | + def setUp(self): |
| 225 | + importlib.reload(posthog) |
| 226 | + |
| 227 | + def tearDown(self): |
| 228 | + if posthog.default_client: |
| 229 | + posthog.shutdown() |
| 230 | + importlib.reload(posthog) |
| 231 | + |
| 232 | + def test_before_send_callback_used_during_module_level_setup(self): |
| 233 | + def my_before_send(event): |
| 234 | + event["properties"]["module_level_before_send"] = True |
| 235 | + return event |
| 236 | + |
| 237 | + with mock.patch("posthog.client.batch_post") as mock_post: |
| 238 | + posthog.api_key = FAKE_TEST_API_KEY |
| 239 | + posthog.before_send = my_before_send |
| 240 | + posthog.sync_mode = True |
| 241 | + |
| 242 | + msg_uuid = posthog.capture("test_event", distinct_id="user1") |
| 243 | + |
| 244 | + self.assertIsNotNone(msg_uuid) |
| 245 | + self.assertIs(posthog.default_client.before_send, my_before_send) |
| 246 | + |
| 247 | + mock_post.assert_called_once() |
| 248 | + batch_data = mock_post.call_args[1]["batch"] |
| 249 | + enqueued_msg = batch_data[0] |
| 250 | + self.assertTrue(enqueued_msg["properties"]["module_level_before_send"]) |
| 251 | + |
| 252 | + def test_before_send_callback_updates_after_client_initialization(self): |
| 253 | + def my_before_send(event): |
| 254 | + event["properties"]["updated_after_init"] = True |
| 255 | + return event |
| 256 | + |
| 257 | + with mock.patch("posthog.client.batch_post") as mock_post: |
| 258 | + posthog.api_key = FAKE_TEST_API_KEY |
| 259 | + posthog.sync_mode = True |
| 260 | + |
| 261 | + first_msg_uuid = posthog.capture("first_event", distinct_id="user1") |
| 262 | + |
| 263 | + posthog.before_send = my_before_send |
| 264 | + second_msg_uuid = posthog.capture("second_event", distinct_id="user1") |
| 265 | + |
| 266 | + self.assertIsNotNone(first_msg_uuid) |
| 267 | + self.assertIsNotNone(second_msg_uuid) |
| 268 | + self.assertIs(posthog.default_client.before_send, my_before_send) |
| 269 | + |
| 270 | + self.assertEqual(mock_post.call_count, 2) |
| 271 | + first_batch = mock_post.call_args_list[0][1]["batch"] |
| 272 | + second_batch = mock_post.call_args_list[1][1]["batch"] |
| 273 | + |
| 274 | + self.assertNotIn("updated_after_init", first_batch[0]["properties"]) |
| 275 | + self.assertTrue(second_batch[0]["properties"]["updated_after_init"]) |
0 commit comments