4 # Copyright (c) 2018 Peter Wu <peter@lekensteyn.nl>
6 # SPDX-License-Identifier: GPL-2.0-or-later
8 '''Helpers for matching test results.'''
12 class MatchAny(object):
13 '''Matches any other value.'''
15 def __init__(self
, type=None):
18 def __eq__(self
, other
):
19 return self
.type is None or self
.type == type(other
)
22 return '<MatchAny type=%s>' % (self
.type.__name
__,)
25 class MatchObject(object):
26 '''Matches all expected fields of an object, ignoring excess others.'''
28 def __init__(self
, fields
):
31 def __eq__(self
, other
):
32 return all(other
.get(k
) == v
for k
, v
in self
.fields
.items())
35 return '<MatchObject fields=%r>' % (self
.fields
,)
38 class MatchList(object):
39 '''Matches elements of a list. Optionally checks list length.'''
41 def __init__(self
, item
, n
=None, match_element
=all
):
44 self
.match_element
= match_element
46 def __eq__(self
, other
):
47 if self
.n
is not None and len(other
) != self
.n
:
49 return self
.match_element(self
.item
== elm
for elm
in other
)
52 return '<MatchList item=%r n=%r match_element=%s>' % \
53 (self
.item
, self
.n
, self
.match_element
.__name
__)
56 class MatchRegExp(object):
57 '''Matches a string against a regular expression.'''
59 def __init__(self
, pattern
):
60 self
.pattern
= pattern
62 def __eq__(self
, other
):
63 return type(other
) == str and re
.match(self
.pattern
, other
)
66 return '<MatchRegExp pattern=%r>' % (self
.pattern
)