|
1 | 1 | import os |
| 2 | +import subprocess |
2 | 3 | from tempfile import NamedTemporaryFile |
3 | 4 | from unittest.mock import patch |
4 | 5 |
|
5 | 6 | import pytest |
6 | 7 |
|
7 | 8 |
|
8 | | -# Pytest-docker configuration |
| 9 | +# Pytest-docker configuration with cleanup |
9 | 10 | @pytest.fixture(scope="session") |
10 | 11 | def docker_compose_file(pytestconfig): |
11 | 12 | return os.path.join(str(pytestconfig.rootdir), "tests", "docker-compose.test.yml") |
12 | 13 |
|
13 | 14 |
|
| 15 | +@pytest.fixture(scope="session") |
| 16 | +def docker_compose_project_name(): |
| 17 | + """Use a consistent project name to avoid creating new networks each run.""" |
| 18 | + return "reflector_test" |
| 19 | + |
| 20 | + |
| 21 | +@pytest.fixture(scope="session", autouse=True) |
| 22 | +def cleanup_docker_resources(): |
| 23 | + """Clean up Docker test resources before and after test session.""" |
| 24 | + |
| 25 | + def cleanup(): |
| 26 | + # Stop and remove any existing test containers |
| 27 | + # This will also remove the reflector_test network if it exists |
| 28 | + subprocess.run( |
| 29 | + [ |
| 30 | + "docker", |
| 31 | + "compose", |
| 32 | + "-p", |
| 33 | + "reflector_test", |
| 34 | + "down", |
| 35 | + "-v", |
| 36 | + "--remove-orphans", |
| 37 | + ], |
| 38 | + capture_output=True, |
| 39 | + cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))), |
| 40 | + ) |
| 41 | + # Clean up any unused networks (includes orphaned pytest networks) |
| 42 | + # This is safe - only removes networks with no attached containers |
| 43 | + subprocess.run(["docker", "network", "prune", "-f"], capture_output=True) |
| 44 | + |
| 45 | + # Clean before tests |
| 46 | + cleanup() |
| 47 | + |
| 48 | + yield |
| 49 | + |
| 50 | + # Clean after tests |
| 51 | + cleanup() |
| 52 | + |
| 53 | + |
14 | 54 | @pytest.fixture(scope="session") |
15 | 55 | def postgres_service(docker_ip, docker_services): |
16 | 56 | """Ensure that PostgreSQL service is up and responsive.""" |
17 | | - port = docker_services.port_for("postgres_test", 5432) |
| 57 | + try: |
| 58 | + port = docker_services.port_for("postgres_test", 5432) |
| 59 | + except Exception as e: |
| 60 | + # If Docker services fail to start, clean up and retry |
| 61 | + subprocess.run(["docker", "network", "prune", "-f"], capture_output=True) |
| 62 | + subprocess.run( |
| 63 | + ["docker", "compose", "-p", "reflector_test", "down", "-v"], |
| 64 | + capture_output=True, |
| 65 | + ) |
| 66 | + raise pytest.skip(f"Docker services failed to start: {e}") |
18 | 67 |
|
19 | 68 | def is_responsive(): |
20 | 69 | try: |
|
0 commit comments