xref: /aosp_15_r20/external/pigweed/pw_rpc/py/tests/console_tools/watchdog_test.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1#!/usr/bin/env python3
2# Copyright 2021 The Pigweed Authors
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may not
5# use this file except in compliance with the License. You may obtain a copy of
6# the License at
7#
8#     https://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations under
14# the License.
15"""Tests the Watchdog module."""
16
17import unittest
18from unittest import mock
19
20from pw_rpc.console_tools import Watchdog
21
22
23class TestWatchdog(unittest.TestCase):
24    """Tests the Watchdog class."""
25
26    def setUp(self) -> None:
27        self._reset = mock.Mock()
28        self._expiration = mock.Mock()
29        self._while_expired = mock.Mock()
30
31        self._watchdog = Watchdog(
32            self._reset, self._expiration, self._while_expired, 99999
33        )
34
35    def _trigger_timeout(self) -> None:
36        # Don't wait for the timeout -- that's too flaky. Call the internal
37        # timeout function instead.
38        self._watchdog._timeout_expired()  # pylint: disable=protected-access
39
40    def test_expiration_callbacks(self) -> None:
41        self._watchdog.start()
42
43        self._expiration.not_called()
44
45        self._trigger_timeout()
46
47        self._expiration.assert_called_once_with()
48        self._while_expired.assert_not_called()
49
50        self._trigger_timeout()
51
52        self._expiration.assert_called_once_with()
53        self._while_expired.assert_called_once_with()
54
55        self._trigger_timeout()
56
57        self._expiration.assert_called_once_with()
58        self._while_expired.assert_called()
59
60    def test_reset_not_called_unless_expires(self) -> None:
61        self._watchdog.start()
62        self._watchdog.reset()
63
64        self._reset.assert_not_called()
65        self._expiration.assert_not_called()
66        self._while_expired.assert_not_called()
67
68    def test_reset_called_if_expired(self) -> None:
69        self._watchdog.start()
70        self._trigger_timeout()
71
72        self._watchdog.reset()
73
74        self._trigger_timeout()
75
76        self._reset.assert_called_once_with()
77        self._expiration.assert_called()
78
79
80if __name__ == '__main__':
81    unittest.main()
82