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 17import unittest 18 19from pw_hdlc import encode 20from pw_hdlc import protocol 21from pw_hdlc.protocol import frame_check_sequence as _fcs 22 23FLAG = bytes([protocol.FLAG]) 24 25 26def _with_fcs(data: bytes) -> bytes: 27 return data + _fcs(data) 28 29 30class TestEncodeUIFrame(unittest.TestCase): 31 """Tests Encoding bytes with different arguments using a custom serial.""" 32 def test_empty(self): 33 self.assertEqual(encode.ui_frame(0, b''), 34 FLAG + _with_fcs(b'\x01\x03') + FLAG) 35 self.assertEqual(encode.ui_frame(0x1a, b''), 36 FLAG + _with_fcs(b'\x35\x03') + FLAG) 37 38 def test_1byte(self): 39 self.assertEqual(encode.ui_frame(0, b'A'), 40 FLAG + _with_fcs(b'\x01\x03A') + FLAG) 41 42 def test_multibyte(self): 43 self.assertEqual(encode.ui_frame(0, b'123456789'), 44 FLAG + _with_fcs(b'\x01\x03123456789') + FLAG) 45 46 def test_multibyte_address(self): 47 self.assertEqual(encode.ui_frame(128, b'123456789'), 48 FLAG + _with_fcs(b'\x00\x03\x03123456789') + FLAG) 49 50 def test_escape(self): 51 self.assertEqual( 52 encode.ui_frame(0x3e, b'\x7d'), 53 FLAG + b'\x7d\x5d\x03\x7d\x5d' + _fcs(b'\x7d\x03\x7d') + FLAG) 54 self.assertEqual( 55 encode.ui_frame(0x3e, b'A\x7e\x7dBC'), 56 FLAG + b'\x7d\x5d\x03A\x7d\x5e\x7d\x5dBC' + 57 _fcs(b'\x7d\x03A\x7e\x7dBC') + FLAG) 58 59 60if __name__ == '__main__': 61 unittest.main() 62