pytest basics
- Python course
- Advanced
- Lesson 13/83
- 5 min
Learn to write tests with pytest.
pytest basics
pytest is the most popular Python test framework. It auto-discovers functions whose names start with test_ and runs them. Validation uses the assert statement.
A test function looks like def test_add():; inside it you write checks like assert add(2, 3) == 5. Run from the command line with pytest file.py.
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0Passing tests show a green dot; failing ones show F. pytest output is short and readable.
Running and output
pytest runs test files from the command line. pytest test_module.py runs one file; bare pytest scans all test_*.py files.
Output summarizes each test on one line: passes show a dot, failures F, skips s. Total time and result count come at the end.
For verbose mode use pytest -v; each test name prints separately. For error detail pytest -v --tb=short is useful.
Practice Write add and test_add
Write a function add(a, b) with body return a + b. Then define a test function test_add(); inside it run assert add(2, 3) == 5. At the end of the file, call test_add() and print("ok").
Starter code
# add function: sum two values and return
# test_add function: check add(2, 3) == 5
# call test_add() then print "ok"Sample solution
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
test_add()
print("ok")Expected output
ok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the test function name
def ____(self=None):
assert add(2, 3) == 5
def test_add(self=None):
assert add(2, 3) == 5
Explanation: The test_ prefix is required for pytest's auto-discovery.
2 Match the pytest output symbols
| Term | Meaning |
|---|---|
. |
Passing test |
F |
Failing test |
s |
Skipped test |
-v |
Verbose mode |
3 Which functions does pytest auto-discover?
- Those starting with test_ Correct answer
- Those starting with main
- All functions
- Only class methods
Explanation: The test_ prefix is the standard for pytest's auto-discovery.