import subprocess
import sys
def test_run_pytest_in_docker():
# Build the Docker image
build_cmd = [
"docker", "build", "-t", "pytest-test-image", "."
]
build_process = subprocess.run(build_cmd, capture_output=True, text=True)
assert build_process.returncode == 0, f"Docker build failed: {build_process.stderr}"
# Run the Docker container to execute pytest
run_cmd = [
"docker", "run", "--rm", "pytest-test-image"
]
run_process = subprocess.run(run_cmd, capture_output=True, text=True)
print(run_process.stdout)
assert run_process.returncode == 0, f"Pytest failed inside Docker: {run_process.stdout}\n{run_process.stderr}"
if __name__ == "__main__":
test_run_pytest_in_docker()This script automates running pytest tests inside a Docker container.
First, it builds a Docker image named pytest-test-image using the Dockerfile in the current directory. It checks if the build succeeded by verifying the return code.
Next, it runs a container from this image, which executes pytest tests. The output is captured and printed to the console.
Assertions check that both the Docker build and the pytest run complete successfully. If any step fails, the test fails with an error message showing the problem.
This approach ensures tests run in a clean, isolated environment defined by the Dockerfile.