Coverage for docs_src/tutorial/fastapi/app_testing/tutorial001/test_main_006.py: 100%

27 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-09 00:02 +0000

1import pytest 1fabcde

2from fastapi.testclient import TestClient 1fabcde

3from sqlmodel import Session, SQLModel, create_engine 1fabcde

4from sqlmodel.pool import StaticPool 1fabcde

5 

6from .main import app, get_session 1fabcde

7 

8 

9@pytest.fixture(name="session") 1fabcde

10def session_fixture(): 1abcde

11 engine = create_engine( 1fabcde

12 "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool 

13 ) 

14 SQLModel.metadata.create_all(engine) 1fabcde

15 with Session(engine) as session: 1fabcde

16 yield session 1fabcde

17 

18 

19@pytest.fixture(name="client") # (1)! 1fabcde

20def client_fixture(session: Session): # (2)! 1fabcde

21 def get_session_override(): # (3)! 1fabcde

22 return session 1ghijklmnopqr

23 

24 app.dependency_overrides[get_session] = get_session_override # (4)! 1fabcde

25 

26 client = TestClient(app) # (5)! 1fabcde

27 yield client # (6)! 1fabcde

28 app.dependency_overrides.clear() # (7)! 1fabcde

29 

30 

31def test_create_hero(client: TestClient): # (8)! 1fabcde

32 response = client.post( 1ghijklmnopqr

33 "/heroes/", json={"name": "Deadpond", "secret_name": "Dive Wilson"} 

34 ) 

35 data = response.json() 1ghijklmnopqr

36 

37 assert response.status_code == 200 1ghijklmnopqr

38 assert data["name"] == "Deadpond" 1ghijklmnopqr

39 assert data["secret_name"] == "Dive Wilson" 1ghijklmnopqr

40 assert data["age"] is None 1ghijklmnopqr

41 assert data["id"] is not None 1ghijklmnopqr