我不知道如何从 python 脚本中运行单个单元测试并收集结果。
场景:我有一组测试,用于检查生成不同对象的各种统计分布的各种方法。测试有时会失败,因为他们应该考虑到我基本上是在检查特定类型的随机性。我想从脚本甚至解释器中重复运行测试并收集结果以供进一步分析。
假设我有一个模块 myTest.py:
class myTest(unittest.TestCase):
def setup(self):
...building objects, etc....
def testTest1(self):
..........
def testTest2(self):
..........
基本上我需要:
- 运行设置方法
- 运行 testTest1(比方说)100 次
- 收集失败
- 返回失败
我最接近的是(使用来自类似问题的代码):
from unittest import TextTestRunner, TestSuite
runner = TextTestRunner(verbosity = 2)
tests = ['testTest1']
suite = unittest.TestSuite(map(myTest, tests))
runner.run(suite)
但这行不通,因为:
runner.run(suite)
不运行设置方法
和
我无法捕获 testTest1 失败时抛出的异常
最佳答案
您只需将要多次运行的测试添加到套件中。
这是一个完整的代码示例。您也可以see this code running in an interactive Python console to prove that it does actually work .
import unittest
import random
class NullWriter(object):
def write(*_, **__):
pass
def flush(*_, **__):
pass
SETUP_COUNTER = 0
class MyTestCase(unittest.TestCase):
def setUp(self):
global SETUP_COUNTER
SETUP_COUNTER += 1
def test_one(self):
self.assertTrue(random.random() > 0.3)
def test_two(self):
# We just want to make sure this isn't run
self.assertTrue(False, "This should not have been run")
def suite():
tests = []
for _ in range(100):
tests.append('test_one')
return unittest.TestSuite(map(MyTestCase, tests))
results = unittest.TextTestRunner(stream=NullWriter()).run(suite())
print dir(results)
print 'setUp was run', SETUP_COUNTER, 'times'
关于python - 如何从脚本中重复运行 python 单元测试并收集结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15604382/