27 lines
1020 B
Python
27 lines
1020 B
Python
"""Point the app at a dedicated test database before any test module imports it."""
|
|
import os
|
|
|
|
import psycopg2
|
|
from psycopg2 import sql
|
|
|
|
ADMIN_URL = os.environ.get("TEST_ADMIN_DATABASE_URL", "postgresql://postgres:[email protected]:5432/postgres")
|
|
TEST_DATABASE = "books_test"
|
|
|
|
|
|
def _ensure_test_database() -> None:
|
|
conn = psycopg2.connect(ADMIN_URL)
|
|
conn.autocommit = True # CREATE DATABASE cannot run inside a transaction
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (TEST_DATABASE,))
|
|
if cur.fetchone() is None:
|
|
cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(TEST_DATABASE)))
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
_ensure_test_database()
|
|
# Assigned, never defaulted: tests TRUNCATE tables, so they must not inherit a real DATABASE_URL.
|
|
os.environ["DATABASE_URL"] = ADMIN_URL.rsplit("/", 1)[0] + "/" + TEST_DATABASE
|
|
os.environ["PASSWORD_PEPPER"] = "test-pepper-0123456789abcdef0123456789abcdef"
|