本文介绍了为什么 unittest 中的断言使用 TestCase.assertEqual 而不是 assert 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 的内置 unittest 模块使用 TestCase.assert* 方法进行断言:

Python's built-in unittest module makes assertions with TestCase.assert* methods:

class FooTest(TestCase):
    def test_foo(self):
        self.assertEqual(1,1)
        self.assertNotEqual(1,2)
        self.assertTrue(True)

我通常使用诸如 nosepy.test 允许使用内置的 assert 进行断言时的关键字:

I have generally used a testrunner such as nose or py.test which allow use of the built-in assert keyword when making assertions:

assert 1 == 1
assert 1 != 2
assert True

unittest 的 TestCase.assert* 方法的动机是什么?这种方法与使用内置 assert 关键字进行断言的优缺点是什么?是否有理由偏向于 unittest 的语法?

What is the motivation for unittest's TestCase.assert* approach and what are the strengths and weaknesses of this vs asserting with the built-in assert keyword? Are there reasons why unittest's syntax should be favoured?

推荐答案

assert 关键字的问题在于它被优化了,因此 忽略,当 Python在优化"模式下运行(使用 -O 参数或 PYTHONOPTIMIZE 环境变量集.)如果测试使用 assert 那么使用 -O 进行测试是不可能的.

The problem with the assert keyword is that it is optimized out, and thus ignored, when Python is run in 'optimized' mode (with the -O argument or with the PYTHONOPTIMIZE environment variable set.) If tests were to use assert then testing with -O would be impossible.

此外,断言方法的使用使得报告实际涉及的值变得微不足道,而不必深入研究堆栈和来源并找出它们应该是什么(我相信这是nosepy.test 用于此的技术.)

Additionally, the use of the assert methods makes it trivial to report about what the values involved actually were, without having to dig into the stack and the source and figure out what they were supposed to be (which, I believe, is the technique nose and py.test use for this.)

这篇关于为什么 unittest 中的断言使用 TestCase.assertEqual 而不是 assert 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 11:18