【问题标题】:Python 2.7 PyHamcrest 1.8.5 Matchers with unicode symbolsPython 2.7 PyHamcrest 1.8.5 带有 unicode 符号的匹配器
【发布时间】:2016-04-26 11:23:01
【问题描述】:

我试图为标准 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'❤'))

有没有更好的方法在不创建自定义匹配器的情况下做到这一点?

【问题讨论】:

    标签: python python-2.7 unicode hamcrest


    【解决方案1】:

    在需要时通过使用包装类解决它:

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

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 2016-12-24
      • 2013-03-02
      • 2017-01-24
      相关资源
      最近更新 更多