Python CI Workflow with pytest

Set up a GitHub Actions CI workflow for Python projects using pytest, pip caching, and flake8 linting. Includes virtual environment setup and coverage reporting.

Basic CI

Detailed Explanation

Python CI with GitHub Actions

A robust Python CI workflow validates code quality with linting and runs the test suite on every push. This workflow uses actions/setup-python to install a specific Python version and leverages pip caching for faster dependency installation.

Workflow YAML

name: Python CI

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

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

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

      - name: Lint with flake8
        run: |
          pip install flake8
          flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics

      - name: Test with pytest
        run: |
          pip install pytest pytest-cov
          pytest --cov=src --cov-report=xml

      - name: Upload coverage
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: coverage.xml

How It Works

  1. Python setup: actions/setup-python@v5 installs the specified Python version and adds it to PATH. The cache: 'pip' option caches the pip download cache automatically.
  2. Dependency installation: Always upgrade pip first, then install from requirements.txt. For projects using pyproject.toml, replace with pip install -e ".[dev]".
  3. Linting: Flake8 checks for syntax errors and undefined names first (the most critical checks), then optionally run full style checks.
  4. Testing: Pytest with coverage generates both terminal output and an XML report for CI integration.

Tips for Python CI

  • Pin your Python version (e.g., 3.12) rather than using 3.x to avoid unexpected breakage.
  • Use pip install -r requirements.txt for reproducible builds, or pip install -e ".[test]" for package projects.
  • Consider adding mypy for type checking in projects using type hints.

Use Case

CI pipeline for Python web applications (Django, Flask, FastAPI), data science projects, or Python packages. Ensures code quality through linting and testing on every commit.

Try It — GitHub Actions Workflow Builder

Open full tool