Debian Codegraph @

test/common/test_base.py

raw
1 # SPDX-License-Identifier: MPL-2.0
2
3 import json
4 import unittest
5
6
7 from cryptodatahub.common.exception import InvalidValue
8
9 from cryptoparser.common.exception import NotEnoughData, TooMuchData
10 from cryptoparser.common.base import (
11 Opaque,
12 OpaqueEnumParsable,
13 OpaqueParam,
14 ProtocolVersionMajorMinorBase,
15 Serializable,
16 SerializableTextEncoder,
17 Vector,
18 VectorEnumCodeString,
19 VectorParamEnumCodeString,
20 VectorParamNumeric,
21 VectorParamParsable,
22 VectorParamString,
23 VectorParsable,
24 VectorParsableDerived,
25 VectorString,
26 )
27 from cryptoparser.common.parse import ComposerBinary
28
29 from .classes import (
30 AlwaysTestStringComposer,
31 ConditionalParsable,
32 EnumStringValue,
33 FourByteEnumComposerTest,
34 FourByteEnumParsableTest,
35 ListParsableTest,
36 NByteEnumTest,
37 NumericRangeParsableTest,
38 OneByteEnumComposerTest,
39 OneByteEnumParsableTest,
40 OneByteOddParsable,
41 OneByteParsable,
42 OpaqueEnum,
43 OpaqueEnumFactory,
44 SerializableAttributeOrder,
45 SerializableEmptyValues,
46 SerializableEnums,
47 SerializableHidden,
48 SerializableHumanFriendly,
49 SerializableHumanReadable,
50 SerializableIterables,
51 SerializableRecursive,
52 SerializableSimpleTypes,
53 SerializableSingle,
54 SerializableUnhandled,
55 SerializableUpperCaseEncoder,
56 StringEnum,
57 StringEnumA,
58 StringEnumAA,
59 StringEnumAAA,
60 TestObject,
61 ThreeByteEnumComposerTest,
62 ThreeByteEnumParsableTest,
63 TwoByteEnumComposerTest,
64 TwoByteEnumParsableTest,
65 TwoByteEvenParsable,
66 TwoByteParsable,
67 VariantParsableTest,
68 VariantParsableExactTest,
69 )
70
71
72 class TestProtocolVersionMajorMinorBase(unittest.TestCase):
73 def setUp(self):
74 self.protocol_version = ProtocolVersionMajorMinorBase(1, 2)
75 self.protocol_version_bytes = b'\x01\x02'
76
77 def test_error(self):
78 with self.assertRaises(NotEnoughData) as context_manager:
79 ProtocolVersionMajorMinorBase.parse_exact_size(b'\x00')
80 self.assertEqual(context_manager.exception.bytes_needed, 1)
81
82 def test_parse(self):
83 self.assertEqual(
84 ProtocolVersionMajorMinorBase.parse_exact_size(self.protocol_version_bytes),
85 self.protocol_version
86 )
87
88 def test_compose(self):
89 self.assertEqual(self.protocol_version.compose(), self.protocol_version_bytes)
90
91 def test_identifier(self):
92 self.assertEqual(self.protocol_version.identifier, '1_2')
93
94 def test_markdown(self):
95 self.assertEqual(self.protocol_version.as_markdown(), '1.2')
96
97 def test_str(self):
98 self.assertEqual(str(self.protocol_version), '1.2')
99
100
101 class VectorNumericTestErrors(Vector):
102 @classmethod
103 def get_param(cls):
104 return VectorParamNumeric(item_size=2, min_byte_num=4, max_byte_num=6)
105
106
107 class VectorNumericTest(Vector):
108 @classmethod
109 def get_param(cls):
110 return VectorParamNumeric(item_size=2, min_byte_num=0, max_byte_num=0xff)
111
112
113 class VectorStringTest(VectorString):
114 @classmethod
115 def get_param(cls):
116 return VectorParamString(
117 min_byte_num=0,
118 max_byte_num=16,
119 separator=';',
120 item_class=StringEnum,
121 fallback_class=str
122 )
123
124
125 class VectorOneByteParsableTest(VectorParsable):
126 @classmethod
127 def get_param(cls):
128 return VectorParamParsable(item_class=OneByteParsable, min_byte_num=0, max_byte_num=0xff, fallback_class=None)
129
130
131 class VectorTwoByteParsableTest(VectorParsable):
132 @classmethod
133 def get_param(cls):
134 return VectorParamParsable(item_class=TwoByteParsable, min_byte_num=0, max_byte_num=0xffff, fallback_class=None)
135
136
137 class VectorConsditionalParsableTest(VectorParsableDerived):
138 @classmethod
139 def get_param(cls):
140 return VectorParamParsable(
141 item_class=ConditionalParsable,
142 min_byte_num=0,
143 max_byte_num=0xff,
144 fallback_class=None
145 )
146
147
148 class VectorFallbackParsableTest(VectorParsableDerived):
149 @classmethod
150 def get_param(cls):
151 return VectorParamParsable(
152 item_class=OneByteOddParsable,
153 min_byte_num=0,
154 max_byte_num=0xff,
155 fallback_class=TwoByteEvenParsable
156 )
157
158
159 class OpaqueTest(Opaque):
160 @classmethod
161 def get_param(cls):
162 return OpaqueParam(min_byte_num=3, max_byte_num=3)
163
164
165 class TestVectorNumeric(unittest.TestCase):
166 def test_error(self):
167 with self.assertRaises(NotEnoughData) as context_manager:
168 VectorNumericTestErrors(items=[1, ])
169 self.assertEqual(context_manager.exception.bytes_needed, VectorNumericTestErrors.get_param().min_byte_num)
170
171 with self.assertRaises(TooMuchData) as context_manager:
172 VectorNumericTestErrors(items=[1, 2, 3, 4, ])
173 self.assertEqual(context_manager.exception.bytes_needed, VectorNumericTestErrors.get_param().max_byte_num)
174
175 vector = VectorNumericTestErrors(items=[1, 2, ])
176 with self.assertRaises(NotEnoughData) as context_manager:
177 del vector[0]
178 self.assertEqual(context_manager.exception.bytes_needed, VectorNumericTestErrors.get_param().min_byte_num)
179
180 vector = VectorNumericTestErrors(items=[1, 2, 3])
181 with self.assertRaises(TooMuchData) as context_manager:
182 vector.append(0xff)
183 self.assertEqual(context_manager.exception.bytes_needed, VectorNumericTestErrors.get_param().max_byte_num)
184
185 def test_parse(self):
186 self.assertEqual(len(VectorNumericTest.parse_exact_size(b'\x00')), 0)
187
188 self.assertEqual(
189 [1, 2, ],
190 list(VectorNumericTest.parse_exact_size(b'\x04\x00\x01\x00\x02'))
191 )
192
193 def test_compose(self):
194 self.assertEqual(
195 b'\x00',
196 VectorNumericTest([]).compose(),
197 )
198
199 self.assertEqual(
200 b'\x04\x00\x01\x00\x02',
201 VectorNumericTest([1, 2, ]).compose(),
202 )
203
204 def test_container(self):
205 vector = VectorNumericTest(items=[])
206
207 vector.append(1)
208 self.assertEqual(vector[0], 1)
209 self.assertEqual(len(vector), 1)
210 self.assertEqual(str(vector), '[1]')
211
212 vector.insert(0, 0)
213 self.assertEqual(vector[0], 0)
214 self.assertEqual(len(vector), 2)
215 self.assertEqual(str(vector), '[0, 1]')
216
217 del vector[0]
218 self.assertEqual(vector[0], 1)
219 self.assertEqual(len(vector), 1)
220 self.assertEqual(str(vector), '[1]')
221
222 vector[0] = 0
223 self.assertEqual(vector[0], 0)
224 self.assertEqual(len(vector), 1)
225 self.assertEqual(str(vector), '[0]')
226
227
228 class TestVectorString(unittest.TestCase):
229 def test_error(self):
230 pass
231
232 def test_parse(self):
233 self.assertEqual(len(VectorStringTest.parse_exact_size(b'\x00')), 0)
234
235 self.assertEqual(
236 [StringEnum.ONE, StringEnum.TWO, StringEnum.THREE, ],
237 list(VectorStringTest.parse_exact_size(b'\x0fone;two;three'))
238 )
239 self.assertEqual(
240 [StringEnum.ONE, StringEnum.TWO, StringEnum.THREE, 'four', ],
241 list(VectorStringTest.parse_exact_size(b'\x14one;two;three;four'))
242 )
243
244 def test_compose(self):
245 self.assertEqual(
246 b'\x00',
247 VectorStringTest([]).compose(),
248 )
249
250 self.assertEqual(
251 b'\x07one;two',
252 VectorStringTest([StringEnum.ONE, StringEnum.TWO, ]).compose(),
253 )
254
255 def test_json(self):
256 self.assertEqual('[]', VectorStringTest([]).as_json())
257
258 self.assertEqual(
259 VectorStringTest([StringEnum.ONE, StringEnum.TWO, ]).as_json(),
260 '[{"ONE": {"code": "one"}}, {"TWO": {"code": "two"}}]',
261 )
262
263 def test_markdown(self):
264 self.assertEqual('-', VectorStringTest([]).as_markdown())
265
266 self.assertEqual(
267 VectorStringTest([StringEnum.ONE, StringEnum.TWO, ]).as_markdown(),
268 '\n'.join([
269 '1. ONE',
270 '2. TWO',
271 '',
272 ])
273 )
274
275
276 class StringEnumFactory(OpaqueEnumParsable):
277 @classmethod
278 def get_enum_class(cls):
279 return StringEnum
280
281 @classmethod
282 def get_param(cls):
283 return OpaqueParam(
284 min_byte_num=1, max_byte_num=2 ** 8 - 1
285 )
286
287
288 class VectorEnumCodeStringTest(VectorEnumCodeString):
289 @classmethod
290 def get_param(cls):
291 return VectorParamEnumCodeString(
292 item_class=StringEnumFactory,
293 min_byte_num=0, max_byte_num=2 ** 16 - 1
294 )
295
296
297 class TestVectorEnumCodeString(unittest.TestCase):
298 def test_error(self):
299 pass
300
301 def test_parse(self):
302 self.assertEqual(
303 [StringEnum.ONE, StringEnum.TWO, StringEnum.THREE, ],
304 list(VectorEnumCodeStringTest.parse_exact_size(b'\x00\x0e\x03one\x03two\x05three'))
305 )
306
307 def test_compose(self):
308 self.assertEqual(
309 b'\x00\x00',
310 VectorEnumCodeStringTest([]).compose(),
311 )
312
313 self.assertEqual(
314 b'\x00\x08\x03one\x03two',
315 VectorEnumCodeStringTest([StringEnum.ONE, StringEnum.TWO, ]).compose(),
316 )
317
318 def test_json(self):
319 self.assertEqual('[]', VectorEnumCodeStringTest([]).as_json())
320
321 self.assertEqual(
322 VectorEnumCodeStringTest([StringEnum.ONE, StringEnum.TWO, ]).as_json(),
323 '[{"ONE": {"code": "one"}}, {"TWO": {"code": "two"}}]',
324 )
325
326 def test_markdown(self):
327 self.assertEqual('-', VectorEnumCodeStringTest([]).as_markdown())
328
329 self.assertEqual(
330 VectorEnumCodeStringTest([StringEnum.ONE, StringEnum.TWO, ]).as_markdown(),
331 '\n'.join([
332 '1. ONE',
333 '2. TWO',
334 '',
335 ])
336 )
337
338
339 class TestVectorParsable(unittest.TestCase):
340 def test_error(self):
341 with self.assertRaises(NotEnoughData) as context_manager:
342 VectorOneByteParsableTest.parse_exact_size(b'')
343 self.assertEqual(context_manager.exception.bytes_needed, 1)
344
345 with self.assertRaises(NotEnoughData) as context_manager:
346 VectorTwoByteParsableTest.parse_exact_size(b'\x00')
347 self.assertEqual(context_manager.exception.bytes_needed, 1)
348
349 with self.assertRaises(NotEnoughData) as context_manager:
350 VectorOneByteParsableTest.parse_exact_size(b'\x03')
351 self.assertEqual(context_manager.exception.bytes_needed, 3)
352
353 with self.assertRaises(NotEnoughData) as context_manager:
354 VectorTwoByteParsableTest.parse_exact_size(b'\x00\x03')
355 self.assertEqual(context_manager.exception.bytes_needed, 3)
356
357 def test_parse(self):
358 self.assertEqual(len(VectorOneByteParsableTest.parse_exact_size(b'\x00')), 0)
359 self.assertEqual(len(VectorTwoByteParsableTest.parse_exact_size(b'\x00\x00')), 0)
360
361 self.assertEqual(
362 [0, 1, 0, 2, ],
363 list(map(int, VectorOneByteParsableTest.parse_exact_size(b'\x04\x00\x01\x00\x02')))
364 )
365 self.assertEqual(
366 [1, 2, ],
367 list(map(int, VectorTwoByteParsableTest.parse_exact_size(b'\x00\x04\x00\x01\x00\x02')))
368 )
369
370 self.assertEqual(
371 [0x01, 0x0200],
372 list(map(int, VectorFallbackParsableTest.parse_exact_size(b'\x03\x01\x02\x00')))
373 )
374
375 def test_compose(self):
376 self.assertEqual(b'\x00', VectorOneByteParsableTest([]).compose())
377 self.assertEqual(b'\x00\x00', VectorTwoByteParsableTest([]).compose())
378
379 self.assertEqual(
380 b'\x04\x00\x01\x00\x02',
381 VectorOneByteParsableTest([
382 OneByteParsable(0),
383 OneByteParsable(1),
384 OneByteParsable(0),
385 OneByteParsable(2)
386 ]).compose(),
387 )
388 self.assertEqual(
389 b'\x00\x04\x00\x01\x00\x02',
390 VectorTwoByteParsableTest([
391 TwoByteParsable(1),
392 TwoByteParsable(2)
393 ]).compose(),
394 )
395
396 def test_container(self):
397 vector = VectorOneByteParsableTest(items=[])
398
399 vector.append(OneByteParsable(1))
400 self.assertEqual(vector[0], OneByteParsable(1))
401 self.assertNotEqual(vector[0], TwoByteParsable(1))
402 self.assertEqual(len(vector), 1)
403 self.assertEqual(str(vector), '[0x01]')
404
405 vector.insert(0, TwoByteParsable(0))
406 self.assertEqual(vector[0], TwoByteParsable(0))
407 self.assertNotEqual(vector[0], OneByteParsable(0))
408 self.assertEqual(len(vector), 2)
409 self.assertEqual(str(vector), '[0x0000, 0x01]')
410
411 del vector[0]
412 self.assertEqual(vector[0], OneByteParsable(1))
413 self.assertNotEqual(vector[0], TwoByteParsable(1))
414 self.assertEqual(len(vector), 1)
415 self.assertEqual(str(vector), '[0x01]')
416
417 vector[0] = TwoByteParsable(0)
418 self.assertEqual(vector[0], TwoByteParsable(0))
419 self.assertNotEqual(vector[0], OneByteParsable(0))
420 self.assertEqual(len(vector), 1)
421 self.assertEqual(str(vector), '[0x0000]')
422
423
424 class TestVectorDerived(unittest.TestCase):
425 def test_error(self):
426 with self.assertRaises(NotEnoughData) as context_manager:
427 VectorConsditionalParsableTest.parse_exact_size(b'\x05\x01\x02\x00')
428 self.assertEqual(context_manager.exception.bytes_needed, 2)
429
430 def test_parse(self):
431 self.assertEqual(
432 [0x01, 0x0200],
433 list(map(int, VectorConsditionalParsableTest.parse_exact_size(b'\x03\x01\x02\x00')))
434 )
435 self.assertEqual(
436 [0x0200, 0x01],
437 list(map(int, VectorConsditionalParsableTest.parse_exact_size(b'\x03\x02\x00\x01')))
438 )
439
440 def test_compose(self):
441 self.assertEqual(
442 b'\x03\x01\x00\x02',
443 VectorConsditionalParsableTest([
444 OneByteParsable(1),
445 TwoByteParsable(2),
446 ]).compose()
447 )
448 self.assertEqual(
449 b'\x03\x00\x02\x01',
450 VectorConsditionalParsableTest([
451 TwoByteParsable(2),
452 OneByteParsable(1),
453 ]).compose()
454 )
455
456
457 class TestOpaque(unittest.TestCase):
458 def test_error(self):
459 with self.assertRaises(NotEnoughData) as context_manager:
460 OpaqueTest.parse_exact_size(b'\x03\x01\x02')
461 self.assertEqual(context_manager.exception.bytes_needed, 1)
462
463 def test_parse(self):
464 self.assertEqual(
465 [1, 2, 3],
466 list(OpaqueTest.parse_exact_size(b'\x03\x01\x02\x03'))
467 )
468
469 def test_compose(self):
470 self.assertEqual(
471 b'\x03\x01\x02\x03',
472 OpaqueTest([1, 2, 3]).compose()
473 )
474 self.assertEqual(
475 b'\x03\x01\x02\x03',
476 OpaqueTest(b'\x01\x02\x03').compose()
477 )
478 self.assertEqual(
479 b'\x03\x01\x02\x03',
480 OpaqueTest(bytearray(b'\x01\x02\x03')).compose()
481 )
482
483
484 class TestOpaqueEnum(unittest.TestCase):
485 def test_error(self):
486 with self.assertRaises(InvalidValue) as context_manager:
487 OpaqueEnumFactory.parse_exact_size(b'\x0a' + 'δέλτα'.encode())
488 self.assertEqual(context_manager.exception.value, 'δέλτα')
489
490 def test_parse(self):
491 self.assertEqual(
492 OpaqueEnum.ALPHA,
493 OpaqueEnumFactory.parse_exact_size(b'\x08' + 'άλφα'.encode())
494 )
495
496 def test_compose(self):
497 self.assertEqual(
498 b'\x0a' + 'γάμμα'.encode(),
499 OpaqueEnum.GAMMA.compose() # pylint: disable=no-member
500 )
501
502 def test_repr(self):
503 self.assertEqual(
504 repr(OpaqueEnum.GAMMA),
505 'OpaqueEnum.GAMMA'
506 )
507
508
509 class TestNByteEnumParsable(unittest.TestCase):
510 def test_compose(self):
511 composer = ComposerBinary()
512 composer.compose_parsable(OneByteEnumComposerTest.ONE)
513 self.assertEqual(composer.composed_bytes, b'\x01')
514
515 composer = ComposerBinary()
516 composer.compose_parsable(TwoByteEnumComposerTest.TWO)
517 self.assertEqual(composer.composed_bytes, b'\x00\x02')
518
519 composer = ComposerBinary()
520 composer.compose_parsable(ThreeByteEnumComposerTest.THREE)
521 self.assertEqual(composer.composed_bytes, b'\x00\x00\x03')
522
523 composer = ComposerBinary()
524 composer.compose_parsable(FourByteEnumComposerTest.FOUR)
525 self.assertEqual(composer.composed_bytes, b'\x00\x00\x00\x04')
526
527 def test_parse(self):
528 self.assertEqual(
529 OneByteEnumParsableTest.parse_exact_size(b'\x01'),
530 NByteEnumTest.ONE
531 )
532 self.assertEqual(
533 TwoByteEnumParsableTest.parse_exact_size(b'\x00\x02'),
534 NByteEnumTest.TWO
535 )
536 self.assertEqual(
537 ThreeByteEnumParsableTest.parse_exact_size(b'\x00\x00\x03'),
538 NByteEnumTest.THREE
539 )
540 self.assertEqual(
541 FourByteEnumParsableTest.parse_exact_size(b'\x00\x00\x00\x04'),
542 NByteEnumTest.FOUR
543 )
544
545
546 class TestEnumString(unittest.TestCase):
547 def test_error(self):
548 with self.assertRaises(InvalidValue) as context_manager:
549 StringEnum.parse_exact_size(b'four')
550 self.assertEqual(context_manager.exception.value, b'four')
551
552 with self.assertRaises(InvalidValue) as context_manager:
553 StringEnum.parse_exact_size(b'\xffthree')
554 self.assertEqual(context_manager.exception.value, b'\xffthree')
555
556 def test_parse(self):
557 self.assertEqual(StringEnum.parse_exact_size(b'one'), StringEnum.ONE)
558
559 def test_compose(self):
560 self.assertEqual(StringEnum.ONE.compose(), b'one')
561
562
563 class TestSerializable(unittest.TestCase):
564 def test_json(self):
565 self.assertEqual(
566 SerializableSimpleTypes().as_json(),
567 '{' +
568 '"bool_value": false, ' +
569 '"bytearray_value": "00:01:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F", ' +
570 '"float_value": 1.0, ' +
571 '"int_value": 1, ' +
572 '"none_value": null, ' +
573 '"str_value": "string"' +
574 '}'
575 )
576 self.assertEqual(
577 SerializableIterables().as_json(),
578 '{' +
579 '"dict_key": ' +
580 '{' +
581 '"1": "int", ' +
582 '"str": "string", ' +
583 '"FIRST": "enum"' +
584 '}, ' +
585 '"dict_value": ' +
586 '{' +
587 '"int": 1, ' +
588 '"string": "str", ' +
589 '"enum": {"FIRST": "1"}' +
590 '}, ' +
591 '"list_value": ["value"], ' +
592 '"tuple_value": ["value"]' +
593 '}'
594 )
595 self.assertEqual(
596 SerializableEnums().as_json(),
597 '{"param_enum": {"FIRST": {"code": 1}}, "string_enum": {"SECOND": "2"}}'
598 )
599 self.assertEqual(
600 SerializableSingle().as_json(),
601 '"single"'
602 )
603 self.assertEqual(
604 SerializableHidden().as_json(),
605 '{"visible_value": "value"}'
606 )
607 self.assertEqual(
608 SerializableUnhandled().as_json(),
609 '{"complex_number": "(1+2j)"}'
610 )
611 self.assertEqual(
612 SerializableHumanFriendly().as_json(),
613 '{' +
614 '"human_friendly": "human-friendly", ' +
615 '"human_friendly_by_default": "human-friendly-by-default", ' +
616 '"non_human_friendly": "non-human-friendly"' +
617 '}'
618 )
619 self.assertEqual(
620 SerializableRecursive().as_json(),
621 '{' +
622 '"json_asdict_object": {"attr_b": "b", "attr_a": "a"}, ' +
623 '"json_attr_as_dict": {"attr_b": "b", "attr_a": "a"}, ' +
624 '"json_attr_object": {"attr_b": "b", "attr_a": "a"}, ' +
625 '"json_crypto_data_hub_enum": "ONE", ' +
626 '"json_gradeable": {"vulnerabilities": [{"attack_type": "MITM", "grade": "INSECURE", "named": "NOFS"}]}, ' +
627 '"json_object": {"attr_a": "a", "attr_b": "b"}, ' +
628 '"json_serializable_hidden": {"visible_value": "value"}, ' +
629 '"json_serializable_in_dict": {"key1": {"visible_value": "value"}, "key2": "single"}, ' +
630 '"json_serializable_in_list": [{"visible_value": "value"}, "single"], ' +
631 '"json_serializable_in_tuple": [{"visible_value": "value"}, "single"], ' +
632 '"json_serializable_single": "single"' +
633 '}'
634 )
635 self.assertEqual(json.dumps(TestObject()), '{}')
636 self.assertEqual(
637 json.dumps(EnumStringValue.ONE),
638 '{"ONE": "one"}'
639 )
640
641 def test_markdown(self):
642 self.assertEqual(
643 SerializableSimpleTypes().as_markdown(),
644 '\n'.join([
645 '* Bool Value: no',
646 '* Bytearray Value: 00:01:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F',
647 '* Float Value: 1.0',
648 '* Int Value: 1',
649 '* None Value: n/a',
650 '* Str Value: string',
651 ''
652 ])
653 )
654 self.assertEqual(
655 SerializableIterables().as_markdown(),
656 '\n'.join([
657 '* Dict Key:',
658 ' * 1: int',
659 ' * Str: string',
660 ' * FIRST: enum',
661 '* Dict Value:',
662 ' * Int: 1',
663 ' * String: str',
664 ' * Enum: FIRST',
665 '* List Value:',
666 ' 1. value',
667 '* Tuple Value:',
668 ' 1. value',
669 ''
670 ])
671 )
672 self.assertEqual(
673 SerializableEnums().as_markdown(),
674 '\n'.join([
675 '* Param Enum: 1',
676 '* String Enum: SECOND',
677 ''
678 ])
679 )
680 self.assertEqual(
681 SerializableHidden().as_markdown(),
682 '* Visible Value: value\n'
683 )
684 self.assertEqual(
685 SerializableUnhandled().as_markdown(),
686 '* Complex Number: (1+2j)\n'
687 )
688 self.assertEqual(
689 SerializableHumanReadable().as_markdown(),
690 '* Human Readable Name 2: value 2\n'
691 '* Human Readable Name 1: value 1\n'
692 )
693 self.assertEqual(
694 SerializableHumanFriendly().as_markdown(),
695 '* Human Friendly: human-friendly\n'
696 '* Human Friendly By Default: human-friendly-by-default\n'
697 )
698 self.assertEqual(
699 SerializableAttributeOrder().as_markdown(),
700 '\n'.join([
701 '* Attr B: b',
702 '* Attr A: a'
703 ]) + '\n'
704 )
705 self.assertEqual(
706 SerializableEmptyValues().as_markdown(),
707 '\n'.join([
708 '* Dict: -',
709 '* List: -',
710 '* Tuple: -',
711 '* Value: n/a',
712 '',
713 ])
714 )
715 self.assertEqual(
716 SerializableRecursive().as_markdown(),
717 '\n'.join([
718 '* Json Asdict Object:',
719 ' * Attr B: b',
720 ' * Attr A: a',
721 '* Json Attr As Dict:',
722 ' * Attr B: b',
723 ' * Attr A: a',
724 '* Json Attr Object:',
725 ' * Attr B: b',
726 ' * Attr A: a',
727 '* Json Crypto Data Hub Enum: one',
728 '* Json Gradeable: value',
729 '* Json Object:',
730 ' * Attr A: a',
731 ' * Attr B: b',
732 '* Json Serializable Hidden:',
733 ' * Visible Value: value',
734 '* Json Serializable In Dict:',
735 ' * Key1:',
736 ' * Visible Value: value',
737 ' * Key2: single',
738 '* Json Serializable In List:',
739 ' 1.',
740 ' * Visible Value: value',
741 ' 2. single',
742 '* Json Serializable In Tuple:',
743 ' 1.',
744 ' * Visible Value: value',
745 ' 2. single',
746 '* Json Serializable Single: single',
747 '',
748 ])
749 )
750
751 Serializable.post_text_encoder = SerializableUpperCaseEncoder()
752 self.assertEqual(
753 SerializableRecursive().as_markdown(),
754 '\n'.join([
755 '* Json Asdict Object:',
756 ' * Attr B: B',
757 ' * Attr A: A',
758 '* Json Attr As Dict:',
759 ' * Attr B: B',
760 ' * Attr A: A',
761 '* Json Attr Object:',
762 ' * Attr B: B',
763 ' * Attr A: A',
764 '* Json Crypto Data Hub Enum: ONE',
765 '* Json Gradeable: VALUE',
766 '* Json Object:',
767 ' * Attr A: A',
768 ' * Attr B: B',
769 '* Json Serializable Hidden:',
770 ' * Visible Value: VALUE',
771 '* Json Serializable In Dict:',
772 ' * Key1:',
773 ' * Visible Value: VALUE',
774 ' * Key2: SINGLE',
775 '* Json Serializable In List:',
776 ' 1.',
777 ' * Visible Value: VALUE',
778 ' 2. SINGLE',
779 '* Json Serializable In Tuple:',
780 ' 1.',
781 ' * Visible Value: VALUE',
782 ' 2. SINGLE',
783 '* Json Serializable Single: SINGLE',
784 '',
785 ])
786 )
787 Serializable.post_text_encoder = SerializableTextEncoder()
788
789
790 class TestListParsable(unittest.TestCase):
791 def test_error(self):
792 with self.assertRaises(NotEnoughData) as context_manager:
793 ListParsableTest.parse_exact_size(b'')
794 self.assertEqual(context_manager.exception.bytes_needed, 2)
795
796 with self.assertRaises(InvalidValue) as context_manager:
797 ListParsableTest.parse_exact_size(b'test')
798 self.assertEqual(context_manager.exception.value, b'test')
799
800 with self.assertRaises(InvalidValue) as context_manager:
801 ListParsableTest.parse_exact_size(b'nottest\r\n\r\n')
802 self.assertEqual(context_manager.exception.value, b'nottest\r\n\r\n')
803
804 with self.assertRaises(InvalidValue) as context_manager:
805 ListParsableTest.parse_exact_size(b'test\r\n\r\ntest\r\n\r\n')
806 self.assertEqual(context_manager.exception.value, b'test\r\n\r\ntest\r\n\r\n')
807
808 def test_parse(self):
809 list_parsable = ListParsableTest.parse_exact_size(b'\r\n')
810 self.assertEqual(list_parsable, ListParsableTest([]))
811
812 list_parsable = ListParsableTest.parse_exact_size(b'test\r\n\r\n')
813 self.assertEqual(list_parsable, ListParsableTest([AlwaysTestStringComposer(), ]))
814
815 list_parsable = ListParsableTest.parse_exact_size(b'test\r\ntest\r\n\r\n')
816 self.assertEqual(list_parsable, ListParsableTest([AlwaysTestStringComposer(), AlwaysTestStringComposer()]))
817
818 def test_compose(self):
819 self.assertEqual(
820 ListParsableTest([]).compose(),
821 b'\r\n'
822 )
823 self.assertEqual(
824 ListParsableTest([AlwaysTestStringComposer(), ]).compose(),
825 b'test\r\n\r\n'
826 )
827 self.assertEqual(
828 ListParsableTest([AlwaysTestStringComposer(), AlwaysTestStringComposer(), ]).compose(),
829 b'test\r\ntest\r\n\r\n'
830 )
831
832
833 class TestVariantParsable(unittest.TestCase):
834 def test_error(self):
835 with self.assertRaises(TooMuchData) as context_manager:
836 VariantParsableTest.parse_exact_size(b'aaaa')
837 self.assertEqual(context_manager.exception.bytes_needed, 1)
838
839 def test_parse(self):
840 parsable = bytearray(b'a')
841 self.assertEqual(VariantParsableTest.parse_mutable(parsable), StringEnumA.A)
842 self.assertEqual(parsable, b'')
843
844 parsable = bytearray(b'aa')
845 self.assertEqual(VariantParsableTest.parse_mutable(parsable), StringEnumA.A)
846 self.assertEqual(parsable, b'a')
847
848 parsable = bytearray(b'aaa')
849 self.assertEqual(VariantParsableTest.parse_mutable(parsable), StringEnumA.A)
850 self.assertEqual(parsable, b'aa')
851
852
853 class TestVariantParsableExact(unittest.TestCase):
854 def test_error(self):
855 with self.assertRaises(InvalidValue) as context_manager:
856 VariantParsableExactTest.parse_exact_size(b'aaaa')
857 self.assertEqual(context_manager.exception.value, b'aaaa')
858
859 def test_parse(self):
860 parsable = bytearray(b'a')
861 self.assertEqual(VariantParsableExactTest.parse_mutable(parsable), StringEnumA.A)
862 self.assertEqual(parsable, b'')
863
864 parsable = bytearray(b'aa')
865 self.assertEqual(VariantParsableExactTest.parse_mutable(parsable), StringEnumAA.AA)
866 self.assertEqual(parsable, b'')
867
868 parsable = bytearray(b'aaa')
869 self.assertEqual(VariantParsableExactTest.parse_mutable(parsable), StringEnumAAA.AAA)
870 self.assertEqual(parsable, b'')
871
872
873 class TestNumericRangeParsable(unittest.TestCase):
874 def test_error(self):
875 with self.assertRaises(InvalidValue) as context_manager:
876 NumericRangeParsableTest.parse_exact_size(b'\x00')
877 self.assertEqual(context_manager.exception.value, 0x00)
878
879 with self.assertRaises(InvalidValue) as context_manager:
880 NumericRangeParsableTest.parse_exact_size(b'\xff')
881 self.assertEqual(context_manager.exception.value, 0xff)
882
883 def test_parse(self):
884 self.assertEqual(NumericRangeParsableTest.parse_exact_size(b'\x01'), NumericRangeParsableTest(1))
885 self.assertEqual(NumericRangeParsableTest(1).compose(), b'\x01')
886
887 def test_str(self):
888 self.assertEqual(str(NumericRangeParsableTest(1)), '1')
889
890 def test_as_markdown(self):
891 self.assertEqual(NumericRangeParsableTest(1).as_markdown(), '1')