2 # Copyright 2020 The Pigweed Authors
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 # use this file except in compliance with the License. You may obtain a copy of
8 # https://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations under
15 """Tests the tokenized string decode module."""
19 import tokenized_string_decoding_test_data as tokenized_string
20 import varint_test_data
21 from pw_tokenizer import decode
24 def error(msg, value=None):
25 """Formats msg as the message for an argument that failed to parse."""
27 return '<[{}]>'.format(msg)
28 return '<[{} ({})]>'.format(msg, value)
31 class TestDecodeTokenized(unittest.TestCase):
32 """Tests decoding tokenized strings with various arguments."""
33 def test_decode_generated_data(self):
34 self.assertGreater(len(tokenized_string.TEST_DATA), 100)
36 for fmt, decoded, encoded in tokenized_string.TEST_DATA:
37 self.assertEqual(decode.decode(fmt, encoded, True), decoded)
39 def test_unicode_decode_errors(self):
40 """Tests unicode errors, which do not occur in the C++ decoding code."""
41 self.assertEqual(decode.decode('Why, %c', b'\x01', True),
42 'Why, ' + error('%c ERROR', -1))
45 decode.decode('%sXY%+ldxy%u', b'\x83N\x80!\x01\x02', True),
46 '{}XY{}xy{}'.format(error('%s ERROR', "'N\\x80!'"),
47 error('%+ld SKIPPED', -1),
48 error('%u SKIPPED', 1)))
51 decode.decode('%s%lld%9u', b'\x82$\x80\x80', True),
52 '{0}{1}{2}'.format(error("%s ERROR ('$\\x80')"),
53 error('%lld SKIPPED'), error('%9u SKIPPED')))
55 self.assertEqual(decode.decode('%c', b'\xff\xff\xff\xff\x0f', True),
56 error('%c ERROR', -2147483648))
58 def test_ignore_errors(self):
59 self.assertEqual(decode.decode('Why, %c', b'\x01'), 'Why, %c')
61 self.assertEqual(decode.decode('%s %d', b'\x01!'), '! %d')
63 def test_pointer(self):
64 """Tests pointer args, which are not natively supported in Python."""
65 self.assertEqual(decode.decode('Hello: %p', b'\x00', True),
67 self.assertEqual(decode.decode('%p%d%d', b'\x02\x80', True),
68 '0x00000001<[%d ERROR]><[%d SKIPPED]>')
71 class TestIntegerDecoding(unittest.TestCase):
72 """Test decoding variable-length integers."""
73 def test_decode_generated_data(self):
74 test_data = varint_test_data.TEST_DATA
75 self.assertGreater(len(test_data), 100)
77 for signed_spec, signed, unsigned_spec, unsigned, encoded in test_data:
80 decode.FormatSpec.from_string(signed_spec).decode(
81 bytearray(encoded)).value)
85 decode.FormatSpec.from_string(unsigned_spec).decode(
86 bytearray(encoded)).value)
89 if __name__ == '__main__':