blob: 0a5f3d9254cefbe6ebe7408f1cf40ec24643e220 [file] [log] [blame]
Allen Lic54362d2017-07-12 18:21:26 -07001# Copyright 2017 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Unit tests for loop."""
6
7# pylint: disable=protected-access
8
9from __future__ import absolute_import
Allen Lic54362d2017-07-12 18:21:26 -070010
11import contextlib
12
Allen Lic54362d2017-07-12 18:21:26 -070013from chromite.lib import cros_test_lib
14from chromite.scripts.sysmon import loop
Mike Frysinger40ffb532021-02-12 07:36:08 -050015from chromite.third_party import mock
Allen Lic54362d2017-07-12 18:21:26 -070016
17
Allen Lic54362d2017-07-12 18:21:26 -070018class _MockTime(object):
19 """Mock time and sleep.
20
21 Provides mock behavior for time.time() and time.sleep()
22 """
23
24 def __init__(self, sleep_delta):
25 """Instantiate instance.
26
27 Args:
28 sleep_delta: Modify sleep time by this many seconds.
29 But sleep will always be at least 1.
30 """
31 self.current_time = 0
32 self._sleep_delta = sleep_delta
33
34 def time(self):
35 return self.current_time
36
37 def sleep(self, secs):
38 actual_sleep = max(secs + self._sleep_delta, 1)
39 self.current_time += actual_sleep
40 return actual_sleep
41
42
43@contextlib.contextmanager
44def _patch_time(sleep_delta):
45 """Mock out time and sleep.
46
47 Patches behavior for time.time() and time.sleep()
48 """
49 mock_time = _MockTime(sleep_delta)
50 with mock.patch('time.time', mock_time.time), \
51 mock.patch('time.sleep', mock_time.sleep):
52 yield mock_time
53
54
55class TestForceSleep(cros_test_lib.TestCase):
56 """Tests for _force_sleep."""
57
58 def test__force_sleep_at_least_given_secs(self):
59 with _patch_time(sleep_delta=-7) as mock_time:
60 loop._force_sleep(10)
61 self.assertGreaterEqual(mock_time.current_time, 10)