How to Identifying TestFiles and TestFunctions in PyTest

Running pytest without referencing a filename will run all files of format test_*.py or *_test.py in the current directory and subdirectories. Pytest naturally distinguishes those files as test files. We can make pytest run different filenames by explicitly referencing them.

Pytest requires the test function names to begin with test. Function names that are not of format test* are not considered as test functions by pytest. We can’t explicitly make pytest consider any function not beginning with the test as a test function.

PyTest test discovery conventions

If no arguments are specified then test files are searched in locations from testpaths (if configured) or the current directory. Alternatively, command-line arguments can be used in any combination of directories, file names or node ids.

In the selected directories, pytest looks for test_*.py or *_test.py files. In the selected files, pytest looks for test prefixed test functions outside of class and test prefixed test methods inside Test prefixed test classes (without an __init__() method).

Python Pytest Simple Example

In the first example, we are going to test a module with add() and mul() functions with pytest.

def add(a, b=5):
    return a + b


def mul(a, b=5):
    return a * b

The testing file test_sample.py has a test word in its name.

import sample

def test_add():
    assert sample.add(10,20) == 30

def test_mul():
    assert sample.mul(10,5) == 50

Also, the testing function sample_test() has a test word. We use the assert keyword to test the value of the sample.

 

  • If you want to use the default set value of y in your test, just make the following changes in sample_test():
import sample

def test_add():
    assert sample.add(10) == 15


def test_mul():
    assert sample.mul(6) == 30
  • let’s change the sample_test() file code to check whether the test case fails or not
import sample

def test_add():
    assert sample.add(10) == 125   #fail case


def test_mul():
    assert sample.mul(6) == 30

  • A more verbose(more detailed) output is shown with pytest test_sample.py -v

  • You can even use code py.test which will automatically test the code since we have used the prefix test.
  • Suppose we do not use the test prefix and execute our test_sample.py as follows, then we can see that pytest wont recognize that testing function. For example:
import sample

def est_add(): #it wont recognize this function and perform test
    assert sample.add(10) == 15


def test_mul():
    assert sample.mul(6) == 30