Unittest Framework 简明教程

UnitTest Framework - Test Discovery

TestLoader 类有一个 discover() 函数。Python 测试框架将此函数用于简单的测试发现。为了保持兼容性,包含测试的模块和包必须可以从顶级目录导入。

The TestLoader class has a discover() function. Python testing framework uses this for simple test discovery. In order to be compatible, modules and packages containing tests must be importable from top level directory.

以下适用于测试发现的基本命令行用法 −

The following is the basic command line usage of test discovery −

Python –m unittest discover

解释器将尝试递归地加载所有包含测试的当前目录和内部目录中的模块。其他命令行选项 −

Interpreter tries to load all modules containing test from current directory and inner directories recursively. Other command line options are −

Sr.No.

Options & Description

1

-v, --verbose Verbose output

2

-s, --start-directory directory Directory to start discovery (. default)

3

-p, --pattern pattern Pattern to match test files (test*.py default)

4

-t, --top-level-directory directory Top level directory of project (defaults to start directory)

例如,为了发现“tests”目录中名称以“assert”开头的模块中的测试,使用了以下命令行:

For example, in order to discover the tests in modules whose names start with 'assert' in 'tests' directory, the following command line is used −

C:\python27>python –m unittest –v –s "c:\test" –p "assert*.py"

测试发现通过导入测试来加载测试。一旦测试发现从您指定的启动目录中找到了所有测试文件,它就会将路径转换为要导入的包名。

Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify, it turns the paths into package names to import.

如果您将启动目录作为包名而不是路径提供给目录,则发现会假设从中导入的任何位置都是您想要的位置,因此您不会收到警告。

If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning.