python - 如何从脚本中重复运行 python 单元测试并收集结果

标签 python unit-testing python-unittest

我不知道如何从 python 脚本中运行单个单元测试并收集结果。

场景:我有一组测试,用于检查生成不同对象的各种统计分布的各种方法。测试有时会失败,因为他们应该考虑到我基本上是在检查特定类型的随机性。我想从脚本甚至解释器中重复运行测试并收集结果以供进一步分析。

假设我有一个模块 myTest.py:

class myTest(unittest.TestCase):
    def setup(self):
       ...building objects, etc....
    def testTest1(self):
           ..........
    def testTest2(self):
           ..........

基本上我需要:

  1. 运行设置方法
  2. 运行 testTest1(比方说)100 次
  3. 收集失败
  4. 返回失败

我最接近的是(使用来自类似问题的代码):

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/

相关文章:

android - 如何在 JUnit(非仪器化)Android 单元测试执行的代码中使用 ArrayMap?

ruby-on-rails - 应该匹配错误:#<RSpec::ExampleGroups::Idea_3::Validations::Title:0x007f3f88fa7548> 的未定义方法 `validate_presence_of'

python - Autospec "through"带有 unittest.mock 的装饰器

python - ZeroMQ 订阅者在单元测试中不接收任何数据。为什么?

python - tkinter - 形状不统一,动画看起来很糟糕

python - 在 PYQT4 中创建和更新多个 QLabel

Python:如何从unittest模块访问测试结果变量

python - 用另一个数据框中的匹配 ID 替换 Pandas 中的单元格值

c++ - 实现一个接收和处理客户端请求的服务器(cassandra 作为后端),Python 还是 C++?

python - 如何断言 Unittest 上的可迭代对象不为空?