Debian Codegraph @

test/test_cbor.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 from test import NativeResourceTest
5 from awscrt.cbor import *
6 import json
7 import struct
8 import os
9 import datetime
10
11
12 class TestCBOR(NativeResourceTest):
13 def test_cbor_encode_decode_int(self):
14 encoder = AwsCborEncoder()
15 try:
16 # pass float instead of int
17 encoder.write_int(1.1)
18 except TypeError as e:
19 self.assertIsNotNone(e)
20 else:
21 self.assertTrue(False)
22
23 val_to_write = [-100, 100, 2**64 - 1, -2**64]
24 for val in val_to_write:
25 encoder.write_int(val)
26
27 decoder = AwsCborDecoder(encoder.get_encoded_data())
28 try:
29 # The first val is a negative val.
30 val = decoder.pop_next_unsigned_int()
31 except RuntimeError as e:
32 self.assertIsNotNone(e)
33 else:
34 self.assertTrue(False)
35
36 for val in val_to_write:
37 t = decoder.pop_next_data_item()
38 self.assertEqual(t, val)
39
40 self.assertEqual(decoder.get_remaining_bytes_len(), 0)
41
42 def test_cbor_encode_decode_data_item(self):
43 encoder = AwsCborEncoder()
44 numerics = [-100.12, 100.0, -100, 100, 2**64 - 1, -2**64, 18446744073709551616.0]
45 another_map = {
46 # "bignum": 2**65, # TODO: big number are not supported from C impl yet.
47 # "negative bignum": -2**75,
48 2**6: [1, 2, 3],
49 -2**6: [1, ["2", b"3"], {"most complicated": numerics}, 2**6, -2**7]
50 }
51 val_to_write = {
52 "mytest": b"write_test",
53 b"test_more": another_map,
54 2: {
55 2.3: ["a", "b", "c"]
56 },
57 "empty map": {},
58 "empty array": [],
59 "True": True,
60 "False": False,
61 "empty str": "",
62 "empty bytes": b"",
63 }
64 encoder.write_data_item(val_to_write)
65
66 decoder = AwsCborDecoder(encoder.get_encoded_data())
67
68 # Temp val only for easier to debug.
69 t = decoder.pop_next_data_item()
70 self.assertEqual(val_to_write, t)
71
72 def test_cbor_encode_decode_indef(self):
73 encoder = AwsCborEncoder()
74 numerics = [-100.12, 100.0, -100, 100, 2**64 - 1, -2**64, 18446744073709551616.0]
75 another_map = {
76 2**6: [1, 2, 3],
77 -2**6: [1, ["2", b"3"], {"most complicated": numerics}, 2**6, -2**7]
78 }
79 encoder.write_indef_array_start()
80 for i in numerics:
81 encoder.write_data_item(i)
82 encoder.write_break()
83
84 encoder.write_indef_map_start()
85 for key in another_map:
86 encoder.write_data_item(key)
87 encoder.write_data_item(another_map[key])
88 encoder.write_break()
89
90 text1 = "test"
91 text2 = "text"
92 encoder.write_indef_text_start()
93 encoder.write_text(text1)
94 encoder.write_text(text2)
95 encoder.write_break()
96
97 bytes1 = b"test"
98 bytes2 = b"bytes"
99 encoder.write_indef_bytes_start()
100 encoder.write_bytes(bytes1)
101 encoder.write_bytes(bytes2)
102 encoder.write_break()
103
104 decoder = AwsCborDecoder(encoder.get_encoded_data())
105 # Temp val only for easier to debug.
106 t = decoder.pop_next_data_item()
107 self.assertEqual(numerics, t)
108 t = decoder.pop_next_data_item()
109 self.assertEqual(another_map, t)
110 t = decoder.pop_next_data_item()
111 self.assertEqual(text1 + text2, t)
112 t = decoder.pop_next_data_item()
113 self.assertEqual(bytes1 + bytes2, t)
114 self.assertEqual(0, decoder.get_remaining_bytes_len())
115
116 def test_cbor_encode_decode_epoch_time(self):
117 time_stamp_secs = 100.1 # some random time
118
119 encoder = AwsCborEncoder()
120 encoder.write_tag(1) # tag time
121 encoder.write_float(time_stamp_secs)
122
123 def on_epoch_time(epoch_secs):
124 return datetime.datetime.fromtimestamp(epoch_secs)
125
126 # without the handler for epoch time, it just return the numeric.
127 decoder = AwsCborDecoder(encoder.get_encoded_data())
128 t = decoder.pop_next_data_item()
129 self.assertEqual(time_stamp_secs, t)
130
131 # add handler
132 decoder = AwsCborDecoder(encoder.get_encoded_data(), on_epoch_time)
133 t = decoder.pop_next_data_item()
134 self.assertEqual(datetime.datetime.fromtimestamp(time_stamp_secs), t)
135
136 def test_cbor_encode_decode_unexpected_tag(self):
137 time_stamp_secs = 100.1 # some random time
138
139 encoder = AwsCborEncoder()
140 encoder.write_tag(0) # tag time
141 encoder.write_float(time_stamp_secs)
142
143 def on_epoch_time(epoch_secs):
144 return datetime.datetime.fromtimestamp(epoch_secs)
145 # add handler
146 decoder = AwsCborDecoder(encoder.get_encoded_data(), on_epoch_time)
147 exception = None
148 try:
149 t = decoder.pop_next_data_item()
150 except Exception as e:
151 exception = e
152 self.assertIsNotNone(exception)
153
154 def _ieee754_bits_to_float(self, bits):
155 return struct.unpack('>f', struct.pack('>I', bits))[0]
156
157 def _ieee754_bits_to_double(self, bits):
158 return struct.unpack('>d', struct.pack('>Q', bits))[0]
159
160 def _convert_expect(self, expect):
161 if isinstance(expect, dict):
162 if 'uint' in expect:
163 return expect['uint']
164 elif 'negint' in expect:
165 return expect['negint']
166 elif 'bool' in expect:
167 return expect['bool']
168 elif 'float32' in expect:
169 return self._ieee754_bits_to_float(expect['float32'])
170 elif 'float64' in expect:
171 return self._ieee754_bits_to_double(expect['float64'])
172 elif 'null' in expect:
173 return None
174 elif 'bytestring' in expect:
175 return bytes(expect['bytestring'])
176 elif 'string' in expect:
177 return expect['string']
178 elif 'list' in expect:
179 return [self._convert_expect(item) for item in expect['list']]
180 elif 'map' in expect:
181 return {k: self._convert_expect(v) for k, v in expect['map'].items()}
182 return expect
183
184 def test_cbor_decode_success(self):
185 """Test CBOR decoding using test cases from JSON file"""
186 current_dir = os.path.dirname(os.path.abspath(__file__))
187 test_file = os.path.join(current_dir, 'resources', 'decode-success-tests.json')
188 with open(test_file, 'r') as f:
189 test_cases = json.load(f)
190
191 for case in test_cases:
192 description = case.get("description", "No description")
193 input_hex = case.get("input")
194 expected = self._convert_expect(case.get("expect"))
195
196 with self.subTest(description=description):
197 # Convert hex input to bytes
198 try:
199 bytes_input = bytes.fromhex(input_hex)
200 except ValueError as e:
201 self.fail(f"Failed to convert hex input: {e}")
202
203 # Decode the CBOR data
204 try:
205 decoder = AwsCborDecoder(bytes_input)
206 type = decoder.peek_next_type()
207 if type == AwsCborType.Tag:
208 # TODO: we don't support parse the tag to python type yet.
209 # hard code the tag cases to the expected format.
210 tag_id = decoder.pop_next_tag_val()
211 if tag_id == 0:
212 tag_value_type = "string"
213 else:
214 tag_value_type = "uint"
215 tag_data = decoder.pop_next_data_item()
216 decoded_data = {
217 "tag": {
218 "id": tag_id,
219 "value": {
220 tag_value_type: tag_data
221 }
222 }
223 }
224 else:
225 decoded_data = decoder.pop_next_data_item()
226
227 self.assertEqual(
228 decoded_data,
229 expected,
230 f"Failed case '{description}'\nDecoded: {decoded_data}\nExpected: {expected}"
231 )
232 except Exception as e:
233 self.fail(f"Failed to decode CBOR data: {e}")
234
235 def test_cbor_decode_errors(self):
236 """Test CBOR decoding error cases from JSON file"""
237 current_dir = os.path.dirname(os.path.abspath(__file__))
238 test_file = os.path.join(current_dir, 'resources', 'decode-error-tests.json')
239
240 with open(test_file, 'r') as f:
241 test_cases = json.load(f)
242
243 for case in test_cases:
244 description = case.get("description", "No description")
245 input_hex = case.get("input")
246
247 with self.subTest(description=description):
248 # Convert hex input to bytes
249 try:
250 bytes_input = bytes.fromhex(input_hex)
251 except ValueError as e:
252 self.fail(f"Failed to convert hex input: {e}")
253
254 # Decode the CBOR data - should raise an exception
255 decoder = AwsCborDecoder(bytes_input)
256
257 with self.assertRaises(RuntimeError):
258 type = decoder.peek_next_type()
259 if type == AwsCborType.Tag:
260 tag_id = decoder.pop_next_tag_val()
261 tag_data = decoder.pop_next_data_item()
262 else:
263 decoded_data = decoder.pop_next_data_item()