Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡️ Improve backend test performance by patching password hashing #1389

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
19 changes: 19 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 ExitStack, contextmanager
from unittest.mock import patch

from fastapi.testclient import TestClient

Expand All @@ -24,3 +27,19 @@ 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:
"""
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
Loading