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
- Triggers: The
onblock tells GitHub to start this workflow whenever code ispushed or apull_requestis opened. - Environment:
runs-on: ubuntu-latestspins up a fresh, ephemeral virtual machine. - Steps:
actions/checkoutclones your repository code into the machine.actions/setup-pythonconfigures the specific Python version you require.- The
runcommands execute standard shell instructions to install yourrequirements.txtand 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.