我正在编写一些 unittest
并发现了一个相当奇怪的行为,几乎让我着急。
下面的测试:
import unittest
class Test(unittest.TestCase):
@unittest.skip('Not ready yet')
def test_A(self):
self.assertTrue(False)
@unittest.skip
def test_B(self):
self.assertTrue(False)
def test_C(self):
self.assertTrue(False)
if __name__ == '__main__':
unittest.main()
结果:
test_A (__main__.Test) ... skipped 'Not ready yet'
test_B (__main__.Test) ... ok
test_C (__main__.Test) ... FAIL
======================================================================
FAIL: test_C (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./test.py", line 13, in test_C
self.assertTrue(False)
AssertionError: False is not true
----------------------------------------------------------------------
Ran 3 tests in 0.000s
使用装饰器 unittest.skip
empty 会跳过测试,但随后报告它已通过。因此,这个跳过的测试很容易在第二天被遗忘,永远处于跳过状态。这种跳过但报告通过行为背后的原因是什么?
万一重要:
- python :3.4.3 | python 2.3.0(64 位)
- 操作系统:RHEL 6.7
最佳答案
@decorator
def f(): ...
相当于
def f(): ...
f = decorator(f)
和
@decorator(...)
def f(): ...
相当于
def f(): ...
f = decorator(...)(f)
这意味着当你忘记跳过的原因时,你得到的效果是
def test_B(self): ...
test_B = unittest.skip(test_B)
测试方法作为跳过原因传递,返回的测试装饰器赋值给test_B
。当 unittest
尝试运行 test_B
时,测试装饰器报告没有断言失败,因此 unittest
认为这是一个通过的测试。
@decorator
和@decorator()
的不等价性是 Python 的设计缺陷之一,但我们对此无能为力。
关于python - 在 python 中使用装饰器跳过单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33788785/