0
0
PyTesttesting~5 mins

Running PyTest in GitHub Actions

Choose your learning style9 modes available
Introduction

Running PyTest in GitHub Actions helps you automatically test your Python code every time you make changes. This keeps your code working well without manual checks.

You want to check your Python code for errors after every update.
You want to make sure new code does not break existing features.
You want to run tests automatically when you push code to GitHub.
You want to share test results with your team easily.
You want to save time by automating testing instead of running tests manually.
Syntax
PyTest
name: Python PyTest Workflow

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.x'
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install pytest
      - name: Run tests
        run: pytest

This YAML file defines a GitHub Actions workflow to run PyTest.

It triggers on code pushes and pull requests.

Examples
This example runs tests only on push events using Python 3.9.
PyTest
on: push

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.9'
      - run: pip install pytest
      - run: pytest
This example runs tests on pull requests to the main branch and installs dependencies from a requirements file.
PyTest
on:
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.10'
      - run: pip install -r requirements.txt
      - run: pytest
Sample Program

This workflow runs PyTest automatically on every push or pull request using Python 3.12.

PyTest
name: Python PyTest Workflow

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.12'
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install pytest
      - name: Run tests
        run: pytest
OutputSuccess
Important Notes

Make sure your test files and functions follow PyTest naming conventions (files start with test_, functions start with test_).

You can add more dependencies to the install step if your project needs them.

Use runs-on: ubuntu-latest to run tests on a Linux machine in GitHub Actions.

Summary

GitHub Actions can run PyTest automatically on code changes.

Define a workflow YAML file with steps to set up Python, install PyTest, and run tests.

This helps catch errors early and keeps your code healthy.