The Problem:
We've been using nose test runner for quite a while.
From time to time, I see our tests having eq_() calls:
eq_(actual, expected)
instead of the common:
self.assertEqual(actual, expected)
The question:
Is there any benefit of using nose.tools.eq_ as opposed to the standard unittest framework's assertEqual()? Are they actually equivalent?
Thoughts:
Well, for one, eq_ is shorter, but it has to be imported from nose.tools which makes the tests dependent on the test runner library which can make it more difficult to switch to a different test runner, say py.test. On the other hand, we are also using @istest, @nottest and @attr nose decorators a lot.
They aren't equivalent to unittest.TestCase.assertEqual.
nose.tools.ok_(expr, msg=None)Shorthand for
assert. Saves 3 whole characters!
nose.tools.eq_(a, b, msg=None)Shorthand for
assert a == b, "%r != %r" % (a, b)
https://nose.readthedocs.org/en/latest/testing_tools.html#nose.tools.ok_
These docs are however slightly misleading. If you check the source you'll see eq_ actually is:
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
This is pretty close to the base case of 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
However, as hinted by the docstring and function name, assertEqual has the potential of being type-specific. This is something you lose with eq_ (or assert a == b, for that matter). unittest.TestCase has special cases for dicts, lists, tuples, sets, frozensets and strs. These mostly seem to facilitate prettier printing of error messages.
But assertEqual is a class member of TestCase, so it can only be used in TestCases. nose.tools.eq_ can be used wherever, like a simple assert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With