Skip to content

Commit 2e3b2a3

Browse files
committedOct 12, 2024
Improve backend test performance by patching password hashing
* Patch password hashing during tests
1 parent 6768359 commit 2e3b2a3

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed
 

‎backend/app/tests/conftest.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,26 @@
99
from app.main import app
1010
from app.models import Item, User
1111
from app.tests.utils.user import authentication_token_from_email
12-
from app.tests.utils.utils import get_superuser_token_headers
12+
from app.tests.utils.utils import get_superuser_token_headers, patch_password_hashing
13+
14+
15+
@pytest.fixture(scope="session")
16+
def disable_password_hashing() -> Generator[None, None, None]:
17+
with patch_password_hashing("app.core.security"):
18+
yield
1319

1420

1521
@pytest.fixture(scope="session", autouse=True)
16-
def db() -> Generator[Session, None, None]:
22+
def db(
23+
disable_password_hashing: Generator[None, None, None], # noqa: ARG001
24+
) -> Generator[Session, None, None]:
1725
with Session(engine) as session:
26+
# cleanup db to prevent interferences with tests
27+
# all existing data will be deleted anyway after the tests run
28+
session.execute(delete(User))
29+
session.execute(delete(Item))
30+
session.commit()
31+
1832
init_db(session)
1933
yield session
2034
statement = delete(Item)

‎backend/app/tests/utils/utils.py

+23
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import random
22
import string
3+
from collections.abc import Generator
4+
from contextlib import contextmanager
5+
from unittest.mock import patch
36

47
from fastapi.testclient import TestClient
58

@@ -24,3 +27,23 @@ def get_superuser_token_headers(client: TestClient) -> dict[str, str]:
2427
a_token = tokens["access_token"]
2528
headers = {"Authorization": f"Bearer {a_token}"}
2629
return headers
30+
31+
32+
@contextmanager
33+
def patch_password_hashing(*modules: str) -> Generator[None, None, None]:
34+
"""
35+
Contextmanager to patch ``pwd_context`` in the given modules.
36+
:param modules: list of modules to patch.
37+
:return:
38+
"""
39+
patchers = []
40+
for module in modules:
41+
patcher_p = patch(f"{module}.pwd_context.verify", lambda x, y: x == y)
42+
patcher_h = patch(f"{module}.pwd_context.hash", lambda x: x)
43+
patcher_p.start()
44+
patcher_h.start()
45+
46+
patchers.extend((patcher_p, patcher_h))
47+
yield
48+
for patcher in patchers:
49+
patcher.stop()

0 commit comments

Comments
 (0)
Failed to load comments.