Starting with Pytest for automated testing
Pytest is a powerful testing framework for Python, allowing developers to write simple, scalable, and efficient tests. Below is a guide to getting started with Pytest.
1. Installing Pytest
# Install Pytest using pip
pip install pytest
2. Writing Your First Pytest Test
# test_example.py
def test_addition():
assert 1 + 1 == 2
def test_string():
assert "pytest".upper() == "PYTEST"
3. Running Tests
# Run all tests
pytest
# Run tests with detailed output
pytest -v
# Run a specific test file
pytest test_example.py
4. Using Fixtures for Setup and Teardown
import pytest
@pytest.fixture
def sample_data():
return {"username": "test_user", "password": "secure123"}
def test_login(sample_data):
assert sample_data["username"] == "test_user"
5. Parametrized Tests
@pytest.mark.parametrize("num1, num2, expected", [
(1, 2, 3),
(3, 5, 8),
(10, 20, 30)
])
def test_addition(num1, num2, expected):
assert num1 + num2 == expected
6. Marking Tests (Skipping & Expected Failures)
@pytest.mark.skip(reason="Skipping this test for now")
def test_skip():
assert False
@pytest.mark.xfail(reason="Known issue")
def test_expected_fail():
assert False
7. Capturing Logs in Tests
import logging
@pytest.fixture
def log_data(caplog):
caplog.set_level(logging.INFO)
return caplog
def test_logging(log_data):
logging.info("This is a log message")
assert "log message" in log_data.text
8. Running Tests in Parallel
# Install pytest-xdist for parallel execution
pip install pytest-xdist
# Run tests in parallel using 4 CPU cores
pytest -n 4
9. Generating Test Reports
# Install pytest-html for generating test reports
pip install pytest-html
# Generate an HTML test report
pytest --html=report.html
10. Using Assertions Effectively
def test_list_contains():
data = [1, 2, 3, 4]
assert 3 in data
def test_string():
message = "Hello Pytest"
assert message.startswith("Hello")