python - 定时 Nose 测试未正确失败

标签 python unit-testing nose

我有以下测试,在运行特别长的 fib 断言时不会失败。

未正确失败的测试

#!/usr/env/bin python2.7

import unittest
from fib import fib
from nose.tools import timed


def test_gen(expected, actual):
    @timed(.001)
    def test_method(self):
        return self.assertEqual(expected, actual)
    return test_method

if __name__ == '__main__':
    all_cases = {
        'user': ((fib(40), 102334155), (fib(2), 1), (fib(5), 5)),
    }
    fails = {}
    for username, cases in all_cases.items():
        class FibTests(unittest.TestCase):
            pass

        for index, case in enumerate(cases):
            test_name = 'test_{0}_{1}'.format(username, index)
            test = test_gen(case[1], case[0])
            setattr(FibTests, test_name, test)

        suite = unittest.TestLoader().loadTestsFromTestCase(FibTests)
        result = unittest.TextTestRunner(verbosity=2).run(suite)
        fails[username] = len(result.failures)
    print fails

(慢)Fib.py 实现

def fib(x):
    if x == 0:
        return 0
    elif x == 1:
        return 1

    return fib(x - 2) + fib(x - 1)

正确失败的测试

import unittest
from fib import fib
from nose.tools import timed


def test_gen(expected, actual):
    @timed(.001)
    def test_method(self):
        time.sleep(.2)
        return self.assertEqual(expected, actual)
    return test_method

最佳答案

您计时错误,并且从未真正调用您的测试方法。您还需要付出巨大的努力来动态创建案例并将其添加到您的类中,该类什么都不做,只是当 Nose 支持生成器测试用例时充当测试容器,这比您拥有的更容易阅读和遵循这里。另外,这是一个测试文件还是一段产品代码?如果它是一个测试文件,那么将所有代码放在 if __name__ == '__main__' 中有点奇怪,如果它是一个产品代码文件,那么将 test_gen code> 函数以及非常规运行部分中的 unittestnose import 语句没有多大意义。我建议按照以下方式进行操作,而不是尝试使测试脚本可自行运行;只需用 Nose 发射即可。

from fib import fib
from nose.tools import timed

fib = timed(.001)(fib)

def execute(username, fib_arg, expected_output):
    result = fib(fib_arg)
    assert result == expected_output, ('%s fib(%d) got %d, expected %d'
                                       % (username, fib_arg, result, expected_output))

def test_fib():
    for name, datasets in (('user', ((40, 102334155), (2, 1), (5, 5))),):
        for arg, expected in datasets:
            yield execute, name, arg, expected

关于python - 定时 Nose 测试未正确失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14389154/

相关文章:

python - 限制Unity ML-Agents/Tensorflow中的 Action 值

java - TestNG 有条件地运行测试多次

unit-testing - tensorflow Nose 测试: lots of debugging output,如何禁用

python - 在 PyDev 中使用 nosetests 进行交互式调试

python 与 R 作用域

python - 将现有的 python 项目导入到 XCode

c# - 尝试从资源字典访问图像资源时多个 NUnit 测试类失败

Python:在覆盖范围内运行 Nose 测试时出现断言错误

python - 如何使用额外方法扩展 SQLAlchemy 绑定(bind)声明模型?

python - 修补作为另一个类的属性的类实例属性