Writing Your First pytest Tests
Understand test discovery, assert statements, and test structure.
Installing pytest
Install pytest with pip. It has no mandatory configuration — it discovers tests automatically.
# pip install pytest
# Run all tests
# pytest
# Run a specific file
# pytest test_math.pyA Simple Test Function
pytest collects any function starting with test_. Use plain assert statements — pytest rewrites them for detailed output.
# test_math.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, 1) == 0All lessons in this course
- Writing Your First pytest Tests
- Fixtures and Setup/Teardown
- Parametrize and Test Coverage
- Mocking with unittest.mock