blob: 333a5c086990f1087ad5fdf5adfcead96589a5f8 [file] [log] [blame]
Chris Liechti790be842016-09-08 23:36:57 +02001#!/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"""\
8Test serial.threaded related functionality.
9"""
10
11import os
12import unittest
13import serial
14import serial.threaded
15import time
16
17
18# on which port should the tests be performed:
19PORT = 'loop://'
20
21class 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 Liechti686abf52016-09-09 00:38:46 +020038 protocol.write_line('world')
Chris Liechti790be842016-09-08 23:36:57 +020039 time.sleep(1)
Chris Liechti686abf52016-09-09 00:38:46 +020040 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 Liechti790be842016-09-08 23:36:57 +020065
66
67if __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()