1
|
|
|
import unittest |
2
|
|
|
import sys |
3
|
|
|
|
4
|
|
|
if sys.version_info[0] < 3: |
5
|
|
|
import mock |
6
|
|
|
else: |
7
|
|
|
import unittest.mock as mock |
8
|
|
|
import obdlib.uart as uart |
9
|
|
|
import serial |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
class TestUART(unittest.TestCase): |
13
|
|
|
def setUp(self): |
14
|
|
|
serial.Serial = mock.Mock() |
15
|
|
|
self.tUART = uart.UART() |
16
|
|
|
|
17
|
|
|
@mock.patch('sys.stdout') |
18
|
|
|
@mock.patch('obdlib.uart.UART._mapping') |
19
|
|
|
@mock.patch('obdlib.uart.uart_base') |
20
|
|
|
def test_connection(self, mock_ubase, mock_map, mock_out): |
21
|
|
|
resp = self.tUART.connection('/dev/null') |
22
|
|
|
self.assertEqual(mock_ubase.call_count, 1) |
23
|
|
|
self.assertEqual(mock_ubase.call_args_list[0][0], ('/dev/null', 38400)) |
24
|
|
|
self.assertEqual(mock_map.call_count, 1) |
25
|
|
|
self.assertEqual(mock_map.call_args_list[0][0], ()) |
26
|
|
|
self.assertIsInstance(resp, uart.UART) |
27
|
|
|
|
28
|
|
|
# Raise Exception |
29
|
|
|
mock_ubase.reset_mock() |
30
|
|
|
mock_map.reset_mock() |
31
|
|
|
mock_ubase.side_effect = Exception("Error connection") |
32
|
|
|
resp = self.tUART.connection('/dev/null') |
33
|
|
|
self.assertEqual(mock_ubase.call_count, 1) |
34
|
|
|
self.assertEqual(mock_ubase.call_args_list[0][0], ('/dev/null', 38400)) |
35
|
|
|
self.assertEqual(mock_map.call_count, 0) |
36
|
|
|
self.assertIsNone(resp) |
37
|
|
|
|
38
|
|
|
def test__getattr__(self): |
39
|
|
|
with self.assertRaises(Exception) as cm: |
40
|
|
|
self.tUART.init() |
41
|
|
|
self.assertEqual(cm.exception.__str__(), 'Unregistered method or attribute init') |
42
|
|
|
|
43
|
|
|
# check method |
44
|
|
|
raised = False |
45
|
|
|
try: |
46
|
|
|
self.tUART.bus = mock.Mock() |
47
|
|
|
self.tUART.read() |
48
|
|
|
except: |
49
|
|
|
raised = True |
50
|
|
|
self.assertFalse(raised) |
51
|
|
|
|
52
|
|
|
def test_invoke_mapping(self): |
53
|
|
|
self.tUART.bus = mock.Mock() |
54
|
|
|
self.tUART.bus_name = 'UART' |
55
|
|
|
self.tUART._mapping() |
56
|
|
|
self.tUART._invoke_mapping('close') |
57
|
|
|
|
58
|
|
|
method = 'init' |
59
|
|
|
with self.assertRaises(Exception) as cm: |
60
|
|
|
self.tUART._invoke_mapping(method) |
61
|
|
|
self.assertEqual(cm.exception.__str__(), 'Unregistered method or attribute {}'.format(method)) |
62
|
|
|
|
63
|
|
|
def test__mapping(self): |
64
|
|
|
expected = { |
65
|
|
|
"UART": { |
66
|
|
|
"close": "deinit", |
67
|
|
|
"flushInput": "", |
68
|
|
|
"flushOutput": "" |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
self.tUART._mapping() |
72
|
|
|
self.assertIsInstance(self.tUART.map, dict) |
73
|
|
|
self.assertEqual(self.tUART.map, expected) |
74
|
|
|
|
75
|
|
|
|
76
|
|
|
suite = unittest.TestLoader().loadTestsFromTestCase(TestUART) |
77
|
|
|
unittest.TextTestRunner(verbosity=2).run(suite) |
78
|
|
|
|