Debian Codegraph @

modules/ta_update/ta_update.unmanagedkey.test.integr/rfc5011/pydnstest/matchpart.py

raw
1 """matchpart is used to compare two DNS messages using a single criterion"""
2
3 from typing import ( # noqa
4 Any, Hashable, Sequence, Tuple, Union)
5
6 import dns.edns
7 import dns.rcode
8 import dns.set
9
10 MismatchValue = Union[str, Sequence[Any]]
11
12
13 class DataMismatch(Exception):
14 def __init__(self, exp_val, got_val):
15 super().__init__()
16 self.exp_val = exp_val
17 self.got_val = got_val
18
19 @staticmethod
20 def format_value(value: MismatchValue) -> str:
21 if isinstance(value, list):
22 return ' '.join([str(val) for val in value])
23 else:
24 return str(value)
25
26 def __str__(self) -> str:
27 return (
28 f'expected "{self.format_value(self.exp_val)}" '
29 f'got "{self.format_value(self.got_val)}"'
30 )
31
32 def __eq__(self, other):
33 return (isinstance(other, DataMismatch)
34 and self.exp_val == other.exp_val
35 and self.got_val == other.got_val)
36
37 def __ne__(self, other):
38 return not self.__eq__(other)
39
40 @property
41 def key(self) -> Tuple[Hashable, Hashable]:
42 def make_hashable(value):
43 if isinstance(value, (list, dns.set.Set)):
44 value = (make_hashable(item) for item in value)
45 value = tuple(value)
46 return value
47
48 return (make_hashable(self.exp_val), make_hashable(self.got_val))
49
50 def __hash__(self) -> int:
51 return hash(self.key)
52
53
54 def compare_val(exp, got):
55 """Compare arbitraty objects, throw exception if different. """
56 if exp != got:
57 raise DataMismatch(exp, got)
58 return True
59
60
61 def compare_rrs(expected, got):
62 """ Compare lists of RR sets, throw exception if different. """
63 for rr in expected:
64 if rr not in got:
65 raise DataMismatch(expected, got)
66 for rr in got:
67 if rr not in expected:
68 raise DataMismatch(expected, got)
69 if len(expected) != len(got):
70 raise DataMismatch(expected, got)
71 return True
72
73
74 def compare_rrs_types(exp_val, got_val, skip_rrsigs):
75 """sets of RR types in both sections must match"""
76 def rr_ordering_key(rrset):
77 if rrset.covers:
78 return rrset.covers, 1 # RRSIGs go to the end of RRtype list
79 else:
80 return rrset.rdtype, 0
81
82 def key_to_text(rrtype, rrsig):
83 if not rrsig:
84 return dns.rdatatype.to_text(rrtype)
85 else:
86 return f'RRSIG({dns.rdatatype.to_text(rrtype)})'
87
88 if skip_rrsigs:
89 exp_val = (rrset for rrset in exp_val
90 if rrset.rdtype != dns.rdatatype.RRSIG)
91 got_val = (rrset for rrset in got_val
92 if rrset.rdtype != dns.rdatatype.RRSIG)
93
94 exp_types = frozenset(rr_ordering_key(rrset) for rrset in exp_val)
95 got_types = frozenset(rr_ordering_key(rrset) for rrset in got_val)
96 if exp_types != got_types:
97 exp_types = tuple(key_to_text(*i) for i in sorted(exp_types))
98 got_types = tuple(key_to_text(*i) for i in sorted(got_types))
99 raise DataMismatch(exp_types, got_types)
100
101
102 def check_question(question):
103 if len(question) > 2:
104 raise NotImplementedError("More than one record in QUESTION SECTION.")
105
106
107 def match_opcode(exp, got):
108 return compare_val(exp.opcode(),
109 got.opcode())
110
111
112 def match_qtype(exp, got):
113 check_question(exp.question)
114 check_question(got.question)
115 if not exp.question and not got.question:
116 return True
117 if not exp.question:
118 raise DataMismatch("<empty question>", got.question[0].rdtype)
119 if not got.question:
120 raise DataMismatch(exp.question[0].rdtype, "<empty question>")
121 return compare_val(exp.question[0].rdtype,
122 got.question[0].rdtype)
123
124
125 def match_qname(exp, got):
126 check_question(exp.question)
127 check_question(got.question)
128 if not exp.question and not got.question:
129 return True
130 if not exp.question:
131 raise DataMismatch("<empty question>", got.question[0].name)
132 if not got.question:
133 raise DataMismatch(exp.question[0].name, "<empty question>")
134 return compare_val(exp.question[0].name,
135 got.question[0].name)
136
137
138 def match_qcase(exp, got):
139 check_question(exp.question)
140 check_question(got.question)
141 if not exp.question and not got.question:
142 return True
143 if not exp.question:
144 raise DataMismatch("<empty question>", got.question[0].name.labels)
145 if not got.question:
146 raise DataMismatch(exp.question[0].name.labels, "<empty question>")
147 return compare_val(exp.question[0].name.labels,
148 got.question[0].name.labels)
149
150
151 def match_subdomain(exp, got):
152 if not exp.question:
153 return True
154 if got.question:
155 qname = got.question[0].name
156 else:
157 qname = dns.name.root
158 if exp.question[0].name.is_superdomain(qname):
159 return True
160 raise DataMismatch(exp, got)
161
162
163 def match_flags(exp, got):
164 return compare_val(dns.flags.to_text(exp.flags),
165 dns.flags.to_text(got.flags))
166
167
168 def match_rcode(exp, got):
169 return compare_val(dns.rcode.to_text(exp.rcode()),
170 dns.rcode.to_text(got.rcode()))
171
172
173 def match_answer(exp, got):
174 return compare_rrs(exp.answer,
175 got.answer)
176
177
178 def match_answertypes(exp, got):
179 return compare_rrs_types(exp.answer,
180 got.answer, skip_rrsigs=True)
181
182
183 def match_answerrrsigs(exp, got):
184 return compare_rrs_types(exp.answer,
185 got.answer, skip_rrsigs=False)
186
187
188 def match_authority(exp, got):
189 return compare_rrs(exp.authority,
190 got.authority)
191
192
193 def match_additional(exp, got):
194 return compare_rrs(exp.additional,
195 got.additional)
196
197
198 def match_edns(exp, got):
199 if got.edns != exp.edns:
200 raise DataMismatch(exp.edns,
201 got.edns)
202 if got.payload != exp.payload:
203 raise DataMismatch(exp.payload,
204 got.payload)
205
206
207 def match_nsid(exp, got):
208 nsid_opt = None
209 for opt in exp.options:
210 if opt.otype == dns.edns.NSID:
211 nsid_opt = opt
212 break
213 # Find matching NSID
214 for opt in got.options:
215 if opt.otype == dns.edns.NSID:
216 if not nsid_opt:
217 raise DataMismatch(None, opt.data)
218 if opt == nsid_opt:
219 return True
220 else:
221 raise DataMismatch(nsid_opt.data, opt.data)
222 if nsid_opt:
223 raise DataMismatch(nsid_opt.data, None)
224 return True
225
226
227 MATCH = {"opcode": match_opcode, "qtype": match_qtype, "qname": match_qname, "qcase": match_qcase,
228 "subdomain": match_subdomain, "flags": match_flags, "rcode": match_rcode,
229 "answer": match_answer, "answertypes": match_answertypes,
230 "answerrrsigs": match_answerrrsigs, "authority": match_authority,
231 "additional": match_additional, "edns": match_edns,
232 "nsid": match_nsid}
233
234
235 def match_part(exp, got, code):
236 try:
237 return MATCH[code](exp, got)
238 except KeyError as ex:
239 raise NotImplementedError(f'unknown match request "{code}"') from ex