From 85712f8c26fb374b5e4a1a737c9e8f95931fab60 Mon Sep 17 00:00:00 2001 From: saltie2193 Date: Thu, 10 Oct 2024 13:51:33 +0200 Subject: [PATCH] Use `contextlib.ExitStack` for managing multiple patchers --- backend/app/tests/utils/utils.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/backend/app/tests/utils/utils.py b/backend/app/tests/utils/utils.py index 8363cf590af..c1ba93fd13d 100644 --- a/backend/app/tests/utils/utils.py +++ b/backend/app/tests/utils/utils.py @@ -1,7 +1,7 @@ import random import string from collections.abc import Generator -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager from unittest.mock import patch from fastapi.testclient import TestClient @@ -36,14 +36,10 @@ def patch_password_hashing(*modules: str) -> Generator[None, None, None]: :param modules: list of modules to patch. :return: """ - patchers = [] - for module in modules: - patcher_p = patch(f"{module}.pwd_context.verify", lambda x, y: x == y) - patcher_h = patch(f"{module}.pwd_context.hash", lambda x: x) - patcher_p.start() - patcher_h.start() - - patchers.extend((patcher_p, patcher_h)) - yield - for patcher in patchers: - patcher.stop() + with ExitStack() as stack: + for module in modules: + stack.enter_context( + patch(f"{module}.pwd_context.verify", lambda x, y: x == y) + ) + stack.enter_context(patch(f"{module}.pwd_context.hash", lambda x: x)) + yield