PythiloLesson 2 of 12 · progress kept in this browser

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.

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 first run loads pytest into this browser.

Next: Fixtures