Python FASTAPI Testing

From bibbleWiki
Jump to navigation Jump to search

Introduction

This page is to capture how to go about testing with FAST API

MonkeyPatch

So you can patch code for testing with monkey patch

monkeypatch.setattr("module.path.name", replacement)

Patch a Function

So you can

monkeypatch.setattr("module.path.get_user", lambda id: fake_user)

Which is like

jest.mock("./getUser", () => () => fakeUser)

Patch a module‑level variable

Setting a variable

monkeypatch.setattr(settings, "API_KEY", "test-key")

Which is like

jest.mock("./settings", () => ({ API_KEY: "test-key" }))

Patch an imported reference

If a module does

from server.encryptors.factory import get_encryptor

Then you can patch it like this

monkeypatch.setattr("server.module.that.uses.it.get_encryptor", fake)

Comparison to Jest

Here is a table to help compare terminology

Concept Jest pytest
Test setup beforeEach, beforeAll Fixtures (function, module, session scope)
Test teardown afterEach, afterAll Fixture finalizers / yield fixtures
Dependency injection Manual mocks, passing objects Fixture injection by name
Auto‑applied setup Global beforeEach in setup files @pytest.fixture(autouse=True)
Mocking jest.mock, jest.spyOn monkeypatch.setattr, unittest.mock.patch
Test data factories Helper functions Fixtures returning objects

Fixtures

These are things you create to set up a test. The autouse means you do not need to pass the fixture to the tests.

#  Force argon2 for testing purposes
@pytest.fixture(autouse=True)
def force_argon2(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr(settings, "authentication_encryptor", EncryptorNames.ARGON2.value)
    monkeypatch.setattr(user_management.password_manager, "encryptor", get_encryptor(EncryptorNames.ARGON2))