blob: 7bc4980a36095068e18d5aa6e83892ff6f4e2935 [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
10from __future__ import print_function
11
12import contextlib
13
14import mock
15
16from chromite.lib import cros_test_lib
17from chromite.scripts.sysmon import loop
18
19
20class _MockTime(object):
21 """Mock time and sleep.
22
23 Provides mock behavior for time.time() and time.sleep()
24 """
25
26 def __init__(self, sleep_delta):
27 """Instantiate instance.
28
29 Args:
30 sleep_delta: Modify sleep time by this many seconds.
31 But sleep will always be at least 1.
32 """
33 self.current_time = 0
34 self._sleep_delta = sleep_delta
35
36 def time(self):
37 return self.current_time
38
39 def sleep(self, secs):
40 actual_sleep = max(secs + self._sleep_delta, 1)
41 self.current_time += actual_sleep
42 return actual_sleep
43
44
45@contextlib.contextmanager
46def _patch_time(sleep_delta):
47 """Mock out time and sleep.
48
49 Patches behavior for time.time() and time.sleep()
50 """
51 mock_time = _MockTime(sleep_delta)
52 with mock.patch('time.time', mock_time.time), \
53 mock.patch('time.sleep', mock_time.sleep):
54 yield mock_time
55
56
57class TestForceSleep(cros_test_lib.TestCase):
58 """Tests for _force_sleep."""
59
60 def test__force_sleep_at_least_given_secs(self):
61 with _patch_time(sleep_delta=-7) as mock_time:
62 loop._force_sleep(10)
63 self.assertGreaterEqual(mock_time.current_time, 10)