Testing FastAPI CRUD operations with SQLModel instead of SQLAlchmey #673
-
First Check
Commit to Help
Example Code# conftest.py
import pytest
import sqlite3
from starlette.testclient import TestClient
from app.auth import settings
from app.main import app
@pytest.fixture
def ro_client():
client_instance = TestClient(app)
client_instance.headers["X-API-KEY"] = settings.ro_api_key
return client_instance
@pytest.fixture
def rw_client():
client_instance = TestClient(app)
client_instance.headers["X-API-KEY"] = settings.rw_api_key
return client_instance
@pytest.fixture(autouse=True, scope="session")
def in_memory_db():
# Connect to an in-memory database
memory_conn = sqlite3.connect(":memory:")
memory_cur = memory_conn.cursor()
# Attach the on-disk database to the in-memory database connection
memory_conn.execute(
f"ATTACH DATABASE '{settings.db_path}{settings.db_name}' AS ondisk"
)
# Get the list of tables from the on-disk database
memory_cur.execute("SELECT name FROM ondisk.sqlite_master WHERE type='table'")
tables = memory_cur.fetchall()
# Copy each table's data from the on-disk database to the in-memory database
for table in tables:
table_name = table[0]
memory_cur.execute(
f"CREATE TABLE {table_name} AS SELECT * FROM ondisk.{table_name}"
)
yield memory_conn # This connection will be used in your tests
# Cleanup: Close the in-memory database connection
memory_conn.close()
# test_models.py
def test_create_location(rw_client):
endpoint = "/v1/locations"
response = rw_client.post(
endpoint,
json={
"name": "Archery Club",
"slug": "archery-club",
"city": "Anytown",
"state": "Archeryville",
},
)
assert response.status_code == 200, response.text
data = response.json()
assert data["name"] == "Archery Club"
assert data["slug"] == "archery-club"
assert data["city"] == "Anytown"
assert data["state"] == "Archeryville"
assert "id" in data
|
Beta Was this translation helpful? Give feedback.
Answered by
gazpachoking
Nov 8, 2023
Replies: 1 comment
-
You have a fixture that's yielding a connection to an in memory database, but you aren't doing anything with it. You'll have to override how your app interacts with the database to tell it to use the in memory database rather than the normal one. There is an example how to do that here https://sqlmodel.tiangolo.com/tutorial/fastapi/tests/ |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have a fixture that's yielding a connection to an in memory database, but you aren't doing anything with it. You'll have to override how your app interacts with the database to tell it to use the in memory database rather than the normal one. There is an example how to do that here https://sqlmodel.tiangolo.com/tutorial/fastapi/tests/