Allen Li | c54362d | 2017-07-12 18:21:26 -0700 | [diff] [blame] | 1 | # 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 | |
| 9 | from __future__ import absolute_import |
Allen Li | c54362d | 2017-07-12 18:21:26 -0700 | [diff] [blame] | 10 | |
| 11 | import contextlib |
Mike Frysinger | 166fea0 | 2021-02-12 05:30:33 -0500 | [diff] [blame^] | 12 | from unittest import mock |
Allen Li | c54362d | 2017-07-12 18:21:26 -0700 | [diff] [blame] | 13 | |
Allen Li | c54362d | 2017-07-12 18:21:26 -0700 | [diff] [blame] | 14 | from chromite.lib import cros_test_lib |
| 15 | from chromite.scripts.sysmon import loop |
| 16 | |
| 17 | |
Allen Li | c54362d | 2017-07-12 18:21:26 -0700 | [diff] [blame] | 18 | class _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 |
| 44 | def _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 | |
| 55 | class 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) |