blob: 6e53cf01e63bfd269e89508ac5e60734b9735c1e [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Allen Lic54362d2017-07-12 18:21:26 -07002# Copyright 2017 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Unit tests for loop."""
7
8# pylint: disable=protected-access
9
10from __future__ import absolute_import
11from __future__ import print_function
12
13import contextlib
Mike Frysinger1ca14432020-02-16 00:18:56 -050014import sys
Allen Lic54362d2017-07-12 18:21:26 -070015
Allen Lic54362d2017-07-12 18:21:26 -070016from chromite.lib import cros_test_lib
17from chromite.scripts.sysmon import loop
Mike Frysinger40ffb532021-02-12 07:36:08 -050018from chromite.third_party import mock
Allen Lic54362d2017-07-12 18:21:26 -070019
20
Mike Frysinger1ca14432020-02-16 00:18:56 -050021assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
22
23
Allen Lic54362d2017-07-12 18:21:26 -070024class _MockTime(object):
25 """Mock time and sleep.
26
27 Provides mock behavior for time.time() and time.sleep()
28 """
29
30 def __init__(self, sleep_delta):
31 """Instantiate instance.
32
33 Args:
34 sleep_delta: Modify sleep time by this many seconds.
35 But sleep will always be at least 1.
36 """
37 self.current_time = 0
38 self._sleep_delta = sleep_delta
39
40 def time(self):
41 return self.current_time
42
43 def sleep(self, secs):
44 actual_sleep = max(secs + self._sleep_delta, 1)
45 self.current_time += actual_sleep
46 return actual_sleep
47
48
49@contextlib.contextmanager
50def _patch_time(sleep_delta):
51 """Mock out time and sleep.
52
53 Patches behavior for time.time() and time.sleep()
54 """
55 mock_time = _MockTime(sleep_delta)
56 with mock.patch('time.time', mock_time.time), \
57 mock.patch('time.sleep', mock_time.sleep):
58 yield mock_time
59
60
61class TestForceSleep(cros_test_lib.TestCase):
62 """Tests for _force_sleep."""
63
64 def test__force_sleep_at_least_given_secs(self):
65 with _patch_time(sleep_delta=-7) as mock_time:
66 loop._force_sleep(10)
67 self.assertGreaterEqual(mock_time.current_time, 10)