Skip to content

Instantly share code, notes, and snippets.

@MaxHalford
Last active April 15, 2023 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxHalford/3554a0427a775c70bbaf8145a70f8385 to your computer and use it in GitHub Desktop.
Save MaxHalford/3554a0427a775c70bbaf8145a70f8385 to your computer and use it in GitHub Desktop.
Interact with FastAPI TestClient using requests
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