What's the purpose of top_level_dir in TestLoader.discover?
Asked Answered
S

1

11

According to the documentation for unittest.TestLoader.discover:

discover(start_dir, pattern=’test*.py’, top_level_dir=None)

... All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately...

I've done some experiments myself, and it seems that when top_level_dir is different to start_dir and is not set, nothing went wrong: all tests are discovered and imported properly.

I wonder what's the purpose of passing a top_level_dir argument to discover. Why would it need to know that's top directory is? I suppose all its job is to (i) find testing packages/modules in start_dir, and (ii) import them, isn't it?

Or, can someone provide an example where the absence of top_level_dir causes test discovery to at least partially fail?

Sileas answered 24/9, 2017 at 12:22 Comment(0)
W
0

The top_level_dir argument in unittest.TestLoader.discover() is used to specify the root directory of the project being tested. This is used to determine the package structure of the modules being tested, and allows the discover() method to properly import and run the tests.

When top_level_dir is not specified, the discover() method will use the current working directory as the root directory of the project. This can be problematic if the current working directory is not the root of the project, as it may cause the method to incorrectly import or not find certain tests.

For example, consider a project with the following directory structure:

    myproject/
        mypackage/
            __init__.py
            tests/
                __init__.py
                test_module.py

If you run unittest.TestLoader.discover() from the myproject directory, and don't specify the top_level_dir argument, the method will search for tests in the current working directory, but it will not find any tests as they are located in the mypackage/tests/ subdirectory.

However, if you specify top_level_dir='myproject' argument, the discover() method will correctly find and import the tests in the mypackage/tests/ directory.

In summary, the top_level_dir argument is used to specify the root directory of the project being tested and it helps to find and import the tests correctly even if the current working directory is not the root of the project.

Wildwood answered 20/1, 2023 at 11:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.