Last active
April 15, 2023 13:33
-
-
Save MaxHalford/3554a0427a775c70bbaf8145a70f8385 to your computer and use it in GitHub Desktop.
Interact with FastAPI TestClient using requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from app.main import app | |
from app.db import engine, get_session | |
from fastapi.testclient import TestClient | |
import pytest | |
import requests | |
import sqlmodel | |
import sqlmodel.pool | |
@pytest.fixture(name="session") | |
def session_fixture(): | |
engine = sqlmodel.create_engine( | |
"sqlite://", | |
connect_args={"check_same_thread": False}, | |
poolclass=sqlmodel.pool.StaticPool, | |
) | |
sqlmodel.SQLModel.metadata.create_all(engine) | |
with sqlmodel.Session(engine) as session: | |
yield session | |
@pytest.fixture(name="client") | |
def client_fixture(session: sqlmodel.Session): | |
def get_session_override(): | |
yield session | |
app.dependency_overrides[get_session] = get_session_override | |
client = TestClient(app) | |
requests.get = client.get # This is the line that matters | |
yield client | |
app.dependency_overrides.clear() | |
def test_index(client): | |
response = requests.get("/docs") | |
assert response.status_code == 200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment