Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 38 ยท Getting Started

What Is pytest?

Learn what pytest is, why most Python projects choose it over unittest, how a test is shaped, and run real pytest sessions right in your browser.

Every program you write makes promises: this function adds two numbers, that one validates an email, a third one never returns a negative price. A test is a small program that checks one of those promises and shouts when it is broken. Without tests you find bugs when a user does. With tests you find them in seconds, before you ship.

pytest is the most popular testing framework for Python. You write plain functions whose names start with test_, use the ordinary assert statement, and pytest does the rest: it finds your tests, runs them, and prints a precise report that shows what went wrong and why. This track teaches pytest from your first test to plugins, mocking, coverage and continuous integration.

How the examples run. Every example on this page runs real pytest 9 inside your browser. A small helper called run_pytest writes the test files you see in the code into a temporary folder and calls pytest.main() on it, which is the same entry point the pytest command uses. On your own computer you skip the helper: save the test file and type pytest.

Why pytest?

Python ships with a testing module called unittest, modelled on Java's JUnit. It works, but it asks for a lot of ceremony: a class, inheritance, and special methods such as assertEqual. pytest keeps the useful parts and removes the ceremony.

Feature unittest pytest
A test is a method in a TestCase subclass any function named test_*
Checking a value self.assertEqual(a, b) assert a == b
Failure report shows both values shows both values, a diff, and the sub-expressions
Setup and teardown setUp / tearDown methods fixtures you request by name
Many inputs loops or subTest @pytest.mark.parametrize
Extras built in only hundreds of plugins

pytest can also run existing unittest tests unchanged, so you can adopt it gradually.

A first look

Here is the smallest useful test. The function under test is add, and the test is a function that calls it and asserts the result.

Python Your first pytest run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the report from the top. pytest collected two items, ran each one, and marked it PASSED. The line at the bottom is the summary, and the exit code is 0, which is how scripts and CI systems know the run succeeded.

What a failure looks like

A test framework earns its keep when something breaks. Change one expected value and run again.

Python Reading a failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The report is the main feature. The line starting with > marks the failing assert. The lines starting with E explain it: pytest evaluated total(prices) for you (9.75) and compared it to 10.0. You never had to write a message.

The anatomy of a test

Every pytest test follows the same three beats, often called Arrange, Act, Assert:

  1. Arrange: build the input and any objects you need.
  2. Act: call the code you are testing, once.
  3. Assert: check the outcome with assert.
Python
def test_discount_is_applied():
    price = 80                           # arrange
    result = apply_discount(price, 25)   # act
    assert result == 60                  # assert

Keep each test small and about one behavior. When a test fails, its name should tell you what broke without opening the file.

How pytest finds and runs tests

flowchart LR
    A["pytest command"] --> B["collect<br/>files, classes, functions"]
    B --> C["set up<br/>fixtures"]
    C --> D["run<br/>each test"]
    D --> E["report<br/>pass, fail, error"]
    E --> F["exit code"]

A pytest run has four stages. Collection decides what the tests are; everything after that is per test.

A test can end in four ways:

  • passed: no assert failed and nothing raised.
  • failed: an assert was false, or the test raised an unexpected exception.
  • error: something went wrong outside the test body, usually in a fixture.
  • skipped or xfailed: you told pytest not to run it or to expect a failure (see skip and xfail).

pytest and unittest side by side

The same check written both ways makes the difference concrete. The unittest version below runs through pytest too.

Python unittest style and pytest style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both pass, and pytest reports them in one list. You can migrate a project one file at a time.

Run pytest as python -m pytest when you want the current folder added to the import path. It also guarantees you use the pytest installed in the active virtual environment.

Installing pytest on your machine

Create a virtual environment, install pytest, and check the version:

Terminal
python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install pytest
pytest --version

Create test_hello.py with one test function and run pytest. That is the whole setup. The next lesson walks through it step by step.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a function be called for pytest to collect it as a test by default?

    By default pytest collects files named test_*.py or *test.py and, inside them, functions starting with test. No decorator or base class is needed.
  2. 2. How do you check that two values are equal in a pytest test?

    pytest uses the plain assert statement and rewrites it so a failure shows the values involved.
  3. 3. A test passes when it...

    A test's return value is ignored. It passes if no assertion fails and no exception escapes.
  4. 4. What does an exit code of 0 from pytest mean?

    0 means success. Exit code 1 means some tests failed and 5 means that no tests were collected.

Summary

  • A test is a small function that checks one promise about your code.
  • pytest collects test_* functions, runs them, and reports each as passed, failed, error or skipped.
  • You write checks with plain assert; pytest explains failures with values and diffs.
  • Arrange, Act, Assert keeps tests short and readable.
  • pytest can run existing unittest tests, so you can adopt it gradually.

Next: Your First Test