From 1ffc3239387bcfadbd8aecfdfacf3d6b52b947f8 Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Sat, 28 Sep 2024 21:13:13 +0300 Subject: [PATCH] plugin: unconfigure should `restore` not `unblock` `restore` pops the `block` in `_setup_django`, while `unblock` pushes an unblock. We want to leave things clean, so should `restore`. --- pytest_django/plugin.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/pytest_django/plugin.py b/pytest_django/plugin.py index 669e7841..285f1733 100644 --- a/pytest_django/plugin.py +++ b/pytest_django/plugin.py @@ -477,10 +477,13 @@ def get_order_number(test: pytest.Item) -> int: def pytest_unconfigure(config: pytest.Config) -> None: - if blocking_manager_key not in config.stash: - return - blocking_manager = config.stash[blocking_manager_key] - blocking_manager.unblock() + # Undo the block() in _setup_django(), if it happenned. + # It's also possible the user forgot to call restore(). + # We can warn about it, but let's just clean it up. + if blocking_manager_key in config.stash: + blocking_manager = config.stash[blocking_manager_key] + while blocking_manager.is_active: + blocking_manager.restore() @pytest.fixture(autouse=True, scope="session") @@ -852,6 +855,11 @@ def restore(self) -> None: """ self._dj_db_wrapper.ensure_connection = self._history.pop() + @property + def is_active(self) -> bool: + """Whether a block() or unblock() is currently active.""" + return bool(self._history) + # On Config.stash. blocking_manager_key = pytest.StashKey[DjangoDbBlocker]()