Debian Codegraph @

src/tests/test_purifiers.py

raw symbols SCIP
1 """
2 This tests requests for Air Purifiers.
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_fans` - Contains API responses
27 """
28
29 import logging
30 import pytest
31
32 import pyvesync.const as const
33 from pyvesync.base_devices.purifier_base import VeSyncPurifier
34 from base_test_cases import TestBase
35 from utils import assert_test, parse_args
36 import call_json_purifiers
37
38
39 logger = logging.getLogger(__name__)
40 logger.setLevel(logging.DEBUG)
41
42
43 class TestAirPurifiers(TestBase):
44 """Air Purifier testing class.
45
46 This class tests Air Purifier device details and methods.
47 The methods are parametrized from the class variables using
48 `pytest_generate_tests`. The call_json_fans module contains the responses
49 for the API requests. The device is instantiated from the details provided by
50 `call_json.DeviceList.device_list_item()`. Inherits from `utils.TestBase`.
51
52 Instance Attributes
53 -------------------
54 self.manager : VeSync
55 Instantiated VeSync object
56 self.mock_api : Mock
57 Mock with patched `helpers.call_api` method
58 self.caplog : LogCaptureFixture
59 Pytest fixture for capturing logs
60
61 Class Attributes
62 ---------------
63 device : str
64 Name of product class - air_purifiers
65 air_purifiers : list
66 List of setup_entry's for air purifiers, this variable is named
67 after the device variable value
68 base_methods : List[List[str, Dict[str, Any]]]
69 List of common methods for all devices
70 device_methods : Dict[List[List[str, Dict[str, Any]]]]
71 Dictionary of methods specific to device types
72
73 Methods
74 --------
75 test_details()
76 Test the device details API request and response
77 test_methods()
78 Test device methods API request and response
79
80 Examples
81 --------
82 >>> device = 'air_purifiers'
83 >>> air_purifiers = call_json_fans.AIR_MODELS
84 >>> base_methods = [['turn_on'], ['turn_off'], ['update']]
85 >>> device_methods = {
86 'ESWD16': [['method1'], ['method2', {'kwargs': 'value'}]]
87 }
88 """
89
90 device = "air_purifiers"
91 air_purifiers = call_json_purifiers.PURIFIER_MODELS
92 base_methods = [
93 ["turn_on"],
94 ["turn_off"],
95 ["set_sleep_mode"],
96 ["set_manual_mode"],
97 ["set_fan_speed", {"speed": 3}],
98 ]
99 # TODO: Add timer tests
100 device_methods = {
101 "Core200S": [["set_sleep_mode"],],
102 "Core300S": [["set_auto_mode"], ['set_sleep_mode'], ["turn_on_display"], ["turn_off_display"]],
103 "Core400S": [["set_auto_mode"], ['set_sleep_mode'], ["turn_on_display"], ["turn_off_display"]],
104 "Core600S": [["set_auto_mode"], ['set_sleep_mode'], ["turn_on_display"], ["turn_off_display"]],
105 "LV-PUR131S": [["set_auto_mode"], ['set_sleep_mode'], ["turn_on_display"], ["turn_off_display"]],
106 "LV-RH131S": [["set_auto_mode"], ['set_sleep_mode'], ["turn_on_display"], ["turn_off_display"]],
107 "LAP-V102S": [["set_auto_mode"], ['set_sleep_mode'], ['set_pet_mode'], ["turn_on_display"], ["turn_off_display"]],
108 "LAP-V201S": [["set_auto_mode"], ['set_sleep_mode'], ['set_pet_mode'], ["turn_on_display"], ["turn_off_display"]],
109 "EL551S": [["set_auto_mode"], ["set_sleep_mode"], ["set_turbo_mode"], ["turn_on_display"], ["turn_off_display"]],
110 "LAP-B851S-WUS": [["set_auto_mode"], ['set_sleep_mode'], ["turn_on_display"], ["turn_off_display"]],
111
112 }
113
114 def test_details(self, setup_entry, method):
115 """Test the device details API request and response.
116
117 This method is automatically parametrized by `pytest_generate_tests`
118 based on class variables `device` (name of product class - air_purifiers),
119 device name (air_purifiers) list of device types.
120
121 Example:
122 >>> device = 'air_purifiers'
123 >>> air_purifiers = call_json_fans.AIR_MODELS
124
125 See Also
126 --------
127 `utils.TestBase` class docstring
128 `call_json_fans` module docstring
129
130 Notes
131 ------
132 The device is instantiated using the `call_json.DeviceList.device_list_item()`
133 method. The device details contain the default values set in `utils.Defaults`
134 """
135 # Set return value for call_api based on call_json_fan.DETAILS_RESPONSES
136 return_dict = call_json_purifiers.DETAILS_RESPONSES[setup_entry]
137 return_val = (return_dict, 200)
138 self.mock_api.return_value = return_val
139
140 # Instantiate device from device list return item
141 fan_obj = self.get_device("air_purifiers", setup_entry)
142 assert isinstance(fan_obj, VeSyncPurifier)
143
144 method_call = getattr(fan_obj, method)
145 self.run_in_loop(method_call)
146
147 # Test state attributes
148 assert fan_obj.state.device_status == const.DeviceStatus.ON
149 assert fan_obj.state.mode == call_json_purifiers.PurifierDefaults.purifier_mode
150 assert fan_obj.state.fan_level == call_json_purifiers.PurifierDefaults.fan_level
151
152 # Parse mock_api args tuple from arg, kwargs to kwargs
153 all_kwargs = parse_args(self.mock_api)
154
155 # Assert request matches recorded request or write new records
156 assert assert_test(
157 method_call, all_kwargs, setup_entry, self.write_api, self.overwrite
158 )
159
160 def test_methods(self, setup_entry, method):
161 """Test device methods API request and response.
162
163 This method is automatically parametrized by `pytest_generate_tests`
164 based on class variables `device` (name of product class - air_purifiers),
165 device name (air_purifiers) list of setup_entry's, `base_methods` - list of
166 methods for all devices, and `device_methods` - list of methods for
167 each device type.
168
169 Example:
170 >>> base_methods = [['turn_on'], ['turn_off'], ['update']]
171 >>> device_methods = {
172 'setup_entry': [['method1'], ['method2', {'kwargs': 'value'}]]
173 }
174
175 Notes
176 -----
177 The response can be a callable that accepts the `kwargs` argument to
178 sync the device response with the API response. In some cases the API
179 returns data from the method call, such as `get_yearly_energy`, in other cases the
180 API returns a simple confirmation the command was successful.
181
182 See Also
183 --------
184 `TestBase` class method
185 `call_json_fans` module
186
187 """
188 # TODO: FIX `clear_timer` recorded API request in yaml
189 if method[0] == "clear_timer":
190 pytest.skip("Incorrect clear_timer API request")
191 # Get method name and kwargs from method fixture
192 method_name = method[0]
193 if len(method) == 2 and isinstance(method[1], dict):
194 method_kwargs = method[1]
195 else:
196 method_kwargs = {}
197
198 # Set return value for call_api based on call_json_fans.METHOD_RESPONSES
199 method_response = call_json_purifiers.METHOD_RESPONSES[setup_entry][method_name]
200 if callable(method_response):
201 if method_kwargs:
202 return_dict = method_response(method_kwargs)
203 else:
204 return_dict = method_response()
205 else:
206 return_dict = method_response
207 self.mock_api.return_value = (return_dict, 200)
208
209 # Get device configuration from call_json.DeviceList.device_list_item()
210 fan_obj = self.get_device("air_purifiers", setup_entry)
211 assert isinstance(fan_obj, VeSyncPurifier)
212
213 # Get method from device object
214 method_call = getattr(fan_obj, method_name)
215
216 # Ensure method runs based on device configuration
217 if method_name == "turn_on":
218 fan_obj.state.device_status = const.DeviceStatus.OFF
219 elif method_name == "turn_off":
220 fan_obj.state.device_status = const.DeviceStatus.ON
221 elif method_name == "set_fan_speed":
222 fan_obj.state.mode = const.PurifierModes.MANUAL
223 elif method_name in ["set_auto_mode", "set_sleep_mode", "set_pet_mode", "set_turbo_mode"]:
224 fan_obj.state.mode = const.PurifierModes.MANUAL
225 elif method_name == "set_manual_mode":
226 fan_obj.state.mode = const.PurifierModes.AUTO
227 elif method_name in ["turn_on_display"]:
228 fan_obj.state.display_set_status = const.DeviceStatus.OFF
229 elif method_name in ["turn_off_display"]:
230 fan_obj.state.display_set_status = const.DeviceStatus.ON
231
232 # Call method with kwargs if defined
233 if method_kwargs:
234 self.run_in_loop(method_call, **method_kwargs)
235 else:
236 self.run_in_loop(method_call)
237
238 if method_name == "turn_on":
239 assert fan_obj.state.device_status == const.DeviceStatus.ON
240 elif method_name == "turn_off":
241 assert fan_obj.state.device_status == const.DeviceStatus.OFF
242 elif method_name == "set_fan_speed":
243 assert fan_obj.state.fan_level == method_kwargs["speed"]
244 elif method_name in ["set_auto_mode"]:
245 assert fan_obj.state.mode == const.PurifierModes.AUTO
246 elif method_name in ["set_sleep_mode"]:
247 assert fan_obj.state.mode == const.PurifierModes.SLEEP
248 elif method_name in ["set_pet_mode"]:
249 assert fan_obj.state.mode == const.PurifierModes.PET
250 elif method_name in ["set_turbo_mode"]:
251 assert fan_obj.state.mode == const.PurifierModes.TURBO
252 elif method_name in ["turn_on_display"]:
253 assert fan_obj.state.display_set_status == const.DeviceStatus.ON
254 elif method_name in ["turn_off_display"]:
255 assert fan_obj.state.display_set_status == const.DeviceStatus.OFF
256
257 # Parse arguments from mock_api call into a dictionary
258 all_kwargs = parse_args(self.mock_api)
259
260 # Assert request matches recorded request or write new records
261 assert assert_test(
262 method_call, all_kwargs, setup_entry, self.write_api, self.overwrite
263 )