Rabodaber Rabodaber - 4 months ago 22
Python Question

Python 2.7 PyHamcrest 1.8.5 Matchers with unicode symbols

I was trying to get str for standard PyHamcrest matcher for loggin purposes:

from hamcrest import equal_to

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

Second print fails because matcher has a "str" call inside.
I solved it with this class:

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

print unicode(UnicodeIsEqual(u'❤'))

Is there a better way to do it without creating custom matcher?


Solved it by using wrapper class, when needed:

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