Debian Codegraph @

utils/benthos_validate.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3
4 """
5 Validator to ensure libais can produce Benthos's expected input
6 """
7
8
9 import json
10 import os
11 import unittest
12 import sys
13
14
15 # In order to ease test maintenance as outputs and inputs change the data structure below contains a test for every
16 # field, a value that will pass the test, and a value that will fail the test. All information is pulled from GPSD
17 # (http://catb.org/gpsd/AIVDM.html) and assumes two things:
18 # 1. Fieldnames are unique across all messages
19 # 2. Fields appearing in different message types contain the same information. For instance, the field 'sog'
20 # appears in multiple types but is always speed over ground in the same units in every message.
21 #
22 # Keys are fieldnames and values are dictionaries containing three keys:
23 # 1. test - a function that verifies a value is acceptable for this field
24 # 2. good - a value that will pass the test function
25 # 3. bad - a value that will not pass the test function
26 #
27 # Some fields are flags with values 0 or 1 that may be switched to Python's bool in the future but in the meantime
28 # we want to be positive these values are int's. Since bool subclasses int expressions like `0 in (1, 0)` and
29 # `True in (0, 1)` both evaluate as `True` which could yield unexpected results. Any test that expects an int
30 # also checks to make sure that int is NOT a bool, even if the field is a range and will never be bool. Better to be
31 # safe here than be forced to debug some potentially ambiguous bugs elsewhere.
32 MSG_VALIDATION_LOOKUP = {
33
34 # Comments about where fields are pulled from just reference where the description was found in the GPSD
35 # specification http://catb.org/gpsd/AIVDM.html
36 # They're not critical but if there is a discrepancy between what is expected and how the test is written
37 # it may help us figure out why.
38
39 # Pulled from types 1, 2, and 3 GPSD spec
40 'type': {
41 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(1, 28),
42 'good': 5,
43 'bad': -1
44 },
45 'repeat': {
46 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 <= x <= 2 ** 2,
47 'good': 4,
48 'bad': -1
49 },
50 'mmsi': {
51 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 30,
52 'good': '12345678902345678',
53 'bad': 1234
54 },
55 'status': {
56 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 16),
57 'good': 2,
58 'bad': -10
59 },
60 'turn': {
61 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(-127, 129),
62 'good': 125,
63 'bad': -1000
64 },
65 'sog': {
66 'test': lambda x: isinstance(x, float) and 0 <= x <= 102.2 or x == 1022,
67 'good': 1022,
68 'bad': 103
69 },
70 'accuracy': {
71 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1),
72 'good': 0,
73 'bad': 2,
74 },
75 'lat': {
76 'test': lambda x: isinstance(x, float) and -90 <= x <= 90 or x == 91,
77 'good': 91,
78 'bad': -100
79 },
80 'lon': {
81 'test': lambda x: isinstance(x, float) and -180 <= x <= 180 or x == 181, # TODO: Should -180 be a valid value? Maybe `-180 < x` instead?
82 'good': 181,
83 'bad': -180.1
84 },
85 'course': {
86 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 <= x <= 359 or x == 3600, # TODO: Should -90 be a valid value? Maybe `-90 < x` instead?
87 'good': 3600,
88 'bad': 360
89 },
90 'heading': {
91 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 <= x <= 359 or x == 511,
92 'good': 511,
93 'bad': -102
94 },
95 'second': {
96 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 64),
97 'good': 63,
98 'bad': 64
99 },
100 'maneuver': {
101 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (1, 2),
102 'good': 2,
103 'bad': 3
104 },
105 'raim': {
106 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # TODO: bool is more Pythonic if the field is actually boolean and not state
107 'good': 0,
108 'bad': -2
109 },
110 'radio': {
111 'test': lambda x: x is None, # TODO: What will this value be?
112 'good': None,
113 'bad': False
114 },
115
116 # Pulled from type 5 GPSD spec
117 'ais_version': {
118 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1, 2, 3), # TODO: Should always be 0 right now. The other vals are reserved.
119 'good': 2,
120 'bad': True
121 },
122 'imo': {
123 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 30,
124 'good': 'value',
125 'bad': True,
126 },
127 'callsign': {
128 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 42,
129 'good': 'good',
130 'bad': json
131 },
132 'shipname': {
133 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 120,
134 'good': 'good value',
135 'bad': False
136 },
137 'shiptype': {
138 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 100),
139 'good': 87,
140 'bad': str
141 },
142 'to_bow': {
143 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 <= x <= 2 ** 9,
144 'good': 1,
145 'bad': -1
146 },
147 'to_stern': {
148 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 <= x <= 2 ** 9,
149 'good': 0,
150 'bad': tuple
151 },
152 'to_port': {
153 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 <= x <= 2 ** 6,
154 'good': 1,
155 'bad': -34
156 },
157 'to_starboard': {
158 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 <= x <= 2 ** 6,
159 'good': 0,
160 'bad': False,
161 },
162 'epfd': {
163 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 9),
164 'good': 8,
165 'bad': 10
166 },
167 'month': {
168 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 13),
169 'good': 12,
170 'bad': 'asdf'
171 },
172 'day': {
173 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 32),
174 'good': 1,
175 'bad': ':'
176 },
177 'hour': {
178 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 25),
179 'good': 23,
180 'bad': ','
181 },
182 'minute': {
183 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in range(0, 61),
184 'good': 54,
185 'bad': '*'
186 },
187 'draught': {
188 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and 0 < x <= 2 ** 8,
189 'good': 1,
190 'bad': 2 ** 8 + 1
191 },
192 'destination': {
193 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 120,
194 'good': 'v',
195 'bad': 2 * 2
196 },
197 'dte': {
198 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # TODO: Switch to a more Pythonic bool if this is actually bolean and not a status
199 'good': 0,
200 'bad': 8
201 },
202
203 # Pulled from type 18 GPSD spec
204 'reserved': {
205 'test': lambda x: x is None,
206 'good': None,
207 'bad': 1
208 },
209 'regional': {
210 'test': lambda x: x is None,
211 'good': None,
212 'bad': -1
213 },
214 'speed': {
215 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x <= 2 ** 10,
216 'good': 0,
217 'bad': str
218 },
219 'cs': {
220 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # Not bool - state
221 'good': 0,
222 'bad': 7
223 },
224 'display': {
225 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # Not bool - state
226 'good': 1,
227 'bad': 'j'
228 },
229 'dsc': {
230 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # TODO: Switch to a more Pythonic bool?
231 'good': 1,
232 'bad': -45
233 },
234 'band': {
235 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # TODO: Switch to a more Pythonic bool?
236 'good': 0,
237 'bad': 4
238 },
239 'msg22': {
240 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # TODO: Switch to a more Pythonic bool?
241 'good': 0,
242 'bad': -2
243 },
244 'assigned': {
245 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # TODO: Switch to a more Pythonic bool?
246 'good': 1,
247 'bad': -33
248 },
249
250 # All type 19 are covered between 1, 2, 3, and 18
251
252 # Pulled from type 24 GPSD spec
253 'partno': {
254 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1),
255 'good': 0,
256 'bad': -1
257 },
258 'vendorid': {
259 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 18,
260 'good': 'this is a gooooooooood value',
261 'bad': int
262 },
263 'model': {
264 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 4,
265 'good': 'something',
266 'bad': 333
267 },
268 'serial': {
269 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 20,
270 'good': 'pawoeiras',
271 'bad': -1
272 },
273 'mothership_mmsi': {
274 'test': lambda x: isinstance(x, str) and len(x) <= 2 ** 30,
275 'good': 'done ... finally ...',
276 'bad': -200
277 },
278
279 # Pulled from type 27 GPSD spec
280 'gnss': {
281 'test': lambda x: isinstance(x, int) and not isinstance(x, bool) and x in (0, 1), # Not bool - state
282 'good': 0,
283 'bad': 3
284 }
285 }
286
287
288 # Keys are message types and values are lists of fields that type expects
289 MSG_TYPE_FIELDS = {
290 1: [
291 'type', 'repeat', 'mmsi', 'status', 'turn', 'sog', 'accuracy', 'lat', 'lon', 'course', 'heading', 'second',
292 'maneuver', 'raim', 'radio'
293 ],
294 2: [
295 'type', 'repeat', 'mmsi', 'status', 'turn', 'sog', 'accuracy', 'lat', 'lon', 'course', 'heading', 'second',
296 'maneuver', 'raim', 'radio'
297 ],
298 3: [
299 'type', 'repeat', 'mmsi', 'status', 'turn', 'sog', 'accuracy', 'lat', 'lon', 'course', 'heading', 'second',
300 'maneuver', 'raim', 'radio'
301 ],
302 5: [
303 'type', 'repeat', 'mmsi', 'ais_version', 'imo', 'callsign', 'shipname', 'shiptype', 'to_bow', 'to_stern',
304 'to_port', 'to_starboard', 'epfd', 'month', 'day', 'hour', 'minute', 'draught', 'destination', 'dte'
305 ],
306 18: [
307 'type', 'repeat', 'mmsi', 'reserved', 'speed', 'accuracy', 'lon', 'lat', 'course', 'heading', 'second',
308 'regional', 'cs', 'display', 'dsc', 'band', 'msg22', 'assigned', 'raim', 'radio', 'dte', 'assigned'
309 ],
310 19: [
311 'type', 'repeat', 'mmsi', 'reserved', 'speed', 'accuracy', 'lon', 'lat', 'course', 'heading', 'second',
312 'regional', 'shipname', 'shiptype', 'to_bow', 'to_stern', 'to_port', 'to_starboard', 'epfd', 'raim', 'dte',
313 'assigned'
314 ],
315 24: [
316 'type', 'repeat', 'mmsi', 'partno', 'shipname', 'shiptype', 'vendorid', 'model', 'serial', 'callsign',
317 'to_bow', 'to_stern', 'to_port', 'to_starboard', 'mothership_mmsi'
318 ],
319 27: [
320 'type', 'repeat', 'mmsi', 'accuracy', 'raim', 'status', 'lon', 'lat', 'speed', 'course', 'gnss'
321 ]
322 }
323
324
325 def validate_messages(messages, err=None):
326
327 """
328 Determine whether or not an input message conforms to the Benthos spec.
329
330 Example:
331
332 >>> import json
333 >>> with open('Messages.json') as infile:
334 ... with open('Logfile') as logfile:
335 ... print(validate_messages(
336 ... (json.loads(msg) for msg in infile), err=logfile))
337
338 Parameters
339 ----------
340 msg : iter
341 An iterable producing one AIS message as a dictionary every iteration.
342 err : file, optional
343 File-like object where errors are logged and failed messages are written.
344 A message with multiple invalid fields will have multiple errors in this
345 file.
346
347 Returns
348 -------
349 bool
350 True if every message passes
351 """
352
353 return_val = True
354
355 for msg in messages:
356
357 # Make sure the message specifies its type and that the type is one we can validate
358 if 'type' not in msg or msg['type'] not in MSG_TYPE_FIELDS:
359 if err is not None:
360 err.write("No 'type' key in msg or type is invalid or not testable: %s" % msg)
361 return_val = False
362
363 # Normal field validation
364 else:
365 msg_type = msg['type']
366 for field in MSG_TYPE_FIELDS[msg_type]:
367 if not MSG_VALIDATION_LOOKUP[field]['test'](msg[field]):
368 if err is not None:
369 sys.stdout.write("Field `%s' failed: %s" % (field, json.dumps(msg) + os.linesep))
370 return_val = False
371
372 return return_val
373
374
375 class TestValidateMessages(unittest.TestCase):
376
377 def test_all_types(self):
378 for msg_type, msg_fields in MSG_TYPE_FIELDS.items():
379
380 # Check type field individually since the other tests force it to be correct
381 assert not validate_messages([{'field': 'val'}])
382 assert not validate_messages([{'type': MSG_VALIDATION_LOOKUP['type']['bad']}])
383
384 # Construct a good message
385 good_message = {f: MSG_VALIDATION_LOOKUP[f]['good'] for f in msg_fields}
386 good_message['type'] = msg_type
387
388 assert validate_messages([good_message]), \
389 "Supposed 'good' msg failed validation: %s" % good_message
390
391 # Creating a bad message from all of the bad values is an insufficient test because the validator
392 # will start checking fields and as soon as it gets to a bad one it will flag the message as invalid.
393 # Every field is checked in every message and every bad field is logged but we can't validate individual
394 # fields without taking a good message and then changing one field at a time to a bad field.
395 for field in msg_fields:
396 if field != 'type':
397 bad_message = good_message.copy()
398 bad_message[field] = MSG_VALIDATION_LOOKUP[field]['bad']
399 assert not validate_messages([bad_message]), \
400 "Field `%s' should have caused message to fail: %s" % (field, bad_message)
401
402
403 if __name__ == '__main__':
404 if len(sys.argv) > 1 and sys.argv[1].lower() == 'test':
405 del sys.argv[1]
406 sys.exit(unittest.main())