aboutsummaryrefslogtreecommitdiff
path: root/tests/mobly/snippet/callback_handler_base_test.py
blob: 0891fd5b8d0aaa820c0aaa52ee387fb51d8e5cb5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# Copyright 2022 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for mobly.snippet.callback_handler_base.CallbackHandlerBase."""

import unittest
from unittest import mock

from mobly.snippet import callback_event
from mobly.snippet import callback_handler_base
from mobly.snippet import errors

MOCK_CALLBACK_ID = '2-1'
MOCK_RAW_EVENT = {
    'callbackId': '2-1',
    'name': 'AsyncTaskResult',
    'time': 20460228696,
    'data': {
        'exampleData': "Here's a simple event.",
        'successful': True,
        'secretNumber': 12
    }
}


class FakeCallbackHandler(callback_handler_base.CallbackHandlerBase):
  """Fake client class for unit tests."""

  def __init__(self,
               callback_id=None,
               event_client=None,
               ret_value=None,
               method_name=None,
               device=None,
               rpc_max_timeout_sec=120,
               default_timeout_sec=120):
    """Initializes a fake callback handler object used for unit tests."""
    super().__init__(callback_id, event_client, ret_value, method_name, device,
                     rpc_max_timeout_sec, default_timeout_sec)
    self.mock_rpc_func = mock.Mock()

  def callEventWaitAndGetRpc(self, *args, **kwargs):
    """See base class."""
    return self.mock_rpc_func.callEventWaitAndGetRpc(*args, **kwargs)

  def callEventGetAllRpc(self, *args, **kwargs):
    """See base class."""
    return self.mock_rpc_func.callEventGetAllRpc(*args, **kwargs)


class CallbackHandlerBaseTest(unittest.TestCase):
  """Unit tests for mobly.snippet.callback_handler_base.CallbackHandlerBase."""

  def assert_event_correct(self, actual_event, expected_raw_event_dict):
    expected_event = callback_event.from_dict(expected_raw_event_dict)
    self.assertEqual(str(actual_event), str(expected_event))

  def test_default_timeout_too_large(self):
    err_msg = ('The max timeout of a single RPC must be no smaller than '
               'the default timeout of the callback handler. '
               'Got rpc_max_timeout_sec=10, default_timeout_sec=20.')
    with self.assertRaisesRegex(ValueError, err_msg):
      _ = FakeCallbackHandler(rpc_max_timeout_sec=10, default_timeout_sec=20)

  def test_timeout_property(self):
    handler = FakeCallbackHandler(rpc_max_timeout_sec=20,
                                  default_timeout_sec=10)
    self.assertEqual(handler.rpc_max_timeout_sec, 20)
    self.assertEqual(handler.default_timeout_sec, 10)
    with self.assertRaises(AttributeError):
      handler.rpc_max_timeout_sec = 5

    with self.assertRaises(AttributeError):
      handler.default_timeout_sec = 5

  def test_callback_id_property(self):
    handler = FakeCallbackHandler(callback_id=MOCK_CALLBACK_ID)
    self.assertEqual(handler.callback_id, MOCK_CALLBACK_ID)
    with self.assertRaises(AttributeError):
      handler.callback_id = 'ha'

  def test_event_dict_to_snippet_event(self):
    handler = FakeCallbackHandler(callback_id=MOCK_CALLBACK_ID)
    handler.mock_rpc_func.callEventWaitAndGetRpc = mock.Mock(
        return_value=MOCK_RAW_EVENT)

    event = handler.waitAndGet('ha', timeout=10)
    self.assert_event_correct(event, MOCK_RAW_EVENT)
    handler.mock_rpc_func.callEventWaitAndGetRpc.assert_called_once_with(
        MOCK_CALLBACK_ID, 'ha', 10)

  def test_wait_and_get_timeout_default(self):
    handler = FakeCallbackHandler(rpc_max_timeout_sec=20, default_timeout_sec=5)
    handler.mock_rpc_func.callEventWaitAndGetRpc = mock.Mock(
        return_value=MOCK_RAW_EVENT)
    _ = handler.waitAndGet('ha')
    handler.mock_rpc_func.callEventWaitAndGetRpc.assert_called_once_with(
        mock.ANY, mock.ANY, 5)

  def test_wait_and_get_timeout_ecxeed_threshold(self):
    rpc_max_timeout_sec = 5
    big_timeout_sec = 10
    handler = FakeCallbackHandler(rpc_max_timeout_sec=rpc_max_timeout_sec,
                                  default_timeout_sec=rpc_max_timeout_sec)
    handler.mock_rpc_func.callEventWaitAndGetRpc = mock.Mock(
        return_value=MOCK_RAW_EVENT)

    expected_msg = (
        f'Specified timeout {big_timeout_sec} is longer than max timeout '
        f'{rpc_max_timeout_sec}.')
    with self.assertRaisesRegex(errors.CallbackHandlerBaseError, expected_msg):
      handler.waitAndGet('ha', big_timeout_sec)

  def test_wait_for_event(self):
    handler = FakeCallbackHandler()
    handler.mock_rpc_func.callEventWaitAndGetRpc = mock.Mock(
        return_value=MOCK_RAW_EVENT)

    def some_condition(event):
      return event.data['successful']

    event = handler.waitForEvent('AsyncTaskResult', some_condition, 0.01)
    self.assert_event_correct(event, MOCK_RAW_EVENT)

  def test_wait_for_event_negative(self):
    handler = FakeCallbackHandler()
    handler.mock_rpc_func.callEventWaitAndGetRpc = mock.Mock(
        return_value=MOCK_RAW_EVENT)

    expected_msg = (
        'Timed out after 0.01s waiting for an "AsyncTaskResult" event that'
        ' satisfies the predicate "some_condition".')

    def some_condition(_):
      return False

    with self.assertRaisesRegex(errors.CallbackHandlerTimeoutError,
                                expected_msg):
      handler.waitForEvent('AsyncTaskResult', some_condition, 0.01)

  def test_wait_for_event_max_timeout(self):
    """waitForEvent should not raise the timeout exceed threshold error."""
    rpc_max_timeout_sec = 5
    big_timeout_sec = 10
    handler = FakeCallbackHandler(rpc_max_timeout_sec=rpc_max_timeout_sec,
                                  default_timeout_sec=rpc_max_timeout_sec)
    handler.mock_rpc_func.callEventWaitAndGetRpc = mock.Mock(
        return_value=MOCK_RAW_EVENT)

    def some_condition(event):
      return event.data['successful']

    # This line should not raise.
    event = handler.waitForEvent('AsyncTaskResult',
                                 some_condition,
                                 timeout=big_timeout_sec)
    self.assert_event_correct(event, MOCK_RAW_EVENT)

  def test_get_all(self):
    handler = FakeCallbackHandler(callback_id=MOCK_CALLBACK_ID)
    handler.mock_rpc_func.callEventGetAllRpc = mock.Mock(
        return_value=[MOCK_RAW_EVENT, MOCK_RAW_EVENT])

    all_events = handler.getAll('ha')
    for event in all_events:
      self.assert_event_correct(event, MOCK_RAW_EVENT)

    handler.mock_rpc_func.callEventGetAllRpc.assert_called_once_with(
        MOCK_CALLBACK_ID, 'ha')


if __name__ == '__main__':
  unittest.main()