How pytest finds tests
Run pytest and it searches the folder for files named test_*.py or *_test.py. In each file it collects functions whose names start with test, and classes whose names start with Test and that have no __init__, taking their test methods. Anything else is skipped without a failure, so a test named check_total simply never runs.
class Stack:
def __init__(self):
self.items = []
class TestStack:
def setup_method(self):
self.stack = Stack()
def test_starts_empty(self):
assert self.stack.items == []
# What pytest does for each test method:
case = TestStack()
case.setup_method()
case.test_starts_empty()
print("passed")pytest makes a new instance of the class for every test method, so methods cannot share state through self. setup_method runs before each one.
Choosing what runs
pytest test_stack.py::TestStackruns one class.pytest -k "pop and not empty"selects tests by name.pytest -xstops at the first failure.- The exit code is 0 when everything passed, 1 when a test failed, and 5 when nothing was collected.
Your task
Stack is written for you. Write a class TestStack that pytest collects, with test_new_stack_is_empty, test_pop_returns_last_pushed (push two items, expect the second back) and test_pop_empty_raises (an IndexError), each starting from a fresh stack.
The explanation opens here once every check passes.