| 1 |
# ruff: noqa: TRY301, TRY300 |
| 2 |
"""PostgreSQL Live Functional Test Script for django-dbbackup |
| 3 |
|
| 4 |
Usage: |
| 5 |
python scripts/postgres_live_test.py [--verbose] |
| 6 |
python scripts/postgres_live_test.py --connector PgDumpBinaryConnector |
| 7 |
python scripts/postgres_live_test.py --all |
| 8 |
|
| 9 |
It provides end-to-end validation of PostgreSQL backup/restore functionality using the |
| 10 |
available connectors and mirrors the visual layout & summary style of the SQLite live test |
| 11 |
(`sqlite_live_test.py`) for consistency. |
| 12 |
|
| 13 |
Exit code 0 on success (all tested connectors passed), 1 on failure. |
| 14 |
""" |
| 15 |
|
| 16 |
import os |
| 17 |
import shutil |
| 18 |
import subprocess |
| 19 |
import sys |
| 20 |
import tempfile |
| 21 |
import time |
| 22 |
from multiprocessing import Process |
| 23 |
from pathlib import Path |
| 24 |
|
| 25 |
from scripts._utils import get_symbols |
| 26 |
|
| 27 |
_SYMS = get_symbols() |
| 28 |
SYMBOL_PASS = _SYMS["PASS"] |
| 29 |
SYMBOL_FAIL = _SYMS["FAIL"] |
| 30 |
SYMBOL_SUMMARY = _SYMS["SUMMARY"] |
| 31 |
SYMBOL_PG = _SYMS["PG"] |
| 32 |
SYMBOL_TEST = _SYMS["TEST"] |
| 33 |
SYMBOL_SKIP = _SYMS["SKIP"] |
| 34 |
|
| 35 |
|
| 36 |
class SkippedTestError(Exception): |
| 37 |
"""Exception raised when a test should be skipped.""" |
| 38 |
|
| 39 |
|
| 40 |
# Available PostgreSQL connectors |
| 41 |
POSTGRES_CONNECTORS = [ |
| 42 |
"PgDumpConnector", |
| 43 |
"PgDumpBinaryConnector", |
| 44 |
"PgDumpGisConnector", |
| 45 |
] |
| 46 |
|
| 47 |
# Add parent directory to path to import Django modules |
| 48 |
sys.path.insert(0, str(Path(__file__).parent.parent)) |
| 49 |
|
| 50 |
import django |
| 51 |
from django.core.management import execute_from_command_line |
| 52 |
|
| 53 |
GITHUB_ACTIONS: bool = os.getenv("GITHUB_ACTIONS", "false").lower() in ("true", "1", "yes") |
| 54 |
|
| 55 |
|
| 56 |
class PostgreSQLTestRunner: |
| 57 |
"""Manages a test database on the existing PostgreSQL instance.""" |
| 58 |
|
| 59 |
def __init__(self, verbose=False): |
| 60 |
self.verbose = verbose |
| 61 |
self.port = 5432 # Use default PostgreSQL port |
| 62 |
self.temp_dir = None |
| 63 |
self.test_db_name = f"dbbackup_test_{int(time.time())}" # Unique DB name |
| 64 |
self.superuser = "postgres" |
| 65 |
self.user = f"postgres_{int(time.time())}" |
| 66 |
self.password = "postgres" # Password (shared by user and superuser for simplicity) |
| 67 |
self.db_created = False |
| 68 |
|
| 69 |
def _log(self, message): |
| 70 |
"""Log a message if verbose mode is enabled.""" |
| 71 |
if self.verbose: |
| 72 |
print(f"[PostgreSQL Test] {message}") |
| 73 |
|
| 74 |
def _run_command(self, cmd, check=True, use_sudo=None, **kwargs): |
| 75 |
"""Run a command and optionally check for errors.""" |
| 76 |
# In GitHub Actions, don't use sudo and connect via TCP |
| 77 |
if GITHUB_ACTIONS: |
| 78 |
use_sudo = False |
| 79 |
# Set PostgreSQL connection environment for action-setup-postgres |
| 80 |
env = kwargs.get("env", os.environ.copy()) |
| 81 |
env.update({"PGHOST": "localhost", "PGPORT": "5432", "PGUSER": "postgres", "PGPASSWORD": "postgres"}) |
| 82 |
kwargs["env"] = env |
| 83 |
elif use_sudo is None: |
| 84 |
use_sudo = os.name == "posix" |
| 85 |
|
| 86 |
if use_sudo: |
| 87 |
cmd = ["sudo", "-u", self.superuser, *cmd] if isinstance(cmd, list) else f"sudo -u {self.superuser} {cmd}" |
| 88 |
|
| 89 |
self._log(f"Running: {' '.join(cmd) if isinstance(cmd, list) else cmd}") |
| 90 |
result = subprocess.run(cmd, shell=isinstance(cmd, str), **kwargs, check=False) |
| 91 |
if check and result.returncode != 0: |
| 92 |
# Collect stdout and stderr for better error reporting |
| 93 |
stdout = getattr(result, "stdout", b"") |
| 94 |
stderr = getattr(result, "stderr", b"") |
| 95 |
if isinstance(stdout, bytes): |
| 96 |
stdout = stdout.decode("utf-8", errors="replace") |
| 97 |
if isinstance(stderr, bytes): |
| 98 |
stderr = stderr.decode("utf-8", errors="replace") |
| 99 |
error_msg = f"Command failed with exit code {result.returncode}: {cmd}" |
| 100 |
if stdout: |
| 101 |
error_msg += f"\nSTDOUT: {stdout}" |
| 102 |
if stderr: |
| 103 |
error_msg += f"\nSTDERR: {stderr}" |
| 104 |
raise RuntimeError(error_msg) |
| 105 |
return result |
| 106 |
|
| 107 |
def setup_postgres(self): |
| 108 |
"""Set up a test database on the existing PostgreSQL instance.""" |
| 109 |
|
| 110 |
if not shutil.which("pg_dump") or not shutil.which("psql"): |
| 111 |
install_instructions = "" |
| 112 |
if os.name == "posix": |
| 113 |
install_instructions = ( |
| 114 |
"\nInstall by running 'sudo apt install postgresql " |
| 115 |
"postgresql-contrib postgresql-client-common postgresql-client'\n" |
| 116 |
"... then run 'sudo service postgresql start' to start the server." |
| 117 |
) |
| 118 |
elif os.name == "nt": |
| 119 |
install_instructions = ( |
| 120 |
"\nInstall PostgreSQL from https://www.postgresql.org/download/windows/ " |
| 121 |
"and ensure pg_dump and psql are in your PATH." |
| 122 |
) |
| 123 |
msg = f"PostgreSQL client tools (pg_dump, psql, etc) are not installed!{install_instructions}" |
| 124 |
raise SkippedTestError(msg) |
| 125 |
|
| 126 |
self._log("Setting up test database...") |
| 127 |
self.temp_dir = tempfile.mkdtemp(prefix="dbbackup_postgres_") |
| 128 |
try: |
| 129 |
# Check if PostgreSQL is running |
| 130 |
self._log("Checking PostgreSQL connection...") |
| 131 |
self._run_command(["pg_isready", "-h", "localhost", "-p", str(self.port)], capture_output=True) |
| 132 |
self._log("PostgreSQL server is ready") |
| 133 |
|
| 134 |
# Create test database |
| 135 |
self._create_test_database() |
| 136 |
|
| 137 |
except Exception as e: |
| 138 |
self.cleanup() |
| 139 |
msg = f"Failed to set up PostgreSQL: {e}" |
| 140 |
raise RuntimeError(msg) from e |
| 141 |
|
| 142 |
def _create_test_database(self): |
| 143 |
"""Create the test database.""" |
| 144 |
self._log(f"Creating test database: {self.test_db_name}") |
| 145 |
|
| 146 |
# In CI environments, use the action-setup-postgres configured postgres user |
| 147 |
if GITHUB_ACTIONS: |
| 148 |
self._log("GitHub Actions detected, using postgres superuser as database owner") |
| 149 |
|
| 150 |
# action-setup-postgres already configures postgres user with password 'postgres' |
| 151 |
# Just create the database directly |
| 152 |
create_db_sql = f"CREATE DATABASE {self.test_db_name};" |
| 153 |
self._run_command(["psql", "-c", create_db_sql], capture_output=True) |
| 154 |
|
| 155 |
# Use the pre-configured postgres user credentials |
| 156 |
self.user = self.superuser |
| 157 |
self.password = "postgres" # action-setup-postgres default |
| 158 |
else: |
| 159 |
# For local development, create a dedicated test user |
| 160 |
create_user_sql = ( |
| 161 |
f"DO $$ BEGIN " |
| 162 |
f"IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{self.user}') THEN " |
| 163 |
f"CREATE USER {self.user} WITH PASSWORD '{self.password}' CREATEDB; " |
| 164 |
f"END IF; " |
| 165 |
f"END $$;" |
| 166 |
) |
| 167 |
|
| 168 |
# Create the user - capture output for better error reporting |
| 169 |
try: |
| 170 |
self._run_command(["psql", "-c", create_user_sql], capture_output=True, use_sudo=True) |
| 171 |
except RuntimeError as e: |
| 172 |
# If user creation fails, provide more context |
| 173 |
self._log(f"User creation failed, but attempting to continue: {e}") |
| 174 |
# Check if user already exists |
| 175 |
check_user_sql = f"SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = '{self.user}';" |
| 176 |
try: |
| 177 |
result = self._run_command( |
| 178 |
["psql", "-t", "-c", check_user_sql], capture_output=True, check=False, use_sudo=True |
| 179 |
) |
| 180 |
if result.stdout and result.stdout.decode().strip(): |
| 181 |
self._log(f"User {self.user} already exists, continuing...") |
| 182 |
else: |
| 183 |
# User doesn't exist and creation failed, this is a real error |
| 184 |
msg = f"Failed to create user {self.user} and user does not exist: {e}" |
| 185 |
raise RuntimeError(msg) from e |
| 186 |
except Exception as check_error: |
| 187 |
self._log(f"Failed to check if user exists: {check_error}") |
| 188 |
msg = f"User creation and verification both failed: {e}" |
| 189 |
raise RuntimeError(msg) from e |
| 190 |
|
| 191 |
# Create database owned by the test user |
| 192 |
create_db_sql = f"CREATE DATABASE {self.test_db_name} OWNER {self.user};" |
| 193 |
self._run_command(["psql", "-c", create_db_sql], capture_output=True, use_sudo=True) |
| 194 |
|
| 195 |
self.db_created = True |
| 196 |
|
| 197 |
def get_database_config(self): |
| 198 |
"""Get Django database configuration for the test PostgreSQL instance.""" |
| 199 |
return { |
| 200 |
"ENGINE": "django.db.backends.postgresql", |
| 201 |
"NAME": self.test_db_name, |
| 202 |
"USER": self.user, |
| 203 |
"PASSWORD": self.password, |
| 204 |
"HOST": "localhost", |
| 205 |
"PORT": self.port, |
| 206 |
} |
| 207 |
|
| 208 |
def cleanup(self): |
| 209 |
"""Clean up the test database.""" |
| 210 |
self._log("Cleaning up test database...") |
| 211 |
|
| 212 |
if self.db_created: |
| 213 |
try: |
| 214 |
# Drop the test database using psql |
| 215 |
drop_db_sql = f"DROP DATABASE IF EXISTS {self.test_db_name};" |
| 216 |
self._run_command( |
| 217 |
["psql", "-c", drop_db_sql], capture_output=True, check=False |
| 218 |
) # Don't fail if database doesn't exist |
| 219 |
|
| 220 |
# Only drop the test user if we created one (not in CI where we use postgres superuser) |
| 221 |
if not GITHUB_ACTIONS and self.user != self.superuser: |
| 222 |
drop_user_sql = f"DROP USER IF EXISTS {self.user};" |
| 223 |
self._run_command(["psql", "-c", drop_user_sql], capture_output=True, check=False) |
| 224 |
except Exception as e: |
| 225 |
self._log(f"Warning: Failed to drop test database or user: {e}") |
| 226 |
|
| 227 |
if self.temp_dir and os.path.exists(self.temp_dir): |
| 228 |
import shutil |
| 229 |
|
| 230 |
shutil.rmtree(self.temp_dir) |
| 231 |
|
| 232 |
|
| 233 |
class PostgreSQLLiveTest: |
| 234 |
"""Runs live tests against PostgreSQL connectors.""" |
| 235 |
|
| 236 |
def __init__(self, connector_name="PgDumpConnector", verbose=False): |
| 237 |
self.connector_name = connector_name |
| 238 |
self.verbose = verbose |
| 239 |
self.postgres_runner = PostgreSQLTestRunner(verbose=verbose) |
| 240 |
|
| 241 |
def _log(self, message): |
| 242 |
"""Log a message if verbose mode is enabled.""" |
| 243 |
if self.verbose: |
| 244 |
print(f"[Live Test] {message}") |
| 245 |
|
| 246 |
def _configure_django(self): |
| 247 |
"""Configure Django with the test PostgreSQL database.""" |
| 248 |
# Configure Django settings |
| 249 |
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") |
| 250 |
|
| 251 |
# Override database settings |
| 252 |
db_config = self.postgres_runner.get_database_config() |
| 253 |
os.environ.update({ |
| 254 |
"DB_ENGINE": db_config["ENGINE"], |
| 255 |
"DB_NAME": db_config["NAME"], |
| 256 |
"DB_USER": db_config["USER"], |
| 257 |
"DB_HOST": db_config["HOST"], |
| 258 |
}) |
| 259 |
# Only set password if it exists |
| 260 |
if db_config["PASSWORD"]: |
| 261 |
os.environ["DB_PASSWORD"] = db_config["PASSWORD"] |
| 262 |
# Set port as string |
| 263 |
os.environ["DB_PORT"] = str(db_config["PORT"]) |
| 264 |
|
| 265 |
# Set connector |
| 266 |
os.environ["CONNECTOR"] = f"dbbackup.db.postgresql.{self.connector_name}" |
| 267 |
|
| 268 |
# Configure storage for backups - use unique directory per test |
| 269 |
backup_dir = os.path.join(str(self.postgres_runner.temp_dir), "backups") |
| 270 |
os.makedirs(backup_dir, exist_ok=True) |
| 271 |
os.environ["STORAGE"] = "django.core.files.storage.FileSystemStorage" |
| 272 |
os.environ["STORAGE_LOCATION"] = backup_dir |
| 273 |
os.environ["STORAGE_OPTIONS"] = f"location={backup_dir}" |
| 274 |
|
| 275 |
# Setup Django only if not already configured |
| 276 |
if not django.apps.apps.ready: |
| 277 |
django.setup() |
| 278 |
|
| 279 |
def _create_test_data(self): |
| 280 |
"""Create test data in the database.""" |
| 281 |
self._log("Creating test data...") |
| 282 |
|
| 283 |
# Run migrations |
| 284 |
execute_from_command_line(["", "migrate", "--noinput"]) |
| 285 |
|
| 286 |
# Create test models |
| 287 |
from tests.testapp.models import CharModel, TextModel |
| 288 |
|
| 289 |
# Create some test data (CharModel has max_length=10) |
| 290 |
char_obj = CharModel.objects.create(field="test_char") # 9 chars, fits in 10 |
| 291 |
text_obj = TextModel.objects.create(field="test text content for backup") |
| 292 |
|
| 293 |
self._log(f"Created CharModel: {char_obj}") |
| 294 |
self._log(f"Created TextModel: {text_obj}") |
| 295 |
|
| 296 |
return char_obj, text_obj |
| 297 |
|
| 298 |
def _verify_test_data(self, expected_char_obj, expected_text_obj): |
| 299 |
"""Verify that test data exists and matches expectations.""" |
| 300 |
from tests.testapp.models import CharModel, TextModel |
| 301 |
|
| 302 |
char_objs = CharModel.objects.all() |
| 303 |
text_objs = TextModel.objects.all() |
| 304 |
|
| 305 |
self._log(f"Found {char_objs.count()} CharModel objects") |
| 306 |
self._log(f"Found {text_objs.count()} TextModel objects") |
| 307 |
|
| 308 |
if char_objs.count() != 1 or text_objs.count() != 1: |
| 309 |
msg = f"Expected 1 of each model, found {char_objs.count()} CharModel and {text_objs.count()} TextModel" |
| 310 |
raise AssertionError(msg) |
| 311 |
|
| 312 |
char_obj = char_objs.first() |
| 313 |
text_obj = text_objs.first() |
| 314 |
|
| 315 |
if char_obj.field != expected_char_obj.field: |
| 316 |
msg = f"CharModel field mismatch: expected '{expected_char_obj.field}', got '{char_obj.field}'" |
| 317 |
raise AssertionError(msg) |
| 318 |
|
| 319 |
if text_obj.field != expected_text_obj.field: |
| 320 |
msg = f"TextModel field mismatch: expected '{expected_text_obj.field}', got '{text_obj.field}'" |
| 321 |
raise AssertionError(msg) |
| 322 |
|
| 323 |
self._log("Test data verification passed") |
| 324 |
|
| 325 |
def run_backup_restore_test(self): |
| 326 |
"""Run a complete backup and restore test cycle.""" |
| 327 |
self._log(f"Starting backup/restore test with {self.connector_name}") |
| 328 |
|
| 329 |
try: |
| 330 |
# Setup PostgreSQL |
| 331 |
self.postgres_runner.setup_postgres() |
| 332 |
|
| 333 |
# Configure Django |
| 334 |
self._configure_django() |
| 335 |
|
| 336 |
# Create test data |
| 337 |
char_obj, text_obj = self._create_test_data() |
| 338 |
|
| 339 |
# Run backup |
| 340 |
self._log("Running database backup...") |
| 341 |
execute_from_command_line(["", "dbbackup", "--noinput"]) |
| 342 |
|
| 343 |
# Clear test data |
| 344 |
self._log("Clearing test data...") |
| 345 |
from tests.testapp.models import CharModel, TextModel |
| 346 |
|
| 347 |
CharModel.objects.all().delete() |
| 348 |
TextModel.objects.all().delete() |
| 349 |
|
| 350 |
# Verify data is cleared |
| 351 |
if CharModel.objects.exists() or TextModel.objects.exists(): |
| 352 |
msg = "Test data was not properly cleared" |
| 353 |
raise AssertionError(msg) |
| 354 |
self._log("Test data cleared successfully") |
| 355 |
|
| 356 |
# Run restore |
| 357 |
self._log("Running database restore...") |
| 358 |
execute_from_command_line(["", "dbrestore", "--noinput"]) |
| 359 |
|
| 360 |
# Verify restored data |
| 361 |
self._verify_test_data(char_obj, text_obj) |
| 362 |
|
| 363 |
self._log(f"{SYMBOL_PASS} {self.connector_name} backup/restore test PASSED") |
| 364 |
return 0 |
| 365 |
|
| 366 |
except SkippedTestError as e: |
| 367 |
self._log(f"{SYMBOL_SKIP} {self.connector_name} backup/restore test SKIPPED: {e}") |
| 368 |
return 77 |
| 369 |
|
| 370 |
except Exception as e: |
| 371 |
self._log(f"{SYMBOL_FAIL} {self.connector_name} backup/restore test FAILED: {e}") |
| 372 |
return 1 |
| 373 |
|
| 374 |
finally: |
| 375 |
self.postgres_runner.cleanup() |
| 376 |
|
| 377 |
|
| 378 |
def _connector_test_entry(connector_name: str, verbose: bool): # pragma: no cover - executed in subprocess |
| 379 |
"""Subprocess entry point to run a single connector test. |
| 380 |
|
| 381 |
Needs to be at module top-level so it can be imported/pickled on Windows |
| 382 |
(the 'spawn' start method). Exits with status code 1 if the test fails. |
| 383 |
""" |
| 384 |
test_runner = PostgreSQLLiveTest(connector_name, verbose) |
| 385 |
exit_code = test_runner.run_backup_restore_test() |
| 386 |
sys.exit(exit_code) |
| 387 |
|
| 388 |
|
| 389 |
def run_single_connector_test(connector_name, verbose=False): |
| 390 |
"""Run a test for a single connector in isolation using a subprocess. |
| 391 |
|
| 392 |
On Windows, multiprocessing with nested (local) functions fails because they |
| 393 |
are not picklable under the 'spawn' start method. We therefore provide a |
| 394 |
top-level function as the process target. If an unexpected multiprocessing |
| 395 |
failure occurs on Windows (e.g., permissions), we gracefully fall back to |
| 396 |
in-process execution to avoid masking all connector results. |
| 397 |
""" |
| 398 |
|
| 399 |
# Normal path: run in a separate process for isolation |
| 400 |
def _run_subprocess(): # local helper kept simple; not used as target |
| 401 |
process_local = Process(target=_connector_test_entry, args=(connector_name, verbose)) |
| 402 |
process_local.start() |
| 403 |
process_local.join() |
| 404 |
return process_local |
| 405 |
|
| 406 |
try: |
| 407 |
process = _run_subprocess() |
| 408 |
if process.exitcode is None: |
| 409 |
return 1 |
| 410 |
if process.exitcode not in {0, 77} and os.name == "nt": # Fallback path on Windows |
| 411 |
# Retry in-process so at least we capture a meaningful failure message |
| 412 |
test_runner = PostgreSQLLiveTest(connector_name, verbose) |
| 413 |
return test_runner.run_backup_restore_test() |
| 414 |
return process.exitcode |
| 415 |
except AttributeError as exc: # Defensive: pickling or spawn related |
| 416 |
if os.name == "nt": |
| 417 |
print(f"{SYMBOL_FAIL} Multiprocessing issue on Windows ({exc}); running in-process instead.") |
| 418 |
test_runner = PostgreSQLLiveTest(connector_name, verbose) |
| 419 |
return test_runner.run_backup_restore_test() |
| 420 |
raise |
| 421 |
|
| 422 |
|
| 423 |
def main(): |
| 424 |
"""Main entry point for the script.""" |
| 425 |
import argparse |
| 426 |
|
| 427 |
parser = argparse.ArgumentParser(description="Run live PostgreSQL tests for django-dbbackup") |
| 428 |
parser.add_argument( |
| 429 |
"--connector", |
| 430 |
default="PgDumpConnector", |
| 431 |
choices=POSTGRES_CONNECTORS, |
| 432 |
help="PostgreSQL connector to test (default: %(default)s)", |
| 433 |
) |
| 434 |
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose output") |
| 435 |
parser.add_argument("--all", action="store_true", help="Test all PostgreSQL connectors") |
| 436 |
|
| 437 |
args = parser.parse_args() |
| 438 |
|
| 439 |
connectors_to_test = POSTGRES_CONNECTORS if args.all else [args.connector] |
| 440 |
|
| 441 |
print(f"{SYMBOL_PG} Starting PostgreSQL Live Tests for django-dbbackup (Isolated)") |
| 442 |
|
| 443 |
results = {} |
| 444 |
for connector in connectors_to_test: |
| 445 |
print(f"\n{SYMBOL_TEST} Testing {connector}...") |
| 446 |
results[connector] = run_single_connector_test(connector, verbose=args.verbose) |
| 447 |
exit_code = results[connector] |
| 448 |
if exit_code == 0: |
| 449 |
status = f"{SYMBOL_PASS} PASSED" |
| 450 |
elif exit_code == 77: |
| 451 |
status = f"{SYMBOL_SKIP} SKIPPED" |
| 452 |
else: |
| 453 |
status = f"{SYMBOL_FAIL} FAILED" |
| 454 |
print(f" {connector}: {status}") |
| 455 |
|
| 456 |
# Summary |
| 457 |
print(f"\n{SYMBOL_SUMMARY} PostgreSQL Connector Test Summary") |
| 458 |
overall_success = True |
| 459 |
for connector, exit_code in results.items(): |
| 460 |
if exit_code == 0: |
| 461 |
symbol = SYMBOL_PASS |
| 462 |
elif exit_code == 77: |
| 463 |
symbol = SYMBOL_SKIP |
| 464 |
else: |
| 465 |
symbol = SYMBOL_FAIL |
| 466 |
overall_success = False |
| 467 |
print(f" {symbol} {connector}") |
| 468 |
|
| 469 |
# Exit with error code if any tests failed |
| 470 |
sys.exit(0 if overall_success else 1) |
| 471 |
|
| 472 |
|
| 473 |
if __name__ == "__main__": |
| 474 |
main() |