【发布时间】:2010-12-16 11:44:02
【问题描述】:
我有一个目录,其中包含我的 Python 单元测试。每个单元测试模块的格式为 test_*.py。我正在尝试创建一个名为 all_test.py 的文件,您猜对了,它将运行上述测试表单中的所有文件并返回结果。到目前为止,我已经尝试了两种方法;两者都失败了。我将展示这两种方法,我希望有人知道如何正确地做到这一点。
对于我的第一次勇敢尝试,我想“如果我只是在文件中导入我所有的测试模块,然后调用这个unittest.main() doodad,它会工作的,对吗?”好吧,事实证明我错了。
import glob
import unittest
testSuite = unittest.TestSuite()
test_file_strings = glob.glob('test_*.py')
module_strings = [str[0:len(str)-3] for str in test_file_strings]
if __name__ == "__main__":
unittest.main()
这不起作用,我得到的结果是:
$ python all_test.py
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
不过,对于我的第二次尝试,好吧,也许我会尝试以更“手动”的方式完成整个测试。所以我尝试在下面这样做:
import glob
import unittest
testSuite = unittest.TestSuite()
test_file_strings = glob.glob('test_*.py')
module_strings = [str[0:len(str)-3] for str in test_file_strings]
[__import__(str) for str in module_strings]
suites = [unittest.TestLoader().loadTestsFromName(str) for str in module_strings]
[testSuite.addTest(suite) for suite in suites]
print testSuite
result = unittest.TestResult()
testSuite.run(result)
print result
#Ok, at this point I have a result
#How do I display it as the normal unit test command line output?
if __name__ == "__main__":
unittest.main()
这也不起作用,但似乎如此接近!
$ python all_test.py
<unittest.TestSuite tests=[<unittest.TestSuite tests=[<unittest.TestSuite tests=[<test_main.TestMain testMethod=test_respondes_to_get>]>]>]>
<unittest.TestResult run=1 errors=0 failures=0>
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
我似乎有某种套件,我可以执行结果。我有点担心它说我只有run=1,看起来应该是run=2,但这是进步。但是如何将结果传递并显示给 main?或者我如何基本上让它工作,这样我就可以运行这个文件,然后运行这个目录中的所有单元测试?
【问题讨论】:
-
如果您使用的是 Python 2.7+,请跳至 Travis 的回答
-
您是否尝试过从测试实例对象运行测试?
-
请参阅this answer 以获取具有示例文件结构的解决方案。
标签: python unit-testing testing python-unittest