Debian Codegraph @

src/tests/test_outlets.py

raw symbols SCIP
1 """
2 This tests all requests made by outlet devices.
3
4 All tests inherit from the TestBase class which contains the fixtures
5 and methods needed to run the tests.
6
7 The tests are automatically parametrized by `pytest_generate_tests` in
8 conftest.py. The two methods that are parametrized are `test_details`
9 and `test_methods`. The class variables are used to build the list of
10 devices, test methods and arguments.
11
12 The `helpers.call_api` method is patched to return a mock response.
13 The method, endpoint, headers and json arguments are recorded
14 in YAML files in the api directory, categorized in folders by
15 module and files by the class name.
16
17 The default is to record requests that do not exist and compare requests
18 that already exist. If the API changes, set the overwrite argument to True
19 in order to overwrite the existing YAML file with the new request.
20
21 See Also
22 --------
23 `utils.TestBase` - Base class for all tests, containing mock objects
24 `confest.pytest_generate_tests` - Parametrizes tests based on
25 method names & class attributes
26 `call_json_outlets` - Contains API responses
27 """
28
29 import pytest
30 import logging
31 import pyvesync.const as const
32 from pyvesync.base_devices.outlet_base import VeSyncOutlet
33 from base_test_cases import TestBase
34 from utils import assert_test, parse_args
35 import call_json
36 import call_json_outlets
37
38 logger = logging.getLogger(__name__)
39 logger.setLevel(logging.DEBUG)
40
41 OUTLET_DEV_TYPES = call_json_outlets.OUTLETS
42 POWER_METHODS = ['get_energy_update']
43 OUTLET_PARAMS = [[dev, method] for dev in OUTLET_DEV_TYPES for method in POWER_METHODS]
44
45
46 class TestOutlets(TestBase):
47 """Outlets testing class.
48
49 This class tests outlets device details and methods. The methods are
50 parametrized from the class variables using `pytest_generate_tests`.
51 The call_json_outlets module contains the responses for the API requests.
52 The device is instantiated from the details provided by
53 `call_json.DeviceList.device_list_item()`. Inherits from `utils.TestBase`.
54
55 Instance Attributes
56 -------------------
57 self.manager : VeSync
58 Instantiated VeSync object
59 self.mock_api : Mock
60 Mock with patched `helpers.call_api` method
61 self.caplog : LogCaptureFixture
62 Pytest fixture for capturing logs
63
64 Class Attributes
65 ---------------
66 device : str
67 Name of device type - outlets
68 outlets : list
69 List of device types for outlets, this variable is named
70 after the device variable value
71 base_methods : List[List[str, Dict[str, Any]]]
72 List of common methods for all devices
73 device_methods : Dict[List[List[str, Dict[str, Any]]]]
74 Dictionary of methods specific to device types
75
76 Methods
77 --------
78 test_details()
79 Test the device details API request and response
80 test_methods()
81 Test device methods API request and response
82
83 Examples
84 --------
85 >>> device = 'outlets'
86 >>> outlets = ['ESW01-USA', 'ESW01-EU', 'ESW01-AU']
87 >>> base_methods = [['turn_on'], ['turn_off'], ['update']]
88 >>> device_methods = {
89 'dev_type': [['method1'], ['method2', {'kwargs': 'value'}]]
90 }
91
92 """
93
94 device = 'outlets'
95 outlets = call_json_outlets.OUTLETS
96 base_methods = [
97 ['turn_on'],
98 ['turn_off']
99 ]
100 device_methods = {
101 'ESW15-USA': [
102 ['turn_on_nightlight'],
103 ['turn_off_nightlight'],
104 ['get_weekly_energy'],
105 ['get_monthly_energy'],
106 ['get_yearly_energy']
107 ],
108 'wifi-switch-1.3': [
109 ['get_weekly_energy'],
110 ['get_monthly_energy'],
111 ['get_yearly_energy']
112 ],
113 # 'ESW03-USA': [
114 # ['get_weekly_energy'],
115 # ['get_monthly_energy'],
116 # ['get_yearly_energy']
117 # ],
118 'ESW01-EU': [
119 ['get_weekly_energy'],
120 ['get_monthly_energy'],
121 ['get_yearly_energy']
122 ],
123 'ESO15-TB': [
124 ['get_weekly_energy'],
125 ['get_monthly_energy'],
126 ['get_yearly_energy']
127 ]
128 }
129
130 def test_details(self, setup_entry, method):
131 """Test the device details API request and response.
132
133 This method is automatically parametrized by `pytest_generate_tests`
134 based on class variables `device` (name of device type - outlets),
135 device name (outlets) list of device types.
136
137 Example:
138 >>> device = 'outlets'
139 >>> outlets = ['ESW01-USA', 'ESW01-EU', 'ESW01-AU']
140
141 See Also
142 --------
143 `utils.TestBase` class docstring
144 `call_json_outlets` module docstring
145
146 Notes
147 ------
148 The device is instantiated using the `call_json.DeviceList.device_list_item()`
149 method. The device details contain the default values set in `utils.Defaults`
150 """ # Get response for device details
151 details_response = call_json_outlets.DETAILS_RESPONSES[setup_entry]
152 if callable(details_response):
153 response_dict = details_response()
154 else:
155 response_dict = details_response
156 self.mock_api.return_value = response_dict, 200
157 # Get device configuration
158 outlet_obj = self.get_device("outlets", setup_entry)
159 assert isinstance(outlet_obj, VeSyncOutlet)
160
161 # Call get_details() directly
162 method_call = getattr(outlet_obj, method)
163 self.run_in_loop(method_call)
164
165 # Parse arguments from mock_api call into dictionary
166 all_kwargs = parse_args(self.mock_api)
167
168 # Set both write_api and overwrite to True to update YAML files
169 assert assert_test(
170 method_call,
171 all_kwargs,
172 setup_entry,
173 write_api=self.write_api,
174 overwrite=self.overwrite,
175 )
176
177 # Test bad responses
178 self.mock_api.reset_mock()
179 if setup_entry == 'wifi-switch-1.3':
180 self.mock_api.return_value = (None, 400)
181 else:
182 self.mock_api.return_value = call_json.DETAILS_BADCODE, 200
183 self.run_in_loop(outlet_obj.get_details)
184 assert 'details' in self.caplog.text
185
186 def test_methods(self, setup_entry: str, method):
187 """Test device methods API request and response.
188
189 This method is automatically parametrized by `pytest_generate_tests`
190 based on class variables `device` (name of device type - outlets),
191 device name (outlets) list of device types, `base_methods` - list of
192 methods for all devices, and `device_methods` - list of methods for
193 each device type.
194
195 Example:
196 >>> base_methods = [['turn_on'], ['turn_off'], ['update']]
197 >>> device_methods = {
198 'dev_type': [['method1'], ['method2', {'kwargs': 'value'}]]
199 }
200
201 Notes
202 -----
203 The response can be a callable that accepts the `kwargs` argument to
204 sync the device response with the API response. In some cases the API
205 returns data from the method call, such as `get_yearly_energy`, in other cases the
206 API returns a simple confirmation the command was successful.
207
208 See Also
209 --------
210 `TestBase` class method
211 `call_json_outlets` module
212
213 """ # Get method name and kwargs from method fixture
214 method_name = method[0]
215 if len(method) == 2 and isinstance(method[1], dict):
216 method_kwargs = method[1]
217 else:
218 method_kwargs = {}
219
220 # Set return value for call_api based on METHOD_RESPONSES
221 method_response = call_json_outlets.METHOD_RESPONSES[setup_entry][method_name]
222 if callable(method_response):
223 if method_kwargs:
224 resp_dict = method_response(**method_kwargs)
225 else:
226 resp_dict = method_response()
227 else:
228 resp_dict = method_response
229 self.mock_api.return_value = resp_dict, 200
230 # Get device configuration
231
232 outlet_obj = self.get_device("outlets", setup_entry)
233 assert isinstance(outlet_obj, VeSyncOutlet)
234
235 # Get method from device object
236 method_call = getattr(outlet_obj, method[0])
237
238 # Ensure method runs based on device configuration
239 if method[0] == 'turn_on':
240 outlet_obj.state.device_status = const.DeviceStatus.OFF
241 elif method[0] == 'turn_off':
242 outlet_obj.state.device_status = const.DeviceStatus.ON
243
244 # Call method with kwargs if present
245 if method_kwargs:
246 self.run_in_loop(method_call, **method_kwargs)
247 else:
248 self.run_in_loop(method_call)
249
250 # Parse arguments from mock_api call into dictionary
251 all_kwargs = parse_args(self.mock_api)
252
253 # Assert request matches recorded request or write new records
254 assert assert_test(
255 method_call, all_kwargs, setup_entry, self.write_api, self.overwrite
256 )
257
258 # Test bad responses
259 self.mock_api.reset_mock()
260 if setup_entry == 'wifi-switch-1.3':
261 self.mock_api.return_value = (None, 400)
262 else:
263 self.mock_api.return_value = call_json.DETAILS_BADCODE, 200
264 if method[0] == 'turn_on':
265 outlet_obj.state.device_status = const.DeviceStatus.OFF
266 if method[0] == 'turn_off':
267 outlet_obj.state.device_status = const.DeviceStatus.ON
268 if 'energy' in method[0]:
269 return
270 bad_return = self.run_in_loop(method_call)
271 assert bad_return is False
272
273 @pytest.mark.parametrize('setup_entry', [d for d in OUTLET_DEV_TYPES])
274 def test_power(self, setup_entry):
275 """Test outlets power history methods."""
276 outlet_obj = self.get_device("outlets", setup_entry)
277 assert isinstance(outlet_obj, VeSyncOutlet)
278 if not outlet_obj.supports_energy:
279 pytest.skip(f"{setup_entry} does not support energy monitoring.")
280
281 self.mock_api.side_effect = [
282 (dict(call_json_outlets.METHOD_RESPONSES[setup_entry]['get_weekly_energy']), 200),
283 (dict(call_json_outlets.METHOD_RESPONSES[setup_entry]['get_monthly_energy']), 200),
284 (dict(call_json_outlets.METHOD_RESPONSES[setup_entry]['get_yearly_energy']), 200),
285
286 ]
287
288 self.run_in_loop(outlet_obj.update_energy)
289 assert self.mock_api.call_count == 3
290 assert outlet_obj.state.weekly_history is not None
291 assert outlet_obj.state.monthly_history is not None
292 assert outlet_obj.state.yearly_history is not None
293 self.mock_api.reset_mock()
294 if setup_entry == 'wifi-switch-1.3':
295 self.mock_api.return_value = (None, 400)
296 else:
297 self.mock_api.return_value = call_json.DETAILS_BADCODE, 200