Skip to content

Commit

Permalink
Improve backend test performance by patching password hashing
Browse files Browse the repository at this point in the history
* Patch password hashing during tests
  • Loading branch information
saltie2193 committed Oct 12, 2024
1 parent 6768359 commit 2e3b2a3
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
18 changes: 16 additions & 2 deletions backend/app/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,26 @@
from app.main import app
from app.models import Item, User
from app.tests.utils.user import authentication_token_from_email
from app.tests.utils.utils import get_superuser_token_headers
from app.tests.utils.utils import get_superuser_token_headers, patch_password_hashing


@pytest.fixture(scope="session")
def disable_password_hashing() -> Generator[None, None, None]:
with patch_password_hashing("app.core.security"):
yield


@pytest.fixture(scope="session", autouse=True)
def db() -> Generator[Session, None, None]:
def db(
disable_password_hashing: Generator[None, None, None], # noqa: ARG001
) -> Generator[Session, None, None]:
with Session(engine) as session:
# cleanup db to prevent interferences with tests
# all existing data will be deleted anyway after the tests run
session.execute(delete(User))
session.execute(delete(Item))
session.commit()

init_db(session)
yield session
statement = delete(Item)
Expand Down
23 changes: 23 additions & 0 deletions backend/app/tests/utils/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import random
import string
from collections.abc import Generator
from contextlib import contextmanager
from unittest.mock import patch

from fastapi.testclient import TestClient

Expand All @@ -24,3 +27,23 @@ def get_superuser_token_headers(client: TestClient) -> dict[str, str]:
a_token = tokens["access_token"]
headers = {"Authorization": f"Bearer {a_token}"}
return headers


@contextmanager
def patch_password_hashing(*modules: str) -> Generator[None, None, None]:
"""
Contextmanager to patch ``pwd_context`` in the given modules.
: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()

0 comments on commit 2e3b2a3

Please sign in to comment.