0
0
PyTesttesting~8 mins

Running PyTest in GitHub Actions - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Running PyTest in GitHub Actions
Folder Structure
my-python-project/
├── tests/
│   ├── test_example.py
│   └── conftest.py
├── src/
│   └── my_module.py
├── requirements.txt
├── pytest.ini
└── .github/
    └── workflows/
        └── python-pytest.yml
    
Test Framework Layers
  • Tests: Located in tests/ folder, contains test cases and fixtures.
  • Source Code: Application code in src/ folder.
  • Configuration: pytest.ini for pytest settings.
  • CI Workflow: GitHub Actions workflow file in .github/workflows/ to run tests automatically.
  • Dependencies: Listed in requirements.txt for reproducible environment.
Configuration Patterns

Use pytest.ini to configure pytest options like test paths and markers.

Manage environments and secrets in GitHub Actions using secrets and environment variables.

Example python-pytest.yml workflow config:

name: Python PyTest

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 -r requirements.txt
    - name: Run PyTest
      run: |
        pytest --junitxml=results.xml
    - name: Upload Test Results
      uses: actions/upload-artifact@v3
      with:
        name: pytest-results
        path: results.xml
    
Test Reporting and CI/CD Integration
  • PyTest generates test reports (e.g., JUnit XML) for CI systems.
  • GitHub Actions uploads test results as artifacts for review.
  • Use GitHub Actions status checks to block merges on test failures.
  • Integrate with code coverage tools (e.g., coverage.py) for quality metrics.
Best Practices
  1. Keep tests isolated and independent for reliable CI runs.
  2. Use requirements.txt to lock dependencies for consistent environments.
  3. Store secrets securely in GitHub repository settings, never in code.
  4. Use explicit Python versions in GitHub Actions for reproducibility.
  5. Upload test reports and artifacts to help diagnose failures quickly.
Self Check

Where in this folder structure would you add a new test file for a feature called user_login?

Key Result
Organize tests in a dedicated folder and automate PyTest runs with GitHub Actions for continuous testing.