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 33 def test_empty(self): 34 self.assertEqual( 35 encode.ui_frame(0, b''), FLAG + _with_fcs(b'\x01\x03') + FLAG 36 ) 37 self.assertEqual( 38 encode.ui_frame(0x1A, b''), FLAG + _with_fcs(b'\x35\x03') + FLAG 39 ) 40 41 def test_1byte(self): 42 self.assertEqual( 43 encode.ui_frame(0, b'A'), FLAG + _with_fcs(b'\x01\x03A') + FLAG 44 ) 45 46 def test_multibyte(self): 47 self.assertEqual( 48 encode.ui_frame(0, b'123456789'), 49 FLAG + _with_fcs(b'\x01\x03123456789') + FLAG, 50 ) 51 52 def test_multibyte_address(self): 53 self.assertEqual( 54 encode.ui_frame(128, b'123456789'), 55 FLAG + _with_fcs(b'\x00\x03\x03123456789') + FLAG, 56 ) 57 58 def test_escape(self): 59 self.assertEqual( 60 encode.ui_frame(0x3E, b'\x7d'), 61 FLAG + b'\x7d\x5d\x03\x7d\x5d' + _fcs(b'\x7d\x03\x7d') + FLAG, 62 ) 63 self.assertEqual( 64 encode.ui_frame(0x3E, b'A\x7e\x7dBC'), 65 FLAG 66 + b'\x7d\x5d\x03A\x7d\x5e\x7d\x5dBC' 67 + _fcs(b'\x7d\x03A\x7e\x7dBC') 68 + FLAG, 69 ) 70 71 72if __name__ == '__main__': 73 unittest.main() 74