ale*_*cxe 10 python testing nose assertion python-unittest
问题:
我们一直在使用nose测试运行器.
我不时会看到我们的测试有eq_()电话:
eq_(actual, expected)
Run Code Online (Sandbox Code Playgroud)
而不是共同的:
self.assertEqual(actual, expected)
Run Code Online (Sandbox Code Playgroud)
问题:
nose.tools.eq_与标准的单元测试框架相比,使用是否有任何好处assertEqual()?它们实际上相当吗?
思考:
好吧,对于一个,eq_更短,但必须从中导入nose.tools,使得测试依赖于测试运行器库,这可能使得更难以切换到不同的测试运行器,比如说py.test.在另一方面,我们也用@istest,@nottest以及@attr鼻子装饰了很多.
它们不等同于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))
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
但是,正如文档字符串和函数名称暗示的那样,assertEqual具有类型特定的潜力.这是你失去的东西eq_(或者assert a == b,就此而言).unittest.TestCase有dicts,lists,tuples,sets,frozensets和strs的特殊情况.这些似乎通常有助于更好地打印错误消息.
但是assertEqual是类的成员TestCase,所以它只能用在TestCases中.nose.tools.eq_可以在任何地方使用,就像一个简单的assert.