summaryrefslogtreecommitdiff
path: root/test/test_asyncio.py
blob: 4794bfe9aeaccfef51b08ce9e54e8f345e493cd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python
#
# This file is part of pySerial - Cross platform serial port support for Python
# (C) 2016 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier:    BSD-3-Clause
"""\
Test asyncio related functionality.
"""

import unittest
import serial

# on which port should the tests be performed:
PORT = '/dev/ttyUSB0'

try:
    import asyncio
    import serial.aio
except (ImportError, SyntaxError):
    # not compatible with python 2.x
    pass
else:

    class Test_asyncio(unittest.TestCase):
        """Test asyncio related functionality"""

        def setUp(self):
            self.loop = asyncio.get_event_loop()
            # create a closed serial port

        def tearDown(self):
            self.loop.close()

        def test_asyncio(self):
            TEXT = b'hello world\n'
            received = []
            actions = []

            class Output(asyncio.Protocol):
                def connection_made(self, transport):
                    self.transport = transport
                    actions.append('open')
                    transport.serial.rts = False
                    transport.write(TEXT)

                def data_received(self, data):
                    #~ print('data received', repr(data))
                    received.append(data)
                    if b'\n' in data:
                        self.transport.close()

                def connection_lost(self, exc):
                    actions.append('close')
                    asyncio.get_event_loop().stop()

                def pause_writing(self):
                    actions.append('pause')
                    print(self.transport.get_write_buffer_size())

                def resume_writing(self):
                    actions.append('resume')
                    print(self.transport.get_write_buffer_size())

            coro = serial.aio.create_serial_connection(self.loop, Output, PORT, baudrate=115200)
            self.loop.run_until_complete(coro)
            self.loop.run_forever()
            self.assertEqual(b''.join(received), TEXT)
            self.assertEqual(actions, ['open', 'close'])


if __name__ == '__main__':
    import sys
    sys.stdout.write(__doc__)
    if len(sys.argv) > 1:
        PORT = sys.argv[1]
    sys.stdout.write("Testing port: %r\n" % PORT)
    sys.argv[1:] = ['-v']
    # When this module is executed from the command-line, it runs all its tests
    unittest.main()