• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/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 Timeout helper class.
9"""
10import sys
11import unittest
12import time
13from serial import serialutil
14
15
16class TestTimeoutClass(unittest.TestCase):
17    """Test the Timeout class"""
18
19    def test_simple_timeout(self):
20        """Test simple timeout"""
21        t = serialutil.Timeout(2)
22        self.assertFalse(t.expired())
23        self.assertTrue(t.time_left() > 0)
24        time.sleep(2.1)
25        self.assertTrue(t.expired())
26        self.assertEqual(t.time_left(), 0)
27
28    def test_non_blocking(self):
29        """Test nonblocking case (0)"""
30        t = serialutil.Timeout(0)
31        self.assertTrue(t.is_non_blocking)
32        self.assertFalse(t.is_infinite)
33        self.assertTrue(t.expired())
34
35    def test_blocking(self):
36        """Test no timeout (None)"""
37        t = serialutil.Timeout(None)
38        self.assertFalse(t.is_non_blocking)
39        self.assertTrue(t.is_infinite)
40        #~ self.assertFalse(t.expired())
41
42    def test_changing_clock(self):
43        """Test recovery from chaning clock"""
44        class T(serialutil.Timeout):
45            def TIME(self):
46                return test_time
47        test_time = 1000
48        t = T(10)
49        self.assertEqual(t.target_time, 1010)
50        self.assertFalse(t.expired())
51        self.assertTrue(t.time_left() > 0)
52        test_time = 100  # clock jumps way back
53        self.assertTrue(t.time_left() > 0)
54        self.assertTrue(t.time_left() <= 10)
55        self.assertEqual(t.target_time, 110)
56        test_time = 10000  # jump way forward
57        self.assertEqual(t.time_left(), 0)  # if will expire immediately
58
59
60if __name__ == '__main__':
61    sys.stdout.write(__doc__)
62    if len(sys.argv) > 1:
63        PORT = sys.argv[1]
64    sys.argv[1:] = ['-v']
65    # When this module is executed from the command-line, it runs all its tests
66    unittest.main()
67