Chris Liechti | 790be84 | 2016-09-08 23:36:57 +0200 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # |
| 3 | # This file is part of pySerial - Cross platform serial port support for Python |
| 4 | # (C) 2016 Chris Liechti <cliechti@gmx.net> |
| 5 | # |
| 6 | # SPDX-License-Identifier: BSD-3-Clause |
| 7 | """\ |
| 8 | Test serial.threaded related functionality. |
| 9 | """ |
| 10 | |
| 11 | import os |
| 12 | import unittest |
| 13 | import serial |
| 14 | import serial.threaded |
| 15 | import time |
| 16 | |
| 17 | |
| 18 | # on which port should the tests be performed: |
| 19 | PORT = 'loop://' |
| 20 | |
| 21 | class Test_asyncio(unittest.TestCase): |
| 22 | """Test asyncio related functionality""" |
| 23 | |
| 24 | def test_line_reader(self): |
| 25 | """simple test of line reader class""" |
| 26 | |
| 27 | class TestLines(serial.threaded.LineReader): |
| 28 | def __init__(self): |
| 29 | super(TestLines, self).__init__() |
| 30 | self.received_lines = [] |
| 31 | |
| 32 | def handle_line(self, data): |
| 33 | self.received_lines.append(data) |
| 34 | |
| 35 | ser = serial.serial_for_url(PORT, baudrate=115200, timeout=1) |
| 36 | with serial.threaded.ReaderThread(ser, TestLines) as protocol: |
| 37 | protocol.write_line('hello') |
Chris Liechti | 686abf5 | 2016-09-09 00:38:46 +0200 | [diff] [blame] | 38 | protocol.write_line('world') |
Chris Liechti | 790be84 | 2016-09-08 23:36:57 +0200 | [diff] [blame] | 39 | time.sleep(1) |
Chris Liechti | 686abf5 | 2016-09-09 00:38:46 +0200 | [diff] [blame] | 40 | self.assertEqual(protocol.received_lines, ['hello', 'world']) |
| 41 | |
| 42 | def test_framed_packet(self): |
| 43 | """simple test of line reader class""" |
| 44 | |
| 45 | class TestFramedPacket(serial.threaded.FramedPacket): |
| 46 | def __init__(self): |
| 47 | super(TestFramedPacket, self).__init__() |
| 48 | self.received_packets = [] |
| 49 | |
| 50 | def handle_packet(self, packet): |
| 51 | self.received_packets.append(packet) |
| 52 | |
| 53 | def send_packet(self, packet): |
| 54 | self.transport.write(self.START) |
| 55 | self.transport.write(packet) |
| 56 | self.transport.write(self.STOP) |
| 57 | |
| 58 | ser = serial.serial_for_url(PORT, baudrate=115200, timeout=1) |
| 59 | with serial.threaded.ReaderThread(ser, TestFramedPacket) as protocol: |
| 60 | protocol.send_packet(b'1') |
| 61 | protocol.send_packet(b'2') |
| 62 | protocol.send_packet(b'3') |
| 63 | time.sleep(1) |
| 64 | self.assertEqual(protocol.received_packets, [b'1', b'2', b'3']) |
Chris Liechti | 790be84 | 2016-09-08 23:36:57 +0200 | [diff] [blame] | 65 | |
| 66 | |
| 67 | if __name__ == '__main__': |
| 68 | import sys |
| 69 | sys.stdout.write(__doc__) |
| 70 | if len(sys.argv) > 1: |
| 71 | PORT = sys.argv[1] |
| 72 | sys.stdout.write("Testing port: {!r}\n".format(PORT)) |
| 73 | sys.argv[1:] = ['-v'] |
| 74 | # When this module is executed from the command-line, it runs all its tests |
| 75 | unittest.main() |