import pytest import requests import os # Configuration # Configuration DOMAIN = os.getenv("DOMAIN", "dev.kovagoadi.hu") PORT = os.getenv("PORT", "898") HTTPS_PORT = os.getenv("HTTPS_PORT", "446") BASE_URL = f"http://127.0.0.1:{PORT}" HTTPS_BASE_URL = f"https://127.0.0.1:{HTTPS_PORT}" HOST_HEADER = f"test-whoami.{DOMAIN}" @pytest.fixture(scope="session", autouse=True) def mock_webserver(): """Start ephemeral mock webserver containers and configure Traefik.""" import time # Skip mocks in CI environment if os.getenv("CI"): print("CI environment detected. Skipping mock webserver setup.") yield return # In CI (Docker-in-Docker), we need to use the HOST path for volumes, not the container path. # The workflow mounts the project root to /app, but the Docker daemon is on the host. # We pass PROJECT_ROOT env var to the test container to tell it where the files are on the HOST. cwd = os.getenv("PROJECT_ROOT", os.getcwd()) certs_dir = os.path.join(cwd, "tests/mock_nginx/certs") image = "nginx:alpine" # Define mocks mocks = [ { "name": "mock-legacy-ephemeral", "alias": "webserver", "conf": os.path.join(cwd, "tests/mock_nginx/legacy.conf"), "ports": ["80", "443"] }, { "name": "mock-staging-ephemeral", "alias": "mock", "conf": os.path.join(cwd, "tests/mock_nginx/staging.conf"), "ports": ["8080", "445"] } ] # Cleanup and Start Mocks mock_ips = {} for mock in mocks: subprocess.run(["docker", "rm", "-f", mock["name"]], capture_output=True) cmd = [ "docker", "run", "-d", "--rm", "--name", mock["name"], "--network", "proxy", "--network-alias", mock["alias"], "-v", f"{mock['conf']}:/etc/nginx/nginx.conf:ro", "-v", f"{certs_dir}:/etc/nginx/certs:ro", image ] print(f"Starting {mock['name']}...") result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: print(f"STDOUT: {result.stdout}") print(f"STDERR: {result.stderr}") pytest.fail(f"Failed to start {mock['name']}: {result.stderr}") # Inspect container to get IP inspect_cmd = ["docker", "inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", mock["name"]] inspect_res = subprocess.run(inspect_cmd, capture_output=True, text=True) if inspect_res.returncode != 0: pytest.fail(f"Failed to inspect {mock['name']}: {inspect_res.stderr}") mock_ips[mock["alias"]] = inspect_res.stdout.strip() print(f"{mock['name']} IP: {mock_ips[mock['alias']]}") # Restart Traefik with IP env vars for extra_hosts print(f"Restarting Traefik with STAGING_IP={mock_ips['mock']} and LEGACY_IP={mock_ips['webserver']}...") env = os.environ.copy() env["STAGING_IP"] = mock_ips["mock"] env["LEGACY_IP"] = mock_ips["webserver"] # In CI (Docker-in-Docker), we need to tell docker-compose that the project root # is the HOST path (PROJECT_ROOT), not the container path (/app). # This ensures volume mounts use the correct host paths. if "PROJECT_ROOT" in os.environ: env["COMPOSE_PROJECT_DIR"] = os.environ["PROJECT_ROOT"] # We need to recreate the container to pick up extra_hosts changes try: subprocess.run(["docker-compose", "--env-file", "dev.env", "up", "-d", "--force-recreate", "--no-deps", "traefik12"], env=env, check=True, capture_output=True, text=True) except subprocess.CalledProcessError as e: print(f"Docker Compose STDOUT: {e.stdout}") print(f"Docker Compose STDERR: {e.stderr}") raise e # Wait for everything to settle time.sleep(5) yield print("Stopping mocks and restoring Traefik...") for mock in mocks: subprocess.run(["docker", "stop", mock["name"]], capture_output=True) # Restore Traefik to default (optional) subprocess.run(["docker-compose", "--env-file", "dev.env", "up", "-d", "--force-recreate", "--no-deps", "traefik12"], check=True) def test_whoami_http_reachable(): """Verify that the whoami service is reachable via HTTP.""" try: response = requests.get(BASE_URL, headers={"Host": HOST_HEADER}, timeout=5) assert response.status_code == 200 assert "Hostname:" in response.text except requests.exceptions.RequestException as e: pytest.fail(f"Failed to connect to {BASE_URL}: {e}") import subprocess def test_whoami_https_reachable(): """Verify that the whoami service is reachable via HTTPS using curl (to handle SNI/DNS).""" # We use curl because requests doesn't support --resolve easily to force SNI with custom IP cmd = [ "curl", "-s", "-k", "--fail", "--resolve", f"{HOST_HEADER}:{HTTPS_PORT}:127.0.0.1", f"https://{HOST_HEADER}:{HTTPS_PORT}" ] try: result = subprocess.run(cmd, capture_output=True, text=True, timeout=10, check=True) assert "Hostname:" in result.stdout except subprocess.CalledProcessError as e: pytest.fail(f"Curl failed with exit code {e.returncode}: {e.stderr}") except subprocess.TimeoutExpired: pytest.fail("Curl timed out") def test_https_redirect(): """Verify that HTTP requests are NOT redirected to HTTPS (based on config, or check if they SHOULD be).""" # Based on docker-compose, there is no global redirect middleware configured on the entrypoint. # So HTTP should remain HTTP. try: response = requests.get(BASE_URL, headers={"Host": HOST_HEADER}, allow_redirects=False, timeout=5) assert response.status_code == 200 except requests.exceptions.RequestException as e: pytest.fail(f"Failed to connect to {BASE_URL}: {e}") @pytest.mark.skipif(os.getenv("CI") is not None, reason="Skipping mock-dependent test in CI") def test_unknown_host_404(): """Verify that requests to an unknown host (hitting legacy-nginx catch-all) are routed to the mock.""" try: # We use a domain that doesn't match the specific *.dev.kovagoadi.hu rules # so it falls through to the catch-all 'nginx-legacy-router' response = requests.get(BASE_URL, headers={"Host": "unknown.com"}, timeout=5) assert response.status_code == 200 assert "X-Mock-Service" in response.headers assert response.headers["X-Mock-Service"] == "legacy" except requests.exceptions.RequestException as e: pytest.fail(f"Failed to connect to {BASE_URL}: {e}") @pytest.mark.skipif(os.getenv("CI") is not None, reason="Skipping mock-dependent test in CI") def test_unknown_host_https_passthrough(): """Verify that HTTPS requests to an unknown host are passed through to the mock Nginx.""" # We use curl to handle SNI and self-signed certs # unknown.com should hit the catch-all SNI router cmd = [ "curl", "-s", "-k", "-i", "--fail", "--resolve", f"unknown.com:{HTTPS_PORT}:127.0.0.1", f"https://unknown.com:{HTTPS_PORT}" ] try: result = subprocess.run(cmd, capture_output=True, text=True, timeout=10, check=True) assert "Mock Nginx Legacy HTTPS" in result.stdout assert "X-Mock-Service: legacy" in result.stdout or "x-mock-service: legacy" in result.stdout.lower() except subprocess.CalledProcessError as e: pytest.fail(f"Curl failed with exit code {e.returncode}: {e.stderr}") except subprocess.TimeoutExpired: pytest.fail("Curl timed out") @pytest.mark.skipif(os.getenv("CI") is not None, reason="Skipping mock-dependent test in CI") def test_staging_http_routing(): """Verify HTTP requests to *.staging.kovagoadi.hu are routed to the mock.""" host = "foo.staging.kovagoadi.hu" try: response = requests.get(BASE_URL, headers={"Host": host}, timeout=5) assert response.status_code == 200 assert "X-Mock-Service" in response.headers assert response.headers["X-Mock-Service"] == "staging" except requests.exceptions.RequestException as e: pytest.fail(f"Failed to connect to {BASE_URL} with host {host}: {e}") @pytest.mark.skipif(os.getenv("CI") is not None, reason="Skipping mock-dependent test in CI") def test_dev_http_routing(): """Verify HTTP requests to *.dev.kovagoadi.hu are routed to the mock.""" host = "bar.dev.kovagoadi.hu" try: response = requests.get(BASE_URL, headers={"Host": host}, timeout=5) assert response.status_code == 200 assert "X-Mock-Service" in response.headers assert response.headers["X-Mock-Service"] == "staging" except requests.exceptions.RequestException as e: pytest.fail(f"Failed to connect to {BASE_URL} with host {host}: {e}") @pytest.mark.skipif(os.getenv("CI") is not None, reason="Skipping mock-dependent test in CI") def test_staging_https_routing(): """Verify HTTPS requests to *.staging.kovagoadi.hu are routed to the mock.""" host = "foo.staging.kovagoadi.hu" cmd = [ "curl", "-s", "-k", "-i", "--fail", "--resolve", f"{host}:{HTTPS_PORT}:127.0.0.1", f"https://{host}:{HTTPS_PORT}" ] try: result = subprocess.run(cmd, capture_output=True, text=True, timeout=10, check=True) assert "Mock Nginx Staging HTTPS" in result.stdout assert "X-Mock-Service: staging" in result.stdout or "x-mock-service: staging" in result.stdout.lower() except subprocess.CalledProcessError as e: pytest.fail(f"Curl failed with exit code {e.returncode}: {e.stderr}") except subprocess.TimeoutExpired: pytest.fail("Curl timed out") @pytest.mark.skipif(os.getenv("CI") is not None, reason="Skipping mock-dependent test in CI") def test_dev_https_routing(): """Verify HTTPS requests to *.dev.kovagoadi.hu are routed to the mock.""" host = "bar.dev.kovagoadi.hu" cmd = [ "curl", "-s", "-k", "-i", "--fail", "--resolve", f"{host}:{HTTPS_PORT}:127.0.0.1", f"https://{host}:{HTTPS_PORT}" ] try: result = subprocess.run(cmd, capture_output=True, text=True, timeout=10, check=True) assert "Mock Nginx Staging HTTPS" in result.stdout assert "X-Mock-Service: staging" in result.stdout or "x-mock-service: staging" in result.stdout.lower() except subprocess.CalledProcessError as e: pytest.fail(f"Curl failed with exit code {e.returncode}: {e.stderr}") except subprocess.TimeoutExpired: pytest.fail("Curl timed out")