Repository navigation
Pytest and CI Tutorial
This tutorial will guide you through the process of setting up testing with Pytest and integrating it with Continuous Integration (CI) using GitHub Actions. This will ensure that tests are automatically executed before pushing changes, making your workflow more reliable and error-free.
- Basic knowledge of Python and Git.
- A repository hosted on GitHub.
- Pytest installed in your development environment.
First, you need to install Pytest if it isn't already installed.
pip install pytest-
Test Files: Create a
tests/directory in your repository. By convention, test files should start withtest_or end with_test.py. -
Example Function and Test: Let's say you have a function
only_positive_additionin the modulemath_utilsthat adds two numbers only if they are both positive:# math_utils.py def only_positive_addition(a, b): if a < 0 or b < 0: raise ValueError("Both numbers must be positive") return a + b
You can write tests for this function in
tests/test_math_utils.py:import pytest from math_utils import only_positive_addition def test_only_positive_addition(): assert only_positive_addition(3, 5) == 8 def test_only_positive_addition_raises_error(): with pytest.raises(ValueError, match="Both numbers must be positive"): only_positive_addition(-1, 5)
-
Interesting Test Cases: Write tests that cover more complex scenarios, such as checking if exceptions are raised correctly or handling edge cases.
To run your tests locally:
pytest tests/You should see the test output in your terminal, which will show how many tests passed or failed.
To ensure that tests run before pushing to GitHub, you can add a Git pre-push hook. This step is optional but convenient to prevent you from forgetting to validate the code.
- Navigate to
.git/hooks/in your local repository. - Create a file named
pre-push(without an extension).
Add the following script to your pre-push file:
#!/bin/sh
# Check if the push is being forced to skip tests
if echo "$@" | grep -q -- "--no-test"; then
echo "Warning: Skipping tests as requested with --no-test."
exit 0
fi
# Run pytest before pushing
echo "Running tests with pytest..."
pytest
# If tests fail, prevent the push
if [ $? -ne 0 ]; then
echo "Tests failed. Aborting push."
echo "You can bypass this check by running 'git push --no-test'."
exit 1
fi
# If tests pass, continue with the push
echo "Tests passed. Proceeding with push."
exit 0This script runs the tests, and if any fail, the push is aborted. You can use the --no-test option to bypass this hook if needed:
git push origin branch-name --no-testRun the following command to make the hook executable:
chmod +x .git/hooks/pre-pushContinuous Integration helps automate the testing of your code changes each time you push to GitHub.
Create a workflow configuration file in your repository at .github/workflows/pytest.yml.
Here is an example of a GitHub Actions workflow for running Pytest:
name: Python Tests
on:
push:
branches:
- main
- dev
pull_request:
branches:
- main
- dev
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install .
- name: Run Pytest
run: |
pytest tests/Explanation of the Workflow:
- name: Specifies the name of the workflow, in this case, "Python Tests".
-
on: Defines the events that trigger the workflow:
-
push: Triggers the workflow when changes are pushed to the
mainordevbranches. -
pull_request: Triggers the workflow when a pull request is opened or updated on
mainordev.
-
push: Triggers the workflow when changes are pushed to the
-
jobs: Defines a job named "test", which runs on the
ubuntu-latestoperating system. A timeout of 10 minutes is set for this job to prevent hanging processes. -
steps:
-
Checkout repository: Uses the
actions/checkoutaction to clone the repository so the workflow can access the code. -
Set up Python: Uses
actions/setup-pythonto install Python version 3.11 in the GitHub Actions environment. -
Install dependencies: Runs commands to upgrade
pipand install the necessary dependencies from the current directory. -
Run Pytest: Runs
pyteston thetests/directory to execute all the test cases.
-
Checkout repository: Uses the
After adding the workflow file, commit and push it to your repository:
git add .github/workflows/pytest.yml
git commit -m "Add GitHub Actions workflow for Pytest"
git push origin mainGo to your GitHub repository, click on the Actions tab, and you should see your workflow running. GitHub will now automatically test your code every time changes are pushed or a pull request is created.
Note: Even though GitHub Actions provides free credits for CI, each minute of testing consumes credits. It's a good practice to run tests locally first to avoid pushing multiple versions just to fix testing issues.
You can add CI workflows by either creating the .github/workflows files locally and pushing them or by directly using the GitHub interface to create these workflows.
By setting up Pytest and GitHub Actions, you can ensure that your code is always tested before it reaches production. The pre-push hook helps you catch errors early, and CI with GitHub Actions provides a continuous feedback loop for your team.