“Testing leads to failure, and failure leads to understanding.” – Burt Rutan
If you’re stepping into the world of Python automation testing, then Pytest is one of the most powerful tools to have in your toolkit. It’s lightweight, scalable, and packed with features that make writing and maintaining test cases efficient and enjoyable.
In this post, we’ll walk you through Pytest basics, why it’s the preferred choice for many automation engineers, and how to set it up for your first automation project.
Table of Contents
Why Use Pytest?
Pytest is a mature testing framework for Python that helps in:
- Writing simple unit tests and complex functional tests.
- Automatic test discovery.
- Advanced features like fixtures, parameterization, and assert rewriting.
- Easy integration with CI/CD tools and frameworks like Selenium, Requests, etc.
Prerequisites
Make sure you have Python installed. You can check it using:
python --version
Install pytest
via pip:
pip install pytest
Writing Your First Test with Pytest
Create a file named test_sample.py
:
# test_sample.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
Now, run your test:
pytest test_sample.py
Pytest File and Naming Conventions
To ensure Pytest discovers your tests automatically:
- Test file names should start with
test_
or end with_test
. - Test functions should start with
test_
.
Parameterization
Test multiple inputs without writing separate test functions:
import pytest
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(10, 5, 15),
(0, 0, 0)
])
def test_add(a, b, expected):
assert a + b == expected
Using Fixtures
Fixtures are used to set up and tear down test environments:
import pytest
@pytest.fixture
def sample_data():
return {"username": "admin", "password": "1234"}
def test_login(sample_data):
assert sample_data["username"] == "admin"
Testing Web APIs (Requests + Pytest)
import requests
def test_status_code():
response = requests.get("https://httpbin.org/get")
assert response.status_code == 200
You can install requests
using:
pip install requests
Advanced Features
Grouping tests with markers (@pytest.mark.smoke
)
Running specific tests: pytest -k "test_add"
Generating HTML reports: pytest --html=report.html
Run All Tests in a Directory
pytest tests/
Make sure all test files follow Pytest naming conventions.
Integrate with CI Tools
Pytest integrates well with CI tools like:
- Jenkins
- GitHub Actions
- GitLab CI
- Azure DevOps
You can trigger pytest
commands in the build pipeline to ensure your code is always tested automatically.
Learning Resources
Conclusion
Pytest is more than just a test runner—it’s a complete testing framework. Whether you’re writing quick unit tests or building complex automation frameworks, Pytest is flexible enough to handle it all.
Next Steps:
- Explore pytest-selenium for web UI testing.
- Start using fixtures in large test suites.
- Try mocking using
pytest-mock
.