Python单元测试与发现

2024-06-16 13:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有目录,其中包含名为: test_foo.py

每个文件都是一个测试用例。

我想

1)从命令行运行目录中的所有测试。我正在使用unittest2,因为我们正在运行Python 2.5.1。在其中一个目录中,我尝试在命令行中键入:

python -m unittest2 discover -p 'test_*.py'

以及几个不同的变种。我没有错,但什么也没发生。我希望该目录中所有测试用例中的所有测试都能运行并获得结果。

2)我还尝试在执行此操作的目录中使用脚本:

loader = unittest2.TestLoader()
t = loader.discover('.')

如果我打印t变量,我可以看到我的测试用例,但是从文档中我无法知道一旦拥有loader对象该怎么办。


Tags: 文件命令行文档pytest目录脚本键入
3条回答

给出您在Python上的命令行中使用unittest2的方法,我认为您可能遗漏了the note on the ^{} PyPI page

Note

Command line usage

In Python 2.7 you invoke the unittest command line features (including test discover) with python -m unittest <args>. As unittest is a package, and the ability to invoke packages with python -m ... is new in Python 2.7, we can't do this for unittest2.

Instead unittest2 comes with a script unit2. Command line usage:

unit2 discover unit2 -v test_module

There is also a copy of this script called unit2.py, useful for Windows which uses file-extensions rather than shebang lines to determine what program to execute files with. Both of these scripts are installed by distutils.

您是否尝试过unit2脚本,本说明建议将其作为Python 2.7的“作为主脚本运行包”功能的替代品?也许它的源代码也有助于找出如何从您自己的代码中发现和运行测试,如果您希望这样做的话。

我在运行python -m unittest discover时遇到了同样的问题。这里有一个很好的检查表来验证您的设置。Nose在允许的配置下更灵活,但未必更好。

  1. 确保所有文件/目录都以test开头。不要使用test-something.py,因为这不是有效的python模块名。使用test_something.py

  2. 如果要将测试放在子目录中(例如test/),请确保创建一个test/__init__.py文件,以便python将该目录视为一个包。

  3. 所有类测试用例定义都必须是扩展的unittest.TestCase。例如

    class DataFormatTests(unittest.TestCase)
    

一旦发现了测试,就可以使用测试运行器运行它们。

import unittest2
loader = unittest2.TestLoader()
tests = loader.discover('.')
testRunner = unittest2.runner.TextTestRunner()
testRunner.run(tests)

运行上面的代码将把测试结果打印出来。

相关问题 更多 >