python - 在 python 中使用装饰器跳过单元测试

标签 python unit-testing python-3.x

我正在编写一些 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/

相关文章:

python - 在 Mac 上找不到 openssl/aes.h' 文件

python - 如何从数据框中绘制条形图,其中x轴是列名称,图例是索引?

unit-testing - 在单元测试中评估多个断言 - 不要在第一个失败的断言处停止

unit-testing - 请解释我们应该如何测试 Julia 库以及为什么两个中断之一

python - 在python中排列字符图

python-3.x - 如何获取运算符类型并将公式应用到 pandas 数据框中

python - 使用 GroupBy 将两个数据帧合并到一个组中

python - 如何将 MultiIndex 转换为字符串类型

angularjs - Jasmine spyOn 函数不是对象的方法

python - 为什么我收到 Kivy KeyError : with my code?