blob: 5c7bb2ae005429c167a93550daac2b3f12a8a80b [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
16import mock
17
18from chromite.lib import cros_test_lib
19from chromite.scripts.sysmon import loop
20
21
Mike Frysinger1ca14432020-02-16 00:18:56 -050022assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
23
24
Allen Lic54362d2017-07-12 18:21:26 -070025class _MockTime(object):
26 """Mock time and sleep.
27
28 Provides mock behavior for time.time() and time.sleep()
29 """
30
31 def __init__(self, sleep_delta):
32 """Instantiate instance.
33
34 Args:
35 sleep_delta: Modify sleep time by this many seconds.
36 But sleep will always be at least 1.
37 """
38 self.current_time = 0
39 self._sleep_delta = sleep_delta
40
41 def time(self):
42 return self.current_time
43
44 def sleep(self, secs):
45 actual_sleep = max(secs + self._sleep_delta, 1)
46 self.current_time += actual_sleep
47 return actual_sleep
48
49
50@contextlib.contextmanager
51def _patch_time(sleep_delta):
52 """Mock out time and sleep.
53
54 Patches behavior for time.time() and time.sleep()
55 """
56 mock_time = _MockTime(sleep_delta)
57 with mock.patch('time.time', mock_time.time), \
58 mock.patch('time.sleep', mock_time.sleep):
59 yield mock_time
60
61
62class TestForceSleep(cros_test_lib.TestCase):
63 """Tests for _force_sleep."""
64
65 def test__force_sleep_at_least_given_secs(self):
66 with _patch_time(sleep_delta=-7) as mock_time:
67 loop._force_sleep(10)
68 self.assertGreaterEqual(mock_time.current_time, 10)