Unit tests for ASTERIX I048
[metze/wireshark/wip.git] / test / matchers.py
1 #
2 # -*- coding: utf-8 -*-
3 # Wireshark tests
4 #
5 # Copyright (c) 2018 Peter Wu <peter@lekensteyn.nl>
6 #
7 # SPDX-License-Identifier: GPL-2.0-or-later
8 #
9 '''Helpers for matching test results.'''
10
11 import re
12
13 class MatchAny(object):
14     '''Matches any other value.'''
15
16     def __init__(self, type=None):
17         self.type = type
18
19     def __eq__(self, other):
20         return self.type is None or self.type == type(other)
21
22     def __repr__(self):
23         return '<MatchAny type=%s>' % (self.type.__name__,)
24
25
26 class MatchObject(object):
27     '''Matches all expected fields of an object, ignoring excess others.'''
28
29     def __init__(self, fields):
30         self.fields = fields
31
32     def __eq__(self, other):
33         return all(other.get(k) == v for k, v in self.fields.items())
34
35     def __repr__(self):
36         return '<MatchObject fields=%r>' % (self.fields,)
37
38
39 class MatchList(object):
40     '''Matches elements of a list. Optionally checks list length.'''
41
42     def __init__(self, item, n=None, match_element=all):
43         self.item = item
44         self.n = n
45         self.match_element = match_element
46
47     def __eq__(self, other):
48         if self.n is not None and len(other) != self.n:
49             return False
50         return self.match_element(self.item == elm for elm in other)
51
52     def __repr__(self):
53         return '<MatchList item=%r n=%r match_element=%s>' % \
54                 (self.item, self.n, self.match_element.__name__)
55
56
57 class MatchRegExp(object):
58     '''Matches a string against a regular expression.'''
59
60     def __init__(self, pattern):
61         self.pattern = pattern
62
63     def __eq__(self, other):
64         return type(other) == str and re.match(self.pattern, other)
65
66     def __repr__(self):
67         return '<MatchRegExp pattern=%r>' % (self.pattern)