Python单元测试和发现

55

我有一些目录,其中包含命名为:

test_foo.py

的文件。

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

我希望:

  1. Run all the tests in a directory from the command line. I am using unittest2, since we are running Python 2.5.1. From one of these directories I tried typing this at the command line:

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

    and several different variants. I get no error, but nothing happens. I was expecting all the tests within all the test cases in that directory to run and get results.

  2. I also tried having a script in the directory where I did this:

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

    If I print the t variable, I can see my test cases, but from the documentation I can't figure out what to do with the loader object once I have it.

3个回答

91

当我运行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)
    
  4. 所有测试用例方法定义必须以test_开头。

  5.  def test_data_format(self):
    

有没有一种方法可以在unittest发现中添加引导脚本? - 101010
3
同时也包括方法名称,例如 test_does_something(self): - Darrell Mozingo
6
对我而言,创建tests/__init__.py可以解决这个问题。 - gzc

60

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

对于 Python 2:

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

对于Python 3:

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

运行上述代码将在标准输出中打印测试结果。


12
这是我在寻找的答案,也是对原问题最直接的回答。不过在2.7中稍有不同:test_loader = unittest.defaultTestLoader.discover( '.' ),然后 test_runner = unittest.TextTestRunner(),最后运行 test_runner.run(test_loader) 即可。 - Paul
4
如果你需要通过自定义脚本或Command实例编程地调用测试运行器,这是推荐的方法。 - Filip Dupanović

27

考虑到您试图在Python < 2.7的命令行中使用unittest2,我认为您可能错过了unittest2 PyPI页面上的注意事项

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中“将包运行为主要脚本”的替代方法。如果您更喜欢这样做,它的源代码也可能对于发现和运行您自己代码中的测试非常有用。


谢谢Alex!我错过了那个注释。现在它可以工作了。你用过nose吗?你推荐它吗?顺便说一句,好书,感谢你写了它们。 - Aaron
@Aaron,不客气!是的,我过去很高兴地使用了nose(我还不知道我是否会用新的unittest功能“替换”或“补充”它 - 我对后者还不是很熟悉!)。 - Alex Martelli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接