blob: 4794bfe9aeaccfef51b08ce9e54e8f345e493cd2 [file] [log] [blame]
Chris Liechti242f8c42016-05-23 23:38:02 +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 asyncio related functionality.
9"""
10
11import unittest
12import serial
13
14# on which port should the tests be performed:
15PORT = '/dev/ttyUSB0'
16
17try:
18 import asyncio
19 import serial.aio
20except (ImportError, SyntaxError):
21 # not compatible with python 2.x
22 pass
23else:
24
25 class Test_asyncio(unittest.TestCase):
26 """Test asyncio related functionality"""
27
28 def setUp(self):
29 self.loop = asyncio.get_event_loop()
30 # create a closed serial port
31
32 def tearDown(self):
33 self.loop.close()
34
35 def test_asyncio(self):
36 TEXT = b'hello world\n'
37 received = []
38 actions = []
39
40 class Output(asyncio.Protocol):
41 def connection_made(self, transport):
42 self.transport = transport
43 actions.append('open')
44 transport.serial.rts = False
45 transport.write(TEXT)
46
47 def data_received(self, data):
48 #~ print('data received', repr(data))
49 received.append(data)
50 if b'\n' in data:
51 self.transport.close()
52
53 def connection_lost(self, exc):
54 actions.append('close')
55 asyncio.get_event_loop().stop()
56
57 def pause_writing(self):
58 actions.append('pause')
59 print(self.transport.get_write_buffer_size())
60
61 def resume_writing(self):
62 actions.append('resume')
63 print(self.transport.get_write_buffer_size())
64
65 coro = serial.aio.create_serial_connection(self.loop, Output, PORT, baudrate=115200)
66 self.loop.run_until_complete(coro)
67 self.loop.run_forever()
68 self.assertEqual(b''.join(received), TEXT)
69 self.assertEqual(actions, ['open', 'close'])
70
71
72if __name__ == '__main__':
73 import sys
74 sys.stdout.write(__doc__)
75 if len(sys.argv) > 1:
76 PORT = sys.argv[1]
77 sys.stdout.write("Testing port: %r\n" % PORT)
78 sys.argv[1:] = ['-v']
79 # When this module is executed from the command-line, it runs all its tests
80 unittest.main()