Debian Codegraph @

test/unit/test_timeout.py

raw symbols SCIP
1 # pyOCD debugger
2 # Copyright (c) 2017-2019 Arm Limited
3 # SPDX-License-Identifier: Apache-2.0
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 from time import (time, sleep)
18 import pytest
19 from unittest.mock import Mock
20
21 from pyocd.utility.timeout import Timeout
22
23 @pytest.fixture(scope='function')
24 def mock_time(monkeypatch):
25 mtime = Mock()
26 mtime.return_value = 0
27 monkeypatch.setattr('pyocd.utility.timeout.time', mtime)
28 return mtime
29
30 @pytest.fixture(scope='function')
31 def mock_sleep(monkeypatch, mock_time):
32 def inc_time(offset):
33 mock_time.return_value += offset
34 msleep = Mock()
35 msleep.side_effect = inc_time
36 msleep.return_value = None
37 monkeypatch.setattr('pyocd.utility.timeout.sleep', msleep)
38 return msleep
39
40 class TestTimeout:
41 def test_no_timeout(self, mock_time, mock_sleep):
42 with Timeout(0.05) as to:
43 cnt = 0
44 while to.check():
45 mock_sleep(0.01)
46 cnt += 1
47 if cnt == 2:
48 break
49 else:
50 assert False
51 assert not to.did_time_out
52
53 def test_timeout_a(self, mock_time, mock_sleep):
54 with Timeout(0.05) as to:
55 while to.check():
56 mock_sleep(0.01)
57 assert to.did_time_out
58
59 def test_timeout_b(self, mock_time, mock_sleep):
60 timedout = False
61 print(repr(time))
62 with Timeout(0.05) as to:
63 cnt = 0
64 while cnt < 10:
65 if to.did_time_out:
66 timedout = True
67 mock_sleep(0.02)
68 cnt += 1
69 assert timedout
70 assert to.did_time_out
71
72 def test_timeout_c(self, mock_time, mock_sleep):
73 timedout = False
74 with Timeout(0.05) as to:
75 cnt = 0
76 while cnt < 10:
77 if to.did_time_out:
78 timedout = True
79 cnt += 1
80 assert not timedout
81 assert not to.did_time_out
82
83 def test_timeout_reset(self, mock_time, mock_sleep):
84 cnt = 0
85 cnta = 0
86 with Timeout(0.05) as to:
87 cnta = 0
88 while cnta < 3:
89 cnt = 0
90 while to.check():
91 mock_sleep(0.01)
92 if cnta > 1:
93 break
94 cnt += 1
95 else:
96 assert to.did_time_out
97 to.clear()
98 to.start()
99 cnta += 1
100 assert cnta == 3 and cnt == 0
101 assert not to.did_time_out
102