Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 38 ยท Getting Started

Your First Test

Write your first pytest test from scratch, split code and tests into separate files, run them, and learn the test-fix-rerun loop that drives everyday testing.

You know what pytest is. Now you will use it the way you will every day: write a small function, write a test for it, run the test, see it fail, fix the code, and see it pass. That loop of write, run, read the report, fix is the heart of testing, and pytest makes each step quick.

You will also learn the standard project shape of code in one file, tests in another, because real programs never keep both together.

The code under test

We will test a small function that turns a title into a URL slug: lowercase, words joined by hyphens. Real sites need this all the time.

Python
# slugs.py
def slugify(title):
    return title.lower().replace(" ", "-")

The module is called slugs.py. Its tests go next to it, in a file called test_slugs.py. The test_ prefix is how pytest recognizes it.

Writing the first test

A test is just a function. It imports what it needs, calls the code, and asserts.

Python Test and code in separate files

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 dictionary keys are file names, so this example mirrors a real folder with two files. from slugs import slugify works because pytest puts the test file's folder on the import path.

Let the test find a bug

Tests are most useful when they ask harder questions. What happens with extra spaces or punctuation? Add tests for the behavior you want, and watch which ones fail.

Python Tests that expose bugs

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.

Two of the three tests fail, and each report tells you the exact difference: leading hyphens in one case, a comma and exclamation mark in the other. --tb=short asks for compact tracebacks; you will meet more options in Running Tests.

Fix the code, rerun the tests

Now improve slugify with a regular expression: lowercase the text, replace every run of characters that are not letters or digits with one hyphen, then trim hyphens from both ends.

Python Green again

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.

All three pass. The old test still passes, which is the second big benefit of tests: when you change code, they tell you immediately whether you broke something that used to work. That safety net is called a regression test suite.

flowchart LR
    A["write or change<br/>a test"] --> B["run pytest"]
    B --> C{"all green?"}
    C -->|no| D["read the report,<br/>fix the code"]
    D --> B
    C -->|yes| E["next behavior"]
    E --> A

The everyday loop. Many developers write the test first (test-driven development), others write it right after the code. Either way the loop is the same.

Choosing good test names

A failing test shows up in the report by name. Compare these two:

  • test_1 tells you nothing.
  • test_punctuation_is_removed tells you what promise broke.

A good name states the scenario and the expected result. Long names are fine; nobody calls a test function by hand. Common patterns are test_<behavior> and test_<function>_<scenario>_<expected>.

One behavior per test

You might be tempted to pack many assertions into one test:

Python
def test_slugify():
    assert slugify("Hello World") == "hello-world"
    assert slugify("  Hello  ") == "hello"
    assert slugify("Hi!") == "hi"

The problem is that the first failing assert stops the test, so you never learn whether the later ones pass. Small, focused tests give you a complete picture in one run. When many tests differ only by their data, use parametrization instead of copy and paste.

A test with several asserts is not forbidden. It is fine when they all check one behavior, for example several fields of one returned object. The rule is one reason to fail.

Errors versus failures

One more distinction you will meet right away. Here a test fails and another one raises an error in the code under test:

Python Failure and error

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 count as failed. The first raised AssertionError because a check was false. The second raised IndexError because the code under test misbehaved. In both cases the fix is in your code or in the test, and pytest prints where. The word error (not "failed") is reserved for problems in setup such as fixtures.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is test_slugs.py a good file name for tests of slugs.py?

    pytest collects files matching test_*.py or *_test.py. Naming the file after the module is only a convention that helps humans.
  2. 2. A test contains three asserts and the first one fails. What happens to the other two?

    An AssertionError ends the test function immediately. That is one reason to keep tests small and focused.
  3. 3. What is a regression test suite for?

    Rerunning the existing tests after each change catches regressions, behavior that used to work and now does not.
  4. 4. Which test name is best?

    A name that states the behavior tells you what broke from the failure report alone.

Summary

  • Put code in one module and its tests in test_<module>.py.
  • The loop is write a test, run pytest, read the report, fix, repeat.
  • Name tests after the behavior they check, and keep each test focused on one reason to fail.
  • A failing assert and an exception in your code both make a test fail; "error" is for setup problems.
  • Passing old tests after a change is your protection against regressions.

Next: Running Tests