【问题标题】:nose.tools.eq_ vs assertEqualnose.tools.eq_ vs assertEqual
【发布时间】:2015-10-22 04:57:36
【问题描述】:

问题:

我们使用nose 测试运行器已经有一段时间了。

有时,我会看到我们的测试有eq_() 调用:

eq_(actual, expected)

而不是普通:

self.assertEqual(actual, expected)

问题:

与标准单元测试框架的assertEqual() 相比,使用nose.tools.eq_ 有什么好处吗?它们实际上是等价的吗?


想法:

好吧,一方面,eq_ 更短,但它必须从 nose.tools 导入,这使得测试依赖于测试运行器库,这使得切换到不同的测试运行器变得更加困难,比如 @ 987654329@。另一方面,我们也经常使用@istest@nottest@attr 鼻子装饰器。

【问题讨论】:

    标签: python testing nose python-unittest assertion


    【解决方案1】:

    它们不等同于unittest.TestCase.assertEqual

    nose.tools.ok_(expr, msg=None)

    assert 的缩写。保存 3 个完整字符!

    nose.tools.eq_(a, b, msg=None)

    assert a == b, "%r != %r" % (a, b)的简写

    https://nose.readthedocs.org/en/latest/testing_tools.html#nose.tools.ok_

    然而,这些文档有点误导。如果您查看源代码,您会看到 eq_ 实际上是:

    def eq_(a, b, msg=None):
        if not a == b:
            raise AssertionError(msg or "%r != %r" % (a, b))
    

    https://github.com/nose-devs/nose/blob/master/nose/tools/trivial.py#L25

    这与assertEqual 的基本情况非​​常接近:

    def _baseAssertEqual(self, first, second, msg=None):
        """The default assertEqual implementation, not type specific."""
        if not first == second:
            standardMsg = '%s != %s' % _common_shorten_repr(first, second)
            msg = self._formatMessage(msg, standardMsg)
            raise self.failureException(msg)  # default: AssertionError
    

    https://github.com/python/cpython/blob/9b5ef19c937bf9414e0239f82aceb78a26915215/Lib/unittest/case.py#L805

    但是,正如文档字符串和函数名称所暗示的那样,assertEqual 有可能是特定于类型的。这是您使用eq_(或assert a == b,就此而言)失去的东西。 unittest.TestCasedicts、lists、tuples、sets、frozensets 和 strs 的特殊情况。这些似乎有助于更漂亮地打印错误消息。

    但是assertEqualTestCase的类成员,所以只能在TestCases中使用。 nose.tools.eq_ 可以在任何地方使用,例如简单的assert

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2010-10-30
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多