2 # -*- coding: utf-8 -*-
5 # Copyright (c) 2018 Peter Wu <peter@lekensteyn.nl>
7 # SPDX-License-Identifier: GPL-2.0-or-later
9 '''Helpers for matching test results.'''
13 class MatchAny(object):
14 '''Matches any other value.'''
16 def __init__(self, type=None):
19 def __eq__(self, other):
20 return self.type is None or self.type == type(other)
23 return '<MatchAny type=%s>' % (self.type.__name__,)
26 class MatchObject(object):
27 '''Matches all expected fields of an object, ignoring excess others.'''
29 def __init__(self, fields):
32 def __eq__(self, other):
33 return all(other.get(k) == v for k, v in self.fields.items())
36 return '<MatchObject fields=%r>' % (self.fields,)
39 class MatchList(object):
40 '''Matches elements of a list. Optionally checks list length.'''
42 def __init__(self, item, n=None, match_element=all):
45 self.match_element = match_element
47 def __eq__(self, other):
48 if self.n is not None and len(other) != self.n:
50 return self.match_element(self.item == elm for elm in other)
53 return '<MatchList item=%r n=%r match_element=%s>' % \
54 (self.item, self.n, self.match_element.__name__)
57 class MatchRegExp(object):
58 '''Matches a string against a regular expression.'''
60 def __init__(self, pattern):
61 self.pattern = pattern
63 def __eq__(self, other):
64 return type(other) == str and re.match(self.pattern, other)
67 return '<MatchRegExp pattern=%r>' % (self.pattern)