Skip to content

Pytest and CI Tutorial

Chris Foulon edited this page Oct 11, 2024 · 7 revisions

Pytest and Continuous Integration (CI) Tutorial

This tutorial will guide you through the process of setting up testing with Pytest and integrating it with Continuous Integration (CI) using GitHub Actions. This will ensure that tests are automatically executed before pushing changes, making your workflow more reliable and error-free.

Prerequisites

  • Basic knowledge of Python and Git.
  • A repository hosted on GitHub.
  • Pytest installed in your development environment.

1. Setting Up Pytest

Step 1: Install Pytest

First, you need to install Pytest if it isn't already installed.

pip install pytest

Step 2: Create Tests

  • Test Files: Create a tests/ directory in your repository. By convention, test files should start with test_ or end with _test.py.

  • Example Function and Test: Let's say you have a function only_positive_addition in the module math_utils that adds two numbers only if they are both positive:

    # math_utils.py
    def only_positive_addition(a, b):
        if a < 0 or b < 0:
            raise ValueError("Both numbers must be positive")
        return a + b

    You can write tests for this function in tests/test_math_utils.py:

    import pytest
    from math_utils import only_positive_addition
    
    def test_only_positive_addition():
        assert only_positive_addition(3, 5) == 8
    
    def test_only_positive_addition_raises_error():
        with pytest.raises(ValueError, match="Both numbers must be positive"):
            only_positive_addition(-1, 5)
  • Interesting Test Cases: Write tests that cover more complex scenarios, such as checking if exceptions are raised correctly or handling edge cases.

Step 3: Run Tests Locally

To run your tests locally:

pytest tests/

You should see the test output in your terminal, which will show how many tests passed or failed.

2. Pre-Push Hook with Git (Optional)

To ensure that tests run before pushing to GitHub, you can add a Git pre-push hook. This step is optional but convenient to prevent you from forgetting to validate the code.

Step 1: Create a Pre-Push Hook

  • Navigate to .git/hooks/ in your local repository.
  • Create a file named pre-push (without an extension).

Step 2: Add Script to Run Tests

Add the following script to your pre-push file:

#!/bin/sh

# Check if the push is being forced to skip tests
if echo "$@" | grep -q -- "--no-test"; then
    echo "Warning: Skipping tests as requested with --no-test."
    exit 0
fi

# Run pytest before pushing
echo "Running tests with pytest..."
pytest

# If tests fail, prevent the push
if [ $? -ne 0 ]; then
    echo "Tests failed. Aborting push."
    echo "You can bypass this check by running 'git push --no-test'."
    exit 1
fi

# If tests pass, continue with the push
echo "Tests passed. Proceeding with push."
exit 0

This script runs the tests, and if any fail, the push is aborted. You can use the --no-test option to bypass this hook if needed:

git push origin branch-name --no-test

Step 3: Make the Hook Executable

Run the following command to make the hook executable:

chmod +x .git/hooks/pre-push

3. Setting Up Continuous Integration (CI) with GitHub Actions

Continuous Integration helps automate the testing of your code changes each time you push to GitHub.

Step 1: Create Workflow File

Create a workflow configuration file in your repository at .github/workflows/pytest.yml.

Step 2: Add GitHub Actions Workflow

Here is an example of a GitHub Actions workflow for running Pytest:

name: Python Tests

on:
  push:
    branches:
      - main
      - dev
  pull_request:
    branches:
      - main
      - dev

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.11'

    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install .

    - name: Run Pytest
      run: |
        pytest tests/

Explanation of the Workflow:

  • name: Specifies the name of the workflow, in this case, "Python Tests".
  • on: Defines the events that trigger the workflow:
    • push: Triggers the workflow when changes are pushed to the main or dev branches.
    • pull_request: Triggers the workflow when a pull request is opened or updated on main or dev.
  • jobs: Defines a job named "test", which runs on the ubuntu-latest operating system. A timeout of 10 minutes is set for this job to prevent hanging processes.
  • steps:
    1. Checkout repository: Uses the actions/checkout action to clone the repository so the workflow can access the code.
    2. Set up Python: Uses actions/setup-python to install Python version 3.11 in the GitHub Actions environment.
    3. Install dependencies: Runs commands to upgrade pip and install the necessary dependencies from the current directory.
    4. Run Pytest: Runs pytest on the tests/ directory to execute all the test cases.

Step 3: Commit and Push the Workflow File

After adding the workflow file, commit and push it to your repository:

git add .github/workflows/pytest.yml
git commit -m "Add GitHub Actions workflow for Pytest"
git push origin main

Step 4: Verify CI Status

Go to your GitHub repository, click on the Actions tab, and you should see your workflow running. GitHub will now automatically test your code every time changes are pushed or a pull request is created.

Note: Even though GitHub Actions provides free credits for CI, each minute of testing consumes credits. It's a good practice to run tests locally first to avoid pushing multiple versions just to fix testing issues.

Running CI Locally vs. GitHub Interface

You can add CI workflows by either creating the .github/workflows files locally and pushing them or by directly using the GitHub interface to create these workflows.

Summary

By setting up Pytest and GitHub Actions, you can ensure that your code is always tested before it reaches production. The pre-push hook helps you catch errors early, and CI with GitHub Actions provides a continuous feedback loop for your team.