Python 2.7 PyHamcrest 1.8.5 带有 unicode 符号的匹配器
Python 2.7 PyHamcrest 1.8.5 Matchers with unicode symbols
我试图为标准 PyHamcrest 匹配器获取 str 以用于登录目的:
from hamcrest import equal_to
print str(equal_to('string'))
print unicode(equal_to(u'❤'))
第二次打印失败,因为匹配器内部有一个 "str" 调用。
我用这个 class:
解决了它
class UnicodeIsEqual(IsEqual):
def __str__(self):
return unicode(StringDescription().append_description_of(self))
print unicode(UnicodeIsEqual(u'❤'))
有没有更好的方法在不创建自定义匹配器的情况下做到这一点?
使用包装器 class 解决了问题,需要时:
class UnicodeMatcherWrapper(object):
def __init__(self, matcher):
if hasattr(matcher, 'matcher'):
matcher.matcher = UnicodeMatcherWrapper(matcher.matcher)
if hasattr(matcher, 'matchers'):
matcher.matchers = [UnicodeMatcherWrapper(nested_matcher) for nested_matcher in matcher.matchers]
self.matcher = matcher
def __getattr__(self, item):
return getattr(self.matcher, item)
def __str__(self):
return unicode(StringDescription().append_description_of(self.matcher))
我试图为标准 PyHamcrest 匹配器获取 str 以用于登录目的:
from hamcrest import equal_to
print str(equal_to('string'))
print unicode(equal_to(u'❤'))
第二次打印失败,因为匹配器内部有一个 "str" 调用。 我用这个 class:
解决了它class UnicodeIsEqual(IsEqual):
def __str__(self):
return unicode(StringDescription().append_description_of(self))
print unicode(UnicodeIsEqual(u'❤'))
有没有更好的方法在不创建自定义匹配器的情况下做到这一点?
使用包装器 class 解决了问题,需要时:
class UnicodeMatcherWrapper(object):
def __init__(self, matcher):
if hasattr(matcher, 'matcher'):
matcher.matcher = UnicodeMatcherWrapper(matcher.matcher)
if hasattr(matcher, 'matchers'):
matcher.matchers = [UnicodeMatcherWrapper(nested_matcher) for nested_matcher in matcher.matchers]
self.matcher = matcher
def __getattr__(self, item):
return getattr(self.matcher, item)
def __str__(self):
return unicode(StringDescription().append_description_of(self.matcher))