Automate running PyTest tests in GitHub Actions
Preconditions (2)
✅ 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
Jump into concepts and practice - no test required
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.
Now add caching of pip dependencies to speed up workflow runs
pytest in a GitHub Actions workflow?pip. The correct command is run: pip install pytest. - name: Run tests
run: pytest tests/pytest tests/ runs all test files inside the tests/ folder by default but does not install dependencies or deploy code.tests/ directory -> Option D- name: Run tests run: py.test
pytest and py.test work if installed.strategy.matrix to run on 3.10/3.11; checkout, then setup Python with ${{ matrix.python-version }}, install pytest, run tests.