Skip to content

Commit df0d2da

Browse files
committed
Improve test setup
Signed-off-by: Vikram Vaswani <112123850+vikram-dagger@users.noreply.github.com>
1 parent e7cbf9b commit df0d2da

File tree

4 files changed

+27
-6
lines changed

4 files changed

+27
-6
lines changed

conftest.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
import pytest
23
from sqlalchemy import create_engine, inspect
34
from sqlalchemy.orm import sessionmaker
@@ -6,6 +7,12 @@
67
from .dependencies import get_db, database_url
78
from .models import Base
89

10+
@pytest.fixture(autouse=True)
11+
def clean_books_table(test_db):
12+
"""Truncate books table before each test to avoid unique constraint errors."""
13+
test_db.execute("TRUNCATE TABLE books RESTART IDENTITY CASCADE;")
14+
test_db.commit()
15+
916
@pytest.fixture(scope="session")
1017
def test_engine():
1118
"""Create test database engine"""

db.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
DROP TABLE books;
1+
DROP TABLE IF EXISTS books;
22

33
CREATE TABLE books (
44
id SERIAL PRIMARY KEY,

docker-compose.yml

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,15 @@ services:
88
environment:
99
- DATABASE_URL=postgresql://app_user:secret@db/app_db
1010
depends_on:
11-
- db
11+
db:
12+
condition: service_healthy
13+
networks:
14+
- app_network
1215

1316
db:
14-
image: postgres:15
17+
image: postgres:15-alpine
1518
container_name: fastapi_db
16-
restart: always
19+
restart: unless-stopped
1720
environment:
1821
POSTGRES_DB: app_db
1922
POSTGRES_USER: app_user
@@ -22,7 +25,19 @@ services:
2225
- "5432:5432"
2326
volumes:
2427
- postgres_data:/var/lib/postgresql/data
25-
- ./db.sql:/docker-entrypoint-initdb.d/db.sql
28+
healthcheck:
29+
test: ["CMD-SHELL", "pg_isready -U app_user -d app_db"]
30+
interval: 10s
31+
timeout: 5s
32+
retries: 5
33+
start_period: 10s
34+
networks:
35+
- app_network
36+
37+
networks:
38+
app_network:
39+
driver: bridge
2640

2741
volumes:
2842
postgres_data:
43+
driver: local

test_main.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from .repositories import create_book, get_books, get_book, update_book, delete_book
22
from .models import BookIn
33
from sqlalchemy import create_engine, inspect
4-
# from . import TEST_BOOKS
54

65
# Test data constants
76
TEST_BOOKS = [

0 commit comments

Comments
 (0)