11import os
22from pathlib import Path
3+ import pytest
34from django .conf import settings
5+ from django .db import connections
6+ import django
47
58ROOT_DIR = Path (__file__ ).parent .parent
69PG_USER = os .environ .get ("PG_USER" , "postgres" )
@@ -12,22 +15,22 @@ def pytest_configure():
1215 "default" : {
1316 "HOST" : "localhost" ,
1417 "PORT" : 5432 ,
15- "NAME" : "test " ,
18+ "NAME" : "postgres " ,
1619 "USER" : PG_USER ,
1720 "ENGINE" : "django.db.backends.postgresql_psycopg2" ,
1821 },
1922 "other" : {
2023 "HOST" : "localhost" ,
2124 "PORT" : 5432 ,
22- "NAME" : "test_alternative " ,
25+ "NAME" : "postgres " ,
2326 "USER" : PG_USER ,
2427 "ENGINE" : "django.db.backends.postgresql_psycopg2" ,
2528 },
2629 "sqlite" : {"NAME" : "sqlite" , "ENGINE" : "django.db.backends.sqlite3" },
2730 "secondary" : {
2831 "HOST" : "localhost" ,
2932 "PORT" : 5432 ,
30- "NAME" : "test_secondary " ,
33+ "NAME" : "postgres " ,
3134 "USER" : PG_USER ,
3235 "ENGINE" : "django.db.backends.postgresql_psycopg2" ,
3336 },
@@ -60,3 +63,64 @@ def pytest_configure():
6063 },
6164 },
6265 )
66+
67+ # Initialize Django
68+ django .setup ()
69+
70+
71+ @pytest .fixture (scope = "session" )
72+ def django_db_setup (django_db_setup , django_db_blocker ):
73+ """
74+ Fixture to set up the test database with the required tables.
75+ This extends the built-in django_db_setup fixture.
76+ """
77+
78+ # Import all test models
79+ from tests .test_models import (
80+ MockObject ,
81+ MockFKObject ,
82+ MockBlankObject ,
83+ ExtendedMockObject ,
84+ LimitedMockObject ,
85+ OverloadMockObject ,
86+ SecondaryMockObject ,
87+ UniqueMockObject ,
88+ )
89+
90+ with django_db_blocker .unblock ():
91+ # Check if tables exist and create them if they don't
92+ for alias in connections :
93+ connection = connections [alias ]
94+
95+ # Get a list of all tables in the database
96+ with connection .cursor () as cursor :
97+ if connection .vendor == "postgresql" :
98+ cursor .execute (
99+ "SELECT tablename FROM pg_tables WHERE schemaname = 'public'"
100+ )
101+ existing_tables = {row [0 ] for row in cursor .fetchall ()}
102+ elif connection .vendor == "sqlite" :
103+ cursor .execute ("SELECT name FROM sqlite_master WHERE type='table'" )
104+ existing_tables = {row [0 ] for row in cursor .fetchall ()}
105+ else :
106+ existing_tables = set ()
107+
108+ # Create tables that don't exist
109+ with connection .schema_editor () as schema_editor :
110+ for model in [
111+ MockObject ,
112+ MockFKObject ,
113+ MockBlankObject ,
114+ ExtendedMockObject ,
115+ LimitedMockObject ,
116+ OverloadMockObject ,
117+ SecondaryMockObject ,
118+ UniqueMockObject ,
119+ ]:
120+ table_name = model ._meta .db_table
121+ if table_name not in existing_tables :
122+ try :
123+ schema_editor .create_model (model )
124+ print (f"Created table { table_name } in { alias } " )
125+ except Exception as e :
126+ print (f"Error creating { table_name } in { alias } : { e } " )
0 commit comments