|
4 | 4 | Classes: |
5 | 5 | EventsToolingTest: Test events tooling. |
6 | 6 | """ |
| 7 | +import base64 |
7 | 8 | import datetime |
8 | 9 | import sys |
9 | 10 | from contextlib import contextmanager |
10 | | -from unittest.mock import Mock, patch |
| 11 | +from unittest.mock import ANY, Mock, patch |
11 | 12 | from uuid import UUID, uuid1 |
12 | 13 |
|
13 | 14 | import attr |
14 | 15 | import ddt |
15 | 16 | import pytest |
16 | | -from django.test import TestCase, override_settings |
| 17 | +from django.db import transaction |
| 18 | +from django.test import TestCase, TransactionTestCase, override_settings |
17 | 19 |
|
18 | 20 | from openedx_events.data import EventsMetadata |
19 | 21 | from openedx_events.exceptions import SenderValidationError |
| 22 | +from openedx_events.learning.data import UserData, UserPersonalData |
| 23 | +from openedx_events.learning.signals import SESSION_LOGIN_COMPLETED |
20 | 24 | from openedx_events.testing import FreezeSignalCacheMixin |
21 | 25 | from openedx_events.tooling import OpenEdxPublicSignal, _process_all_signals_modules, load_all_signals |
22 | 26 |
|
@@ -257,7 +261,8 @@ def test_send_event_with_custom_metadata(self, mock_send_event_with_metadata): |
257 | 261 |
|
258 | 262 | assert response == expected_response |
259 | 263 | mock_send_event_with_metadata.assert_called_once_with( |
260 | | - metadata=metadata, send_robust=True, foo="bar", from_event_bus=True |
| 264 | + metadata=metadata, send_robust=True, foo="bar", from_event_bus=True, |
| 265 | + send_on_commit=False, send_async=False, |
261 | 266 | ) |
262 | 267 |
|
263 | 268 | @ddt.data( |
@@ -333,6 +338,225 @@ def test_send_event_disabled(self, send_mock): |
333 | 338 | self.assertListEqual([], result) |
334 | 339 |
|
335 | 340 |
|
| 341 | +def _make_user_data(): |
| 342 | + """Build a UserData payload for the real SESSION_LOGIN_COMPLETED signal.""" |
| 343 | + return UserData( |
| 344 | + pii=UserPersonalData(username="alice", email="alice@example.com", name="Alice"), |
| 345 | + id=1, |
| 346 | + is_active=True, |
| 347 | + ) |
| 348 | + |
| 349 | + |
| 350 | +class SendEventOnCommitTests(TestCase): |
| 351 | + """ |
| 352 | + Tests for the ``send_on_commit`` parameter of ``send_event``. |
| 353 | +
|
| 354 | + Uses ``TestCase.captureOnCommitCallbacks`` to observe callbacks that |
| 355 | + ``transaction.on_commit`` registers inside the outer test-level |
| 356 | + transaction. |
| 357 | + """ |
| 358 | + |
| 359 | + def setUp(self): |
| 360 | + super().setUp() |
| 361 | + self.receiver = Mock(return_value="ok") |
| 362 | + SESSION_LOGIN_COMPLETED.connect(self.receiver) |
| 363 | + self.addCleanup(SESSION_LOGIN_COMPLETED.disconnect, self.receiver) |
| 364 | + |
| 365 | + def test_send_on_commit_defers_until_commit(self): |
| 366 | + """ |
| 367 | + With ``send_on_commit=True`` inside a transaction, the receiver is |
| 368 | + only called once the enclosing transaction commits. |
| 369 | + """ |
| 370 | + with self.captureOnCommitCallbacks(execute=False) as callbacks: |
| 371 | + result = SESSION_LOGIN_COMPLETED.send_event( |
| 372 | + send_on_commit=True, user=_make_user_data(), |
| 373 | + ) |
| 374 | + |
| 375 | + self.receiver.assert_not_called() |
| 376 | + self.assertEqual(result, []) |
| 377 | + self.assertEqual(len(callbacks), 1) |
| 378 | + |
| 379 | + # Now "commit" and verify receiver runs. |
| 380 | + for cb in callbacks: |
| 381 | + cb() |
| 382 | + self.receiver.assert_called_once() |
| 383 | + |
| 384 | + def test_send_on_commit_callback_runs_receiver(self): |
| 385 | + """ |
| 386 | + Executing the captured ``on_commit`` callback (simulating a commit) |
| 387 | + triggers the receiver, verifying that the work registered under the |
| 388 | + callback is the actual signal send. |
| 389 | + """ |
| 390 | + with self.captureOnCommitCallbacks(execute=True): |
| 391 | + SESSION_LOGIN_COMPLETED.send_event( |
| 392 | + send_on_commit=True, user=_make_user_data(), |
| 393 | + ) |
| 394 | + self.receiver.assert_called_once() |
| 395 | + |
| 396 | + |
| 397 | +class SendEventOnCommitRollbackTests(TransactionTestCase): |
| 398 | + """ |
| 399 | + Tests that ``send_on_commit`` suppresses sending when the transaction |
| 400 | + rolls back. Uses ``TransactionTestCase`` so transactions actually commit |
| 401 | + and roll back. |
| 402 | + """ |
| 403 | + |
| 404 | + def setUp(self): |
| 405 | + super().setUp() |
| 406 | + self.receiver = Mock(return_value="ok") |
| 407 | + SESSION_LOGIN_COMPLETED.connect(self.receiver) |
| 408 | + self.addCleanup(SESSION_LOGIN_COMPLETED.disconnect, self.receiver) |
| 409 | + |
| 410 | + def test_send_on_commit_immediate_when_no_transaction(self): |
| 411 | + """ |
| 412 | + Outside any transaction, ``send_on_commit=True`` sends immediately |
| 413 | + (per Django's ``transaction.on_commit`` contract). |
| 414 | + """ |
| 415 | + SESSION_LOGIN_COMPLETED.send_event( |
| 416 | + send_on_commit=True, user=_make_user_data(), |
| 417 | + ) |
| 418 | + self.receiver.assert_called_once() |
| 419 | + |
| 420 | + def test_send_on_commit_not_sent_on_rollback(self): |
| 421 | + """ |
| 422 | + If the transaction rolls back, the on_commit callback is never run, |
| 423 | + so the event is not sent. |
| 424 | + """ |
| 425 | + class _Rollback(Exception): |
| 426 | + pass |
| 427 | + |
| 428 | + with self.assertRaises(_Rollback): |
| 429 | + with transaction.atomic(): |
| 430 | + SESSION_LOGIN_COMPLETED.send_event( |
| 431 | + send_on_commit=True, user=_make_user_data(), |
| 432 | + ) |
| 433 | + raise _Rollback() |
| 434 | + |
| 435 | + self.receiver.assert_not_called() |
| 436 | + |
| 437 | + |
| 438 | +class SendEventAsyncTests(TestCase): |
| 439 | + """ |
| 440 | + Tests for the ``send_async`` parameter of ``send_event``. |
| 441 | + """ |
| 442 | + |
| 443 | + def setUp(self): |
| 444 | + super().setUp() |
| 445 | + self.receiver = Mock(return_value="ok") |
| 446 | + SESSION_LOGIN_COMPLETED.connect(self.receiver) |
| 447 | + self.addCleanup(SESSION_LOGIN_COMPLETED.disconnect, self.receiver) |
| 448 | + |
| 449 | + @patch("openedx_events.tasks.send_async_event.delay") |
| 450 | + def test_send_async_dispatches_celery_task(self, mock_delay): |
| 451 | + """ |
| 452 | + With ``send_async=True``, the receiver is not called synchronously. |
| 453 | + Instead a Celery task is dispatched with the serialized event data. |
| 454 | + """ |
| 455 | + result = SESSION_LOGIN_COMPLETED.send_event( |
| 456 | + send_async=True, user=_make_user_data(), |
| 457 | + ) |
| 458 | + |
| 459 | + self.assertEqual(result, []) |
| 460 | + self.receiver.assert_not_called() |
| 461 | + mock_delay.assert_called_once_with( |
| 462 | + SESSION_LOGIN_COMPLETED.event_type, ANY, ANY, |
| 463 | + ) |
| 464 | + _, metadata_json, event_data_b64 = mock_delay.call_args.args |
| 465 | + # The metadata round-trips through JSON. |
| 466 | + self.assertEqual( |
| 467 | + EventsMetadata.from_json(metadata_json).event_type, |
| 468 | + SESSION_LOGIN_COMPLETED.event_type, |
| 469 | + ) |
| 470 | + # The event data is valid base64. |
| 471 | + base64.b64decode(event_data_b64) |
| 472 | + |
| 473 | + def test_send_async_task_sends_event(self): |
| 474 | + """ |
| 475 | + End-to-end: when ``send_async=True``, running the dispatched Celery |
| 476 | + task synchronously delivers the event to the receiver with the same |
| 477 | + metadata and a payload that round-trips through Avro. |
| 478 | + """ |
| 479 | + captured = {} |
| 480 | + |
| 481 | + def _capture_delay(event_type, metadata_json, event_data_b64): |
| 482 | + captured["args"] = (event_type, metadata_json, event_data_b64) |
| 483 | + |
| 484 | + with patch("openedx_events.tasks.send_async_event.delay", side_effect=_capture_delay): |
| 485 | + SESSION_LOGIN_COMPLETED.send_event( |
| 486 | + send_async=True, user=_make_user_data(), |
| 487 | + ) |
| 488 | + |
| 489 | + self.receiver.assert_not_called() |
| 490 | + |
| 491 | + # Now run the task body directly, simulating a Celery worker. |
| 492 | + from openedx_events.tasks import send_async_event # pylint: disable=import-outside-toplevel |
| 493 | + send_async_event(*captured["args"]) |
| 494 | + |
| 495 | + self.receiver.assert_called_once() |
| 496 | + call_kwargs = self.receiver.call_args.kwargs |
| 497 | + self.assertEqual(call_kwargs["signal"], SESSION_LOGIN_COMPLETED) |
| 498 | + self.assertEqual(call_kwargs["user"], _make_user_data()) |
| 499 | + self.assertEqual(call_kwargs["metadata"].event_type, SESSION_LOGIN_COMPLETED.event_type) |
| 500 | + self.assertEqual(call_kwargs["from_event_bus"], False) |
| 501 | + |
| 502 | + |
| 503 | +class SendEventAsyncOnCommitTests(TestCase): |
| 504 | + """ |
| 505 | + Tests combining ``send_on_commit=True`` with ``send_async=True``: the |
| 506 | + Celery task dispatch should be deferred until the transaction commits. |
| 507 | + """ |
| 508 | + |
| 509 | + def setUp(self): |
| 510 | + super().setUp() |
| 511 | + self.receiver = Mock(return_value="ok") |
| 512 | + SESSION_LOGIN_COMPLETED.connect(self.receiver) |
| 513 | + self.addCleanup(SESSION_LOGIN_COMPLETED.disconnect, self.receiver) |
| 514 | + |
| 515 | + @patch("openedx_events.tasks.send_async_event.delay") |
| 516 | + def test_async_on_commit_defers_dispatch(self, mock_delay): |
| 517 | + """ |
| 518 | + ``send_async=True`` + ``send_on_commit=True`` in a transaction: the |
| 519 | + Celery dispatch is registered as an on_commit callback, not invoked |
| 520 | + immediately. |
| 521 | + """ |
| 522 | + with self.captureOnCommitCallbacks(execute=False) as callbacks: |
| 523 | + SESSION_LOGIN_COMPLETED.send_event( |
| 524 | + send_async=True, send_on_commit=True, user=_make_user_data(), |
| 525 | + ) |
| 526 | + |
| 527 | + mock_delay.assert_not_called() |
| 528 | + self.assertEqual(len(callbacks), 1) |
| 529 | + |
| 530 | + for cb in callbacks: |
| 531 | + cb() |
| 532 | + mock_delay.assert_called_once() |
| 533 | + |
| 534 | + |
| 535 | +class SendEventAsyncOnCommitRollbackTests(TransactionTestCase): |
| 536 | + """Rollback behavior for ``send_async`` + ``send_on_commit``.""" |
| 537 | + |
| 538 | + def setUp(self): |
| 539 | + super().setUp() |
| 540 | + self.receiver = Mock(return_value="ok") |
| 541 | + SESSION_LOGIN_COMPLETED.connect(self.receiver) |
| 542 | + self.addCleanup(SESSION_LOGIN_COMPLETED.disconnect, self.receiver) |
| 543 | + |
| 544 | + @patch("openedx_events.tasks.send_async_event.delay") |
| 545 | + def test_async_on_commit_not_dispatched_on_rollback(self, mock_delay): |
| 546 | + class _Rollback(Exception): |
| 547 | + pass |
| 548 | + |
| 549 | + with self.assertRaises(_Rollback): |
| 550 | + with transaction.atomic(): |
| 551 | + SESSION_LOGIN_COMPLETED.send_event( |
| 552 | + send_async=True, send_on_commit=True, user=_make_user_data(), |
| 553 | + ) |
| 554 | + raise _Rollback() |
| 555 | + |
| 556 | + mock_delay.assert_not_called() |
| 557 | + self.receiver.assert_not_called() |
| 558 | + |
| 559 | + |
336 | 560 | class TestLoadAllSignals(FreezeSignalCacheMixin, TestCase): |
337 | 561 | """ Tests for the load_all_signals method""" |
338 | 562 | def setUp(self): |
|
0 commit comments