mirror of
https://github.com/fastapi/fastapi.git
synced 2026-01-06 04:57:58 -05:00
📝 Add an example of setting up a test database (#1144)
* Add an example of setting up a test database. * 📝 Add/update docs for testing a DB with dependency overrides * 🔧 Update test script, remove line removing test file as it is removed during testing * ✅ Update testing coverage pragma Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
This commit is contained in:
0
docs_src/sql_databases/sql_app/tests/__init__.py
Normal file
0
docs_src/sql_databases/sql_app/tests/__init__.py
Normal file
47
docs_src/sql_databases/sql_app/tests/test_sql_app.py
Normal file
47
docs_src/sql_databases/sql_app/tests/test_sql_app.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from ..database import Base
|
||||
from ..main import app, get_db
|
||||
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
)
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
|
||||
def override_get_db():
|
||||
try:
|
||||
db = TestingSessionLocal()
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_create_user():
|
||||
response = client.post(
|
||||
"/users/",
|
||||
json={"email": "deadpool@example.com", "password": "chimichangas4life"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == "deadpool@example.com"
|
||||
assert "id" in data
|
||||
user_id = data["id"]
|
||||
|
||||
response = client.get(f"/users/{user_id}")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["email"] == "deadpool@example.com"
|
||||
assert data["id"] == user_id
|
||||
Reference in New Issue
Block a user