|
5 | 5 |
|
6 | 6 | import pytest |
7 | 7 | from django.db import transaction as django_transaction |
| 8 | +from django.test import override_settings |
8 | 9 |
|
9 | 10 | from django_subatomic import db, test |
10 | 11 |
|
@@ -46,6 +47,38 @@ def test_callbacks_not_executed_in_normal_test_case(self) -> None: |
46 | 47 | with test.part_of_a_transaction(): |
47 | 48 | db.run_after_commit(_callback_which_should_not_be_called) |
48 | 49 |
|
| 50 | + def test_dangling_callbacks_cause_an_error_on_enter(self) -> None: |
| 51 | + """ |
| 52 | + Pre-existing callbacks will be detected and cause an error. |
| 53 | + """ |
| 54 | + # Django's `atomic` leaves dangling after-commit callbacks |
| 55 | + # on the test case's transaction. |
| 56 | + with django_transaction.atomic(): |
| 57 | + django_transaction.on_commit(_callback_which_should_not_be_called) |
| 58 | + |
| 59 | + # Ignoring private API here because it's the only way to test this guardrail. |
| 60 | + with pytest.raises(test._UnhandledCallbacks) as exc_info: # noqa: SLF001 |
| 61 | + with test.part_of_a_transaction(): |
| 62 | + ... |
| 63 | + |
| 64 | + assert exc_info.value.callbacks == (_callback_which_should_not_be_called,) |
| 65 | + |
| 66 | + def test_dangling_callbacks_detection_can_be_disabled(self) -> None: |
| 67 | + """ |
| 68 | + Pre-existing callbacks can be ignored with a setting. |
| 69 | + """ |
| 70 | + # Django's `atomic` leaves dangling after-commit callbacks |
| 71 | + # on the test case's transaction. |
| 72 | + with django_transaction.atomic(): |
| 73 | + django_transaction.on_commit(_callback_which_should_not_be_called) |
| 74 | + |
| 75 | + # This setting suppresses the guardrail. |
| 76 | + with override_settings( |
| 77 | + SUBATOMIC_CATCH_UNHANDLED_AFTER_COMMIT_CALLBACKS_IN_TESTS=False |
| 78 | + ): |
| 79 | + with test.part_of_a_transaction(): |
| 80 | + ... |
| 81 | + |
49 | 82 | def test_remaining_callbacks_cleared_on_exit(self) -> None: |
50 | 83 | """ |
51 | 84 | Any callbacks left at the end of the block are cleared out. |
|
0 commit comments