Change script for apply upstream code
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_hdlc_lite / py / encode_test.py
1 #!/usr/bin/env python3
2 # Copyright 2020 The Pigweed Authors
3 #
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
6 # the License at
7 #
8 #     https://www.apache.org/licenses/LICENSE-2.0
9 #
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
14 # the License.
15 """Tests encoding HDLC frames."""
16
17 import unittest
18
19 from pw_hdlc_lite import encode
20 from pw_hdlc_lite import protocol
21 from pw_hdlc_lite.protocol import frame_check_sequence as _fcs
22
23 FLAG = bytes([protocol.FLAG])
24
25
26 def _with_fcs(data: bytes) -> bytes:
27     return data + _fcs(data)
28
29
30 class TestEncodeInformationFrame(unittest.TestCase):
31     """Tests Encoding bytes with different arguments using a custom serial."""
32     def test_empty(self):
33         self.assertEqual(encode.information_frame(0, b''),
34                          FLAG + _with_fcs(b'\0\0') + FLAG)
35         self.assertEqual(encode.information_frame(0x1a, b''),
36                          FLAG + _with_fcs(b'\x1a\0') + FLAG)
37
38     def test_1byte(self):
39         self.assertEqual(encode.information_frame(0, b'A'),
40                          FLAG + _with_fcs(b'\0\0A') + FLAG)
41
42     def test_multibyte(self):
43         self.assertEqual(encode.information_frame(0, b'123456789'),
44                          FLAG + _with_fcs(b'\x00\x00123456789') + FLAG)
45
46     def test_escape(self):
47         self.assertEqual(
48             encode.information_frame(0x7e, b'\x7d'),
49             FLAG + b'\x7d\x5e\x00\x7d\x5d' + _fcs(b'\x7e\x00\x7d') + FLAG)
50         self.assertEqual(
51             encode.information_frame(0x7d, b'A\x7e\x7dBC'),
52             FLAG + b'\x7d\x5d\x00A\x7d\x5e\x7d\x5dBC' +
53             _fcs(b'\x7d\x00A\x7e\x7dBC') + FLAG)
54
55
56 if __name__ == '__main__':
57     unittest.main()