1#!/usr/bin/env python
2#
3# This file is part of pySerial - Cross platform serial port support for Python
4# (C) 2017 Chris Liechti <cliechti@gmx.net>
5#
6# SPDX-License-Identifier:    BSD-3-Clause
7"""\
8Tests for exclusive access feature.
9"""
10
11import os
12import unittest
13import sys
14import serial
15
16# on which port should the tests be performed:
17PORT = 'loop://'
18
19class Test_exclusive(unittest.TestCase):
20    """Test serial port locking"""
21
22    def setUp(self):
23        with serial.serial_for_url(PORT, do_not_open=True) as x:
24            if not isinstance(x, serial.Serial):
25                raise unittest.SkipTest("exclusive test only compatible with real serial port")
26
27    def test_exclusive_none(self):
28        """test for exclusive=None"""
29        with serial.Serial(PORT, exclusive=None):
30            pass  # OK
31
32    @unittest.skipUnless(os.name == 'posix', "exclusive=False not supported on platform")
33    def test_exclusive_false(self):
34        """test for exclusive=False"""
35        with serial.Serial(PORT, exclusive=False):
36            pass  # OK
37
38    @unittest.skipUnless(os.name in ('posix', 'nt'), "exclusive=True setting not supported on platform")
39    def test_exclusive_true(self):
40        """test for exclusive=True"""
41        with serial.Serial(PORT, exclusive=True):
42            with self.assertRaises(serial.SerialException):
43                serial.Serial(PORT, exclusive=True)  # fails to open twice
44
45    @unittest.skipUnless(os.name == 'nt', "platform is not restricted to exclusive=True (and None)")
46    def test_exclusive_only_true(self):
47        """test if exclusive=False is not supported"""
48        with self.assertRaises(ValueError):
49            serial.Serial(PORT, exclusive=False) # expected to fail: False not supported
50
51
52if __name__ == '__main__':
53    sys.stdout.write(__doc__)
54    if len(sys.argv) > 1:
55        PORT = sys.argv[1]
56    sys.stdout.write("Testing port: {!r}\n".format(PORT))
57    sys.argv[1:] = ['-v']
58    # When this module is executed from the command-line, it runs all its tests
59    unittest.main()
60