1#!/usr/bin/env python
2#
3# This file is part of pySerial - Cross platform serial port support for Python
4# (C) 2002-2015 Chris Liechti <[email protected]>
5#
6# SPDX-License-Identifier:    BSD-3-Clause
7"""\
8Test the ability to get and set the settings with a dictionary.
9
10Part of pySerial (http://pyserial.sf.net)  (C) 2002-2015 [email protected]
11
12"""
13
14import unittest
15import serial
16
17# on which port should the tests be performed:
18PORT = 'loop://'
19
20
21SETTINGS = ('baudrate', 'bytesize', 'parity', 'stopbits', 'xonxoff',
22            'dsrdtr', 'rtscts', 'timeout', 'write_timeout', 'inter_byte_timeout')
23
24
25class Test_SettingsDict(unittest.TestCase):
26    """Test with settings dictionary"""
27
28    def test_getsettings(self):
29        """the settings dict reflects the current settings"""
30        ser = serial.serial_for_url(PORT, do_not_open=True)
31        d = ser.get_settings()
32        for setting in SETTINGS:
33            self.assertEqual(getattr(ser, setting), d[setting])
34
35    def test_partial_settings(self):
36        """partial settings dictionaries are also accepted"""
37        ser = serial.serial_for_url(PORT, do_not_open=True)
38        d = ser.get_settings()
39        del d['baudrate']
40        del d['bytesize']
41        ser.apply_settings(d)
42        for setting in d:
43            self.assertEqual(getattr(ser, setting), d[setting])
44
45    def test_unknown_settings(self):
46        """unknown settings are ignored"""
47        ser = serial.serial_for_url(PORT, do_not_open=True)
48        d = ser.get_settings()
49        d['foobar'] = 'ignore me'
50        ser.apply_settings(d)
51
52    def test_init_sets_the_correct_attrs(self):
53        """__init__ sets the fields that get_settings reads"""
54        for setting, value in (
55                ('baudrate', 57600),
56                ('timeout', 7),
57                ('write_timeout', 12),
58                ('inter_byte_timeout', 15),
59                ('stopbits', serial.STOPBITS_TWO),
60                ('bytesize', serial.SEVENBITS),
61                ('parity', serial.PARITY_ODD),
62                ('xonxoff', True),
63                ('rtscts', True),
64                ('dsrdtr', True)):
65            kwargs = {'do_not_open': True, setting: value}
66            ser = serial.serial_for_url(PORT, **kwargs)
67            d = ser.get_settings()
68            self.assertEqual(getattr(ser, setting), value)
69            self.assertEqual(d[setting], value)
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".format(PORT))
78    sys.argv[1:] = ['-v']
79    # When this module is executed from the command-line, it runs all its tests
80    unittest.main()
81