Python 2.7 PyHamcrest 1.8.5带有unicode符号的匹配器

2024-04-29 18:41:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为标准的PyHamcrest匹配器获取str,以便登录:

from hamcrest import equal_to

print str(equal_to('string'))
print unicode(equal_to(u'❤'))

第二次打印失败,因为matcher内部有一个“str”调用。 我用这门课解决了这个问题:

class UnicodeIsEqual(IsEqual):
    def __str__(self):
        return unicode(StringDescription().append_description_of(self))

print unicode(UnicodeIsEqual(u'❤'))

有没有更好的方法不用创建自定义匹配器?你知道吗


Tags: tofromimportself标准stringunicodematcher
1条回答
网友
1楼 · 发布于 2024-04-29 18:41:53

在需要时,通过使用包装类解决了此问题:

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))

相关问题 更多 >