0
我有一些代码返回repr
的例外。它需要在Python 2和Python 3的Python 2&3兼容的Unicode字符串断言相等
运行代码的一个非常简单化下来的版本如下:
from __future__ import unicode_literals
class Foo:
def bar(self):
return repr(Exception('bar'))
问题是与测试上面的代码。
的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 ``'``
有没有忽略u
一种优雅的方式断言两个字符串的平等是什么时候?我正在使用unittest2。
type-cast'bar' to'str'?即'str('bar')' –
这听起来像你应该根据正在运行的Python版本不同地定义预期的结果。 – user2357112
这就是我现在拥有的。但是对于多行字符串和很多测试,这意味着很多重复,所以我正在尝试更好的解决方案。 – zupo