Changing Test Discovery Rules

pytest finds tests to run based on certain test discovery rules. The standard test discovery rules are:

  • Start at one or more directory. You can specify filenames or directory names on the command line. If you don’t specify anything, the current directory is used.

  • Look in the directory and all subdirectories recursively for test modules.

  • A test module is a file with a name that looks like test_*.py or *_test.py.

  • Look in test modules for functions that start with test_.

  • Look for classes that start with Test. Look for methods in those classes that start with test_ but don’t have an __init__ method.

These are the standard discovery rules; however, you can change them.

python_classes

The usual test discovery rule for pytest and classes is to consider a class a potential test class if it starts with Test*. The class also can’t have an __init__() function. But what if we want to name our test classes <something>Test or <something>Suite? That’s where python_classes comes in:

 [pytest]
 python_classes = ​*Test Test* *Suite

This enables us to name classes like this:

 class​ DeleteSuite():
 def​ test_delete_1():
  ...
 
 def​ test_delete_2():
  ...
 
  ....

python_files

Like pytest_classes, python_files modifies the default test discovery rule, which is to look for files that start with test_* or end in *_test.

Let’s say you have a custom test framework in which you named all of your test files check_<something>.py. Seems reasonable. Instead of renaming all of your files, just add a line to pytest.ini like this:

 [pytest]
 python_files = ​test_* *_test check_*

Easy peasy. Now you can migrate your naming convention gradually if you want to, or just leave it as check_*.

python_functions

python_functions acts like the previous two settings, but for test function and method names. The default is test_*. To add check_*—you guessed it—do this:

 [pytest]
 python_functions = ​test_* check_*

Now the pytest naming conventions don’t seem that restrictive, do they? If you don’t like the default naming convention, just change it. However, I encourage you to have a better reason. Migrating hundreds of test files is definitely a good reason.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.138.195