Debian Codegraph @

src/tests/test_fans.py

raw symbols SCIP
1 """
2 This tests requests for FANS (not purifiers or humidifiers).
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 from dataclasses import asdict
31 import pyvesync.const as const
32 from pyvesync.base_devices.fan_base import VeSyncFanBase
33 from base_test_cases import TestBase
34 from utils import assert_test, parse_args
35 from defaults import TestDefaults
36 import call_json_fans
37
38
39 logger = logging.getLogger(__name__)
40 logger.setLevel(logging.DEBUG)
41
42 DEFAULT_COLOR = TestDefaults.color
43 DEFAULT_COLOR_RGB = dict(asdict(DEFAULT_COLOR.rgb))
44 DEFAULT_COLOR_HSV = dict(asdict(DEFAULT_COLOR.hsv))
45
46
47 class TestFans(TestBase):
48 """Fan testing class.
49
50 This class tests Fan product details and methods. The methods are
51 parametrized from the class variables using `pytest_generate_tests`.
52 The call_json_fans module contains the responses for the API requests.
53 The device is instantiated from the details provided by
54 `call_json.DeviceList.device_list_item()`. Inherits from `utils.TestBase`.
55
56 Instance Attributes
57 -------------------
58 self.manager : VeSync
59 Instantiated VeSync object
60 self.mock_api : Mock
61 Mock with patched `helpers.call_api` method
62 self.caplog : LogCaptureFixture
63 Pytest fixture for capturing logs
64
65 Class Variables
66 ---------------
67 device : str
68 Name of product class - humidifiers
69 humidifers : list
70 List of setup_entry's for humidifiers, this variable is named
71 after the device variable value
72 base_methods : List[List[str, Dict[str, Any]]]
73 List of common methods for all devices
74 device_methods : Dict[List[List[str, Dict[str, Any]]]]
75 Dictionary of methods specific to device types
76
77 Methods
78 --------
79 test_details()
80 Test the device details API request and response
81 test_methods()
82 Test device methods API request and response
83
84 Examples
85 --------
86 >>> device = 'fans'
87 >>> fans = call_json_fans.FAN_MODELS
88 >>> base_methods = [['turn_on'], ['turn_off'], ['update']]
89 >>> device_methods = {
90 'ESWD16': [['method1'], ['method2', {'kwargs': 'value'}]]
91 }
92
93 """
94
95 device = 'fans'
96 fans = call_json_fans.FANS
97 base_methods = [['turn_on'], ['turn_off'], ['set_fan_speed', {'speed': 3}],]
98 device_methods = {
99 "LTF-F422S": [
100 ["turn_off_oscillation",],
101 ["turn_off_mute",],
102 ],
103 "LPF-R423S": [
104 ["turn_off_vertical_oscillation",],
105 ["turn_off_horizontal_oscillation",],
106 ["set_horizontal_oscillation_range", {"left": 10, "right": 80}],
107 ["set_vertical_oscillation_range", {"top": 100, "bottom": 20}],
108 ],
109 }
110
111 def test_details(self, setup_entry, method):
112 """Test the device details API request and response.
113
114 This method is automatically parametrized by `pytest_generate_tests`
115 based on class variables `device` (name of product class - fans),
116 device name (fans) list of setup_entry's.
117
118 Example:
119 >>> device = 'air_purifiers'
120 >>> air_purifiers = call_json_fans.AIR_MODELS
121
122 See Also
123 --------
124 `utils.TestBase` class docstring
125 `call_json_fans` module docstring
126
127 Notes
128 ------
129 The device is instantiated using the `call_json.DeviceList.device_list_item()`
130 method. The device details contain the default values set in `utils.Defaults`
131 """
132 # Set return value for call_api based on call_json_fan.DETAILS_RESPONSES
133 return_dict = call_json_fans.DETAILS_RESPONSES[setup_entry]
134 self.mock_api.return_value = (return_dict, 200)
135
136 # Instantiate device from device list return item
137 fan_obj = self.get_device("fans", setup_entry)
138 assert isinstance(fan_obj, VeSyncFanBase)
139
140 method_call = getattr(fan_obj, method)
141 self.run_in_loop(method_call)
142
143 # Parse mock_api args tuple from arg, kwargs to kwargs
144 all_kwargs = parse_args(self.mock_api)
145
146 # Assert state is set correctly
147 assert fan_obj.state.device_status == call_json_fans.FanDefaults.fan_status
148 assert fan_obj.state.display_set_status == call_json_fans.FanDefaults.screen_status
149 if fan_obj.supports_oscillation:
150 assert fan_obj.state.oscillation_status == call_json_fans.FanDefaults.oscillation_status
151
152 if fan_obj.supports_horizontal_oscillation:
153 assert fan_obj.state.horizontal_oscillation_status == call_json_fans.FanDefaults.oscillation_horizontal
154 if fan_obj.supports_vertical_oscillation:
155 assert fan_obj.state.vertical_oscillation_status == call_json_fans.FanDefaults.oscillation_vertical
156 if fan_obj.supports_mute:
157 assert fan_obj.state.mute_status == call_json_fans.FanDefaults.mute_status
158
159 # Assert request matches recorded request or write new records
160 assert assert_test(
161 method_call, all_kwargs, setup_entry, self.write_api, self.overwrite
162 )
163
164 def test_methods(self, setup_entry, method):
165 """Test device methods API request and response.
166
167 This method is automatically parametrized by `pytest_generate_tests`
168 based on class variables `device` (name of product class - humidifiers),
169 device name (humidifiers) list of setup_entry's, `base_methods` - list of
170 methods for all devices, and `device_methods` - list of methods for
171 each device type.
172
173 Example:
174 >>> base_methods = [['turn_on'], ['turn_off'], ['update']]
175 >>> device_methods = {
176 'setup_entry': [['method1'], ['method2', {'kwargs': 'value'}]]
177 }
178
179 Notes
180 -----
181 The response can be a callable that accepts the `kwargs` argument to
182 sync the device response with the API response. In some cases the API
183 returns data from the method call, such as `get_yearly_energy`, in other cases the
184 API returns a simple confirmation the command was successful.
185
186 See Also
187 --------
188 `TestBase` class method
189 `call_json_fans` module
190
191 """
192 # Get method name and kwargs from method fixture
193 method_name = method[0]
194 if len(method) == 2 and isinstance(method[1], dict):
195 method_kwargs = method[1]
196 else:
197 method_kwargs = {}
198
199 # Set return value for call_api based on call_json_fans.METHOD_RESPONSES
200 method_response = call_json_fans.METHOD_RESPONSES[setup_entry][method_name]
201 if callable(method_response):
202 if method_kwargs:
203 self.mock_api.return_value = method_response(method_kwargs), 200
204 else:
205 self.mock_api.return_value = method_response(), 200
206 else:
207 self.mock_api.return_value = method_response, 200
208
209 # Get device configuration from call_json.DeviceList.device_list_item()
210 fan_obj = self.get_device("fans", setup_entry)
211 assert isinstance(fan_obj, VeSyncFanBase)
212
213 # Get method from device object
214 method_call = getattr(fan_obj, method[0])
215
216 # Ensure method runs based on device configuration
217 if method[0] == 'turn_on':
218 fan_obj.state.device_status = const.DeviceStatus.OFF
219 elif method[0] == 'turn_off':
220 fan_obj.state.device_status = const.DeviceStatus.ON
221
222 # Call method with kwargs if defined
223 if method_kwargs:
224 self.run_in_loop(method_call, **method_kwargs)
225 else:
226 self.run_in_loop(method_call)
227
228 # Parse arguments from mock_api call into a dictionary
229 all_kwargs = parse_args(self.mock_api)
230
231 # Assert request matches recorded request or write new records
232 assert assert_test(
233 method_call, all_kwargs, setup_entry, self.write_api, self.overwrite
234 )