Reputation: 1556
I have some code that returns repr
's of Exceptions. It needs to run on Python 2 and Python 3.
A very dumbed-down version of the code is as follows:
from __future__ import unicode_literals
class Foo:
def bar(self):
return repr(Exception('bar'))
The problem is with testing the code above.
Python 3.5:
foo = Foo()
assert foo.bar() == "Exception('bar',)"
# true
Python 2.7:
foo = Foo()
assert foo.bar() == "Exception('bar',)"
# false because foo.bar() returns "Exception(u'bar',)",
# note the ``u`` before the first ``'``
Is there an elegant way to ignore that u
when asserting equality of two strings? I'm using unittest2.
Upvotes: 0
Views: 803
Reputation: 101969
There is no simple way to "change" the string equality. There are ways to do approximate matching, but that might allow other changes that you don't want.
The best way to solve your problem is simply changing how you define the condition for assert
. The following alternatives should work in both python2 & python3:
Create the exception you expect dynamically:
assert foo.bar() == repr(Exception(u'bar'))
Use in
and check for both alternatives:
assert foo.bar() in ("Exception('bar',)", "Exception(u'bar',)")
The latter allows the u'bar'
even in python2, which, depending on your requirements, might be fine or not.
Upvotes: 1