I created a test that creates the docker image based on a Dockerfile, and test that the web app is running. I did it because sometimes during the development of this project, I broke the creation of the docker image. However, I would like for a review whether this is the best approach.
import subprocess
import time
import pytest
import requests
from testcontainers.core.container import DockerContainer
from testcontainers.core.wait_strategies import LogMessageWaitStrategy
port = 8000
@pytest.fixture(scope="module")
def app_container():
# Build the docker image
subprocess.run(["docker", "build", "-t", "my-app:test", "."], check=True)
# Start the container
# We need to provide necessary environment variables for the app to start
container = DockerContainer("my-app:test")
container.with_exposed_ports(port)
container.with_env("PORT", str(port))
container.with_env("DATABASE_CONNECTION_STRING", "sqlite:///:memory:")
container.with_env("ENVIRONMENT", "test")
container.waiting_for(LogMessageWaitStrategy("Uvicorn running on"))
container.start()
yield container
container.stop()
@pytest.mark.timeout(20)
def test_actuators_info(app_container):
host: str = app_container.get_container_host_ip()
container_port: int = app_container.get_exposed_port(port)
base_url = f"http://{host}:{container_port}"
# Retry logic in case the app takes a moment to be fully responsive
max_retries = 5
for _ in range(max_retries):
try:
response = requests.get(f"{base_url}/actuators/info")
if response.status_code == 200:
assert response.json() is not None
return
except requests.exceptions.ConnectionError:
pass
time.sleep(0.5)
pytest.fail("Could not connect to the application or received non-200 status")