59 lines
2.3 KiB
Python
59 lines
2.3 KiB
Python
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from main import app, get_db
|
|
from models import Base
|
|
|
|
TEST_DB = "sqlite:///./test.db"
|
|
test_engine = create_engine(TEST_DB, connect_args={"check_same_thread": False})
|
|
TestSession = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
|
|
Base.metadata.create_all(bind=test_engine)
|
|
|
|
def override_get_db():
|
|
db = TestSession()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
app.dependency_overrides[get_db] = override_get_db
|
|
client = TestClient(app)
|
|
|
|
def test_create_todo():
|
|
response = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
|
|
assert response.status_code == 201
|
|
data = response.json()
|
|
assert "id" in data
|
|
|
|
def test_list_todos():
|
|
client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
|
|
response = client.get('/todos/')
|
|
assert response.status_code == 200
|
|
assert len(response.json()) >= 1
|
|
|
|
def test_get_todo_by_id():
|
|
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
|
|
item_id = created['id']
|
|
response = client.get(f'/todos/{item_id}')
|
|
assert response.status_code == 200
|
|
assert response.json()['id'] == item_id
|
|
|
|
def test_get_todo_not_found():
|
|
response = client.get('/todos/99999')
|
|
assert response.status_code == 404
|
|
|
|
def test_update_todo():
|
|
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
|
|
item_id = created['id']
|
|
response = client.put(f'/todos/{item_id}', json={"title": "Updated title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
|
|
assert response.status_code == 200
|
|
|
|
def test_delete_todo():
|
|
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
|
|
item_id = created['id']
|
|
response = client.delete(f'/todos/{item_id}')
|
|
assert response.status_code == 204
|
|
response = client.get(f'/todos/{item_id}')
|
|
assert response.status_code == 404
|