Python Testing with pytest
pytest is a popular Python testing framework that makes it easy to write and run automated tests.
Install pytest
TEXT
Install pytest using pip.
pip install pytest
Write Your First Test
Python
Create a simple test function.
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
Save the test in a file such as test_math.py and run pytest from the terminal.
Using Assertions
Python
Test different expected results.
def test_values():
assert 10 > 5
assert "python".upper() == "PYTHON"
assert [1, 2] == [1, 2]
pytest Fixtures
Fixtures provide reusable setup data or resources for tests.
Python
Create and use a simple fixture.
import pytest
@pytest.fixture
def user():
return {"name": "Alice", "age": 25}
def test_user(user):
assert user["name"] == "Alice"
Test Exceptions
Python
Verify that a function raises an exception.
import pytest
def divide(a, b):
return a / b
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(10, 0)
Run Tests
TEXT
Run all pytest tests in the current project.
pytest
You can also run a specific test file by providing its filename, such as pytest test_math.py.
Summary
pytest provides a simple way to automate Python tests. Assertions verify results, fixtures provide reusable setup, and pytest.raises() checks expected exceptions.