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

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))