Persist Test Results after Docker Container stop

To persist test results generated by automated tests in a Docker container, you can use Docker volumes. Docker volumes allow you to store data outside of the container’s filesystem, ensuring that the data persists even after the container stops or is removed.

Step 1: Set Up Your Project Structure

First, organize your project directory. Here’s a suggested structure:

my_project/
├── Dockerfile
├── docker-compose.yml
├── tests/
│   ├── test_sample.py
├── results/

 

Step 2: Create a Dockerfile

In your Dockerfile, you’ll need to set up the environment for running your tests. Here’s an example:

# Use an official Python runtime as a parent image
FROM python:3.9-slim

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . .

# Install necessary packages
RUN pip install pytest selenium

# Command to run the tests
CMD ["pytest", "tests/"]

 

Step 3: Create a docker-compose.yml File

Using Docker Compose makes it easier to manage your multi-container setup. Here’s how you can configure your docker-compose.yml:

version: '3.8'

services:
  test-runner:
    build: .
    volumes:
      - ./results:/app/results  # Mount the results directory
    environment:
      - DISPLAY=:99  # If you need to run a headless browser
    # Additional configurations for Selenium can go here

 

Step 4: Write Your Test Case

In your tests/test_sample.py, you can create a simple test case that uses Selenium. Make sure it saves the test results to the /app/results directory.

import pytest
from selenium import webdriver

@pytest.fixture(scope="module")
def browser():
    # Set up Selenium WebDriver
    driver = webdriver.Chrome()  # Make sure the chromedriver is available
    yield driver
    driver.quit()

def test_example(browser):
    browser.get("http://example.com")
    assert "Example Domain" in browser.title

    # Save results (you can customize this as needed)
    with open("results/test_result.txt", "w") as f:
        f.write("Test passed!\n")

 

Step 5: Build and Run Your Container

You can build and run your container using Docker Compose:

docker-compose up --build

Step 6: Access the Test Results

After the tests run, you will find the test results saved in the results/ directory on your host machine. This directory is mapped to the container’s /app/results directory via the volume specified in docker-compose.yml.

Summary

  1. Dockerfile: Defines the environment for running your tests with Python, Pytest, and Selenium.
  2. docker-compose.yml: Manages the container and defines the volume for persisting results.
  3. Tests: Use Selenium to perform tests and save results in the mounted volume.

Using Docker volumes allows you to ensure that the test results persist beyond the lifecycle of the Docker container, making it easy to access and analyze them after tests have run.

Search

Table of Contents

You may also like to read