blob: 988e9ea89279b2016d6cdc18e214600446ab9955 [file] [log] [blame]
Mike Frysingerf1ba7ad2022-09-12 05:42:57 -04001# Copyright 2017 The ChromiumOS Authors
Allen Lic54362d2017-07-12 18:21:26 -07002# 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
Mike Frysinger166fea02021-02-12 05:30:33 -050012from unittest import mock
Allen Lic54362d2017-07-12 18:21:26 -070013
Allen Lic54362d2017-07-12 18:21:26 -070014from chromite.lib import cros_test_lib
15from chromite.scripts.sysmon import loop
16
17
Allen Lic54362d2017-07-12 18:21:26 -070018class _MockTime(object):
Alex Klein1699fab2022-09-08 08:46:06 -060019 """Mock time and sleep.
Allen Lic54362d2017-07-12 18:21:26 -070020
Alex Klein1699fab2022-09-08 08:46:06 -060021 Provides mock behavior for time.time() and time.sleep()
Allen Lic54362d2017-07-12 18:21:26 -070022 """
Allen Lic54362d2017-07-12 18:21:26 -070023
Alex Klein1699fab2022-09-08 08:46:06 -060024 def __init__(self, sleep_delta):
25 """Instantiate instance.
Allen Lic54362d2017-07-12 18:21:26 -070026
Alex Klein1699fab2022-09-08 08:46:06 -060027 Args:
Trent Apted66736d82023-05-25 10:38:28 +100028 sleep_delta: Modify sleep time by this many seconds. But sleep will
29 always be at least 1.
Alex Klein1699fab2022-09-08 08:46:06 -060030 """
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
Allen Lic54362d2017-07-12 18:21:26 -070041
42
43@contextlib.contextmanager
44def _patch_time(sleep_delta):
Alex Klein1699fab2022-09-08 08:46:06 -060045 """Mock out time and sleep.
Allen Lic54362d2017-07-12 18:21:26 -070046
Alex Klein1699fab2022-09-08 08:46:06 -060047 Patches behavior for time.time() and time.sleep()
48 """
49 mock_time = _MockTime(sleep_delta)
50 with mock.patch("time.time", mock_time.time), mock.patch(
51 "time.sleep", mock_time.sleep
52 ):
53 yield mock_time
Allen Lic54362d2017-07-12 18:21:26 -070054
55
56class TestForceSleep(cros_test_lib.TestCase):
Alex Klein1699fab2022-09-08 08:46:06 -060057 """Tests for _force_sleep."""
Allen Lic54362d2017-07-12 18:21:26 -070058
Alex Klein1699fab2022-09-08 08:46:06 -060059 def test__force_sleep_at_least_given_secs(self):
60 with _patch_time(sleep_delta=-7) as mock_time:
61 loop._force_sleep(10)
62 self.assertGreaterEqual(mock_time.current_time, 10)