Test discovery and naming conventions

RoadmapsPython

Overview

Before testing code, we need a way to find and run those tests. **Test discovery is how tools like pytest find your test files and functions automatically.** To see this, imagine we have a function that checks if a student passed their exams. Here is a working test file: ```python # File: test_marks.py def has_passed(marks): return marks > 40 def test_has_passed(): assert has_passed(50) == True ``` When we run the command `pytest`, it looks for files starting with `test_` or ending with `_test.py`. Inside those files, it looks for functions starting with `test_`. Because our file is named `test_marks.py` and our function is named `test_has_passed`, pytest finds and runs it. Now, let us look at a similar test, but one step is blank: ```python # File: test_attendance.py def is_present(days): return days > 75 def _______is_present(): assert is_present(80) == True ``` To make pytest find this test automatically, we must name the function `test_is_present`.

Without a naming rule, you would have to manually list every test file you want to run. Discovery rules save time and keep projects organized.

Where used: Pytest setups, CI/CD pipelines

Why learn this

Code walkthrough

# File: test_logic.py
def is_even(n):
  return n % 2 == 0

def test_is_even():
  result = is_even(4)
  print('Test running')
  assert result == True

test_is_even()

Focus: def test_is_even():

Aha moment

# File: my_tests.py
def test_logic():
  print('Checking logic')
  assert True

print('Done')

Prediction: If you run `pytest` in the folder containing this file, will it run `test_logic`?

Common guess: Yes, because the function starts with test_.

The file name `my_tests.py` does not start with `test_` or end with `_test.py`. pytest will not look inside it, so the test is skipped.

Common mistakes

Recall questions

Understanding checks

What happens when you run pytest on this file?

pytest runs zero tests because verify_add does not start with test_.

Test discovery relies strictly on the `test_` prefix. Since `verify_add` does not start with `test_`, pytest ignores it entirely.

Will pytest find and run this test?

Yes, because the file ends with _test.py and the function starts with test_.

Files ending in `_test.py` are also valid for test discovery, and the function correctly starts with `test_`.

Practice tasks

Fix the naming

Given this code, change the names so that pytest will find and run the test.

Challenge

Name a test file and function

Write a test file named correctly for pytest. Inside it, write a test function named correctly that asserts `True`.

Continue learning

Previous: Defining functions and return values

Next: Assertions and pytest.raises

Return to Python Roadmap