| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 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 |
|