Course contentsShow
← Python
Lesson 1039 of 1,06016. Capstone and AutomationFree lesson

Automating Testing with GitHub Actions

Implement continuous integration workflows that automatically run your test suite whenever code is pushed to your repository.

In this lesson, you will learn how to trigger your Python test suite automatically on every push to your repository using GitHub Actions.

From Manual Checks to Automated CI

Up until now, you have been building robust tools, managing dependencies with lockfiles, and packaging applications. However, manually running your tests before every commit is error-prone. Continuous Integration (CI) bridges this gap by ensuring that every change is validated in a clean, isolated environment the moment you push your code to GitHub.

Defining the Workflow

GitHub Actions uses YAML files located in .github/workflows/ to define your automation pipeline. To test a Python project, we need to set up a virtual environment, install the pinned dependencies, and execute the test runner (like pytest).

Create a file named .github/workflows/test.yml in your repository:

name: Python CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - 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 -r requirements.txt
          
      - name: Run tests
        run: pytest

How It Works

  1. Triggers: The on block tells GitHub to start this workflow whenever code is pushed or a pull_request is opened.
  2. Environment: runs-on: ubuntu-latest spins up a fresh, ephemeral virtual machine.
  3. Steps:
    • actions/checkout clones your repository code into the machine.
    • actions/setup-python configures the specific Python version you require.
    • The run commands execute standard shell instructions to install your requirements.txt and invoke your testing framework.

If pytest exits with a non-zero status code (indicating a test failure), the GitHub Action will mark the build as failed, preventing you from merging broken code into your main branch. This gives you high confidence that your logic holds up across different pushes, regardless of your local machine's state.

Key Takeaway: By automating your test suite with GitHub Actions, you transform your repository into a self-validating system that prevents regressions before they reach your production branch.