intermediateLibraries

Testing with pytest

Write and run tests to ensure code correctness.

In this lesson

01Writing Tests

Use pytest for simple and powerful testing.

Python
1# calculator.py
2def add(a, b):
3 return a + b
4
5def divide(a, b):
6 if b == 0:
7 raise ValueError("Cannot divide by zero")
8 return a / b
9
10# test_calculator.py
11import pytest
12from calculator import add, divide
13
14def test_add():
15 assert add(2, 3) == 5
16 assert add(-1, 1) == 0
17
18def test_divide():
19 assert divide(10, 2) == 5.0
20 with pytest.raises(ValueError):
21 divide(10, 0)
22
23# Run: pytest test_calculator.py -v