0
0
PyTesttesting~15 mins

Running PyTest in GitHub Actions - Build an Automation Script

Choose your learning style9 modes available
Automate running PyTest tests in GitHub Actions
Preconditions (2)
Step 1: Create a .github/workflows/python-test.yml file in the repository
Step 2: Define a workflow that triggers on push and pull request events
Step 3: Set up a job that runs on ubuntu-latest
Step 4: Add steps to check out the repository code
Step 5: Add a step to set up Python 3.12
Step 6: Add a step to install dependencies from requirements.txt
Step 7: Add a step to run pytest command
Step 8: Push the workflow file to the repository
✅ Expected Result: GitHub Actions runs the workflow on push or pull request, installs dependencies, runs pytest tests, and reports test results as pass or fail in the Actions tab
Automation Requirements - GitHub Actions YAML workflow
Assertions Needed:
Verify workflow triggers on push and pull request
Verify Python 3.12 is used
Verify dependencies are installed
Verify pytest runs and completes successfully
Verify test results are reported in GitHub Actions
Best Practices:
Use official actions like actions/checkout and actions/setup-python
Use explicit Python version 3.12
Cache dependencies if possible
Keep workflow steps clear and simple
Use separate steps for install and test
Automated Solution
PyTest
name: Python PyTest CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - name: Check out repository code
      uses: actions/checkout@v3

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

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

    - name: Run PyTest
      run: |
        pytest

This GitHub Actions workflow is named 'Python PyTest CI'. It triggers on pushes and pull requests to the main branch.

The job runs on the latest Ubuntu runner.

First, it checks out the repository code using the official actions/checkout@v3 action.

Then it sets up Python 3.12 explicitly using actions/setup-python@v4.

Next, it installs dependencies from requirements.txt using pip.

Finally, it runs pytest to execute the tests.

This setup ensures tests run automatically on GitHub servers and results show in the Actions tab.

Common Mistakes - 5 Pitfalls
Not specifying the Python version explicitly
Not installing dependencies before running tests
Running pytest without checking out the code
Using an outdated or incorrect action version
{'mistake': 'Not triggering workflow on pull requests', 'why_bad': "Tests won't run on code changes from forks or branches before merging.", 'correct_approach': 'Include pull_request trigger to test all proposed changes.'}
Bonus Challenge

Now add caching of pip dependencies to speed up workflow runs

Show Hint