编程语言
首页 > 编程语言> > python-鼻子:基于TestCase的类的生成器

python-鼻子:基于TestCase的类的生成器

作者:互联网

我想为TestCase派生类的变体创建一个生成器.

我试过的是:

import unittest

def create_class(param):
    class Test(unittest.TestCase):
        def setUp(self):
            pass

        def test_fail(self):
            assert False
    return Test

def test_basic():
    for i in range(5):
        yield create_class(i)

我得到的是:

======================================================================
ERROR: test_1.test_basic
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.3/site-packages/nose/case.py", line 268, in setUp
    try_run(self.test, names)
  File "/usr/lib/python3.3/site-packages/nose/util.py", line 478, in try_run
    return func()
TypeError: setUp() missing 1 required positional argument: 'self'

屈服的实例而不是类(yield create_class(i)())使我遇到此错误:

======================================================================
ERROR: test_1.test_basic
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python3.3/site-packages/nose/case.py", line 198, in runTest
    self.test(*self.arg)
  File "/usr/lib/python3.3/unittest/case.py", line 492, in __call__
    return self.run(*args, **kwds)
  File "/usr/lib/python3.3/unittest/case.py", line 423, in run
    testMethod = getattr(self, self._testMethodName)
AttributeError: 'Test' object has no attribute 'runTest'

有任何想法吗?

解决方法:

实例化一个TestCase时,您应该传递测试的方法名称:

yield create_class(i)('test_fail')

否则,名称默认为runTest(以及您最后遇到的错误).

还要注意,测试生成器和TestCase之间存在奇怪的交互.使用以下代码:

import unittest

def create_class(param):
    class Test(unittest.TestCase):
        def setUp(self):
            pass

        def test_fail(self):
            print('executed')
            assert False
            print('after assert')

    return Test

def test_basic():
    for i in range(5):
        yield create_class(i)('test_fail')

我得到以下输出:

$nosetests -s
executed
.executed
.executed
.executed
.executed
.
----------------------------------------------------------------------
Ran 5 tests in 0.004s

OK

如您所见,即使断言有效,测试也不会失败.这可能是由于TestCase处理AssertionError而鼻子不希望处理此问题,因此它无法看到测试失败.

TestCase.run的文档中可以看出:

Run the test, collecting the result into the test result object passed as result. If result is omitted or None, a temporary result
object is created (by calling the defaultTestResult() method) and
used. The result object is not returned to run()‘s caller.

06003

因此,鼻子看不到生成器产生的对象是TestCase,应该以一种特殊的方式对其进行处理,它只是希望可调用.运行了TestCase,但是结果被放入丢失的临时对象中,这吞噬了测试内部发生的所有测试失败.因此,放弃TestCasees根本行不通.

标签:python-3-x,nose,python
来源: https://codeday.me/bug/20191031/1973663.html