| 1 |
"""Common base class for tests and Default values. |
| 2 |
|
| 3 |
Routine Listings |
| 4 |
---------------- |
| 5 |
|
| 6 |
TestBase: class |
| 7 |
Base class for tests to start mock & instantiat VS object |
| 8 |
parse_args: function |
| 9 |
Parse arguments from mock API call |
| 10 |
assert_test: function |
| 11 |
Test pyvesync API calls against existing API |
| 12 |
""" |
| 13 |
from itertools import zip_longest |
| 14 |
import logging |
| 15 |
from pathlib import Path |
| 16 |
from typing import Any |
| 17 |
import yaml |
| 18 |
import orjson |
| 19 |
from mashumaro.mixins.orjson import DataClassORJSONMixin |
| 20 |
from defaults import CALL_API_ARGS, ID_KEYS, API_DEFAULTS |
| 21 |
|
| 22 |
logger = logging.getLogger(__name__) |
| 23 |
|
| 24 |
_SENTINEL = object() |
| 25 |
|
| 26 |
|
| 27 |
class YAMLWriter: |
| 28 |
"""Read and Write API request data to YAML files. |
| 29 |
|
| 30 |
Arguments |
| 31 |
--------- |
| 32 |
module : str |
| 33 |
name of module that is being tested |
| 34 |
dev_type : str |
| 35 |
device type being tested |
| 36 |
|
| 37 |
Attributes |
| 38 |
---------- |
| 39 |
self.file_path : Path |
| 40 |
Path to YAML directory, default to API dir in tests folder |
| 41 |
self.file : Path |
| 42 |
Path to YAML file based on device type and module |
| 43 |
self.existings_yaml : dict |
| 44 |
Existing YAML data read to dict object |
| 45 |
self._existing_api : dict, optional |
| 46 |
Existing data dict of a specific API call |
| 47 |
|
| 48 |
Methods |
| 49 |
------- |
| 50 |
self.existing_api() |
| 51 |
Return existing data dict of a specific API call or None |
| 52 |
self.write_api(api, data, overwrite=False) |
| 53 |
Writes data to YAML file for a specific API call, |
| 54 |
set overwrite=True to overwrite existing data |
| 55 |
|
| 56 |
""" |
| 57 |
|
| 58 |
def __init__(self, module, dev_type): |
| 59 |
"""Init the YAMLWriter class. |
| 60 |
|
| 61 |
Arguments |
| 62 |
---------- |
| 63 |
module : str |
| 64 |
name of module that is being tested |
| 65 |
dev_type : str |
| 66 |
device type being tested |
| 67 |
""" |
| 68 |
self.file_path = self._get_path(module) |
| 69 |
self.file = Path.joinpath(self.file_path, dev_type + '.yaml') |
| 70 |
self.new_file = self._new_file() |
| 71 |
self.existing_yaml = self._get_existing_yaml() |
| 72 |
self._existing_api = None |
| 73 |
|
| 74 |
@staticmethod |
| 75 |
def _get_path(module) -> Path: |
| 76 |
yaml_dir = Path.joinpath(Path(__file__).parent, 'api', module) |
| 77 |
if not yaml_dir.exists(): |
| 78 |
yaml_dir.mkdir(parents=True) |
| 79 |
return yaml_dir |
| 80 |
|
| 81 |
def _new_file(self) -> bool: |
| 82 |
if not self.file.exists(): |
| 83 |
logger.debug(f'Creating new file {self.file}') |
| 84 |
self.file.touch() |
| 85 |
return True |
| 86 |
return False |
| 87 |
|
| 88 |
def _get_existing_yaml(self) -> Any: |
| 89 |
if self.new_file: |
| 90 |
return None |
| 91 |
with open(self.file, 'rb') as f: |
| 92 |
data = yaml.full_load(f) |
| 93 |
return data |
| 94 |
|
| 95 |
def existing_api(self, method) -> bool: |
| 96 |
"""Check YAML file for existing data for API call. |
| 97 |
|
| 98 |
Arguments |
| 99 |
---------- |
| 100 |
method : str |
| 101 |
Name of method being tested |
| 102 |
|
| 103 |
Returns |
| 104 |
------- |
| 105 |
dict or None |
| 106 |
Existing data for API call or None |
| 107 |
""" |
| 108 |
if self.existing_yaml is not None: |
| 109 |
current_dict = self.existing_yaml.get(method) |
| 110 |
self._existing_api = current_dict |
| 111 |
if current_dict is not None: |
| 112 |
logger.debug(f'API call {method} already exists in {self.file}') |
| 113 |
return True |
| 114 |
return False |
| 115 |
|
| 116 |
def write_api(self, method, yaml_dict, overwrite=False): |
| 117 |
"""Write API data to YAML file. |
| 118 |
|
| 119 |
Arguments |
| 120 |
---------- |
| 121 |
method : str |
| 122 |
Name of method being tested |
| 123 |
yaml_dict : dict |
| 124 |
Data to write to YAML file |
| 125 |
overwrite : bool, optional |
| 126 |
Overwrite existing data, default to False |
| 127 |
""" |
| 128 |
if self.existing_yaml is not None: |
| 129 |
current_dict = self.existing_yaml.get(method) |
| 130 |
if current_dict is not None and overwrite is False: |
| 131 |
logger.debug(f'API call {method} already exists in {self.file}') |
| 132 |
return |
| 133 |
self.existing_yaml[method] = yaml_dict |
| 134 |
else: |
| 135 |
self.existing_yaml = {method: yaml_dict} |
| 136 |
with open(self.file, 'w', encoding='utf-8') as f: |
| 137 |
yaml.dump(dict(sorted(self.existing_yaml.items())), f, encoding='utf-8') |
| 138 |
|
| 139 |
|
| 140 |
def api_scrub(api_dict, device_type=None): |
| 141 |
"""Recursive function to scrub all sensitive data from API call. |
| 142 |
|
| 143 |
Arguments |
| 144 |
---------- |
| 145 |
api_dict : dict |
| 146 |
API call data to scrub |
| 147 |
device_type : str, optional |
| 148 |
Device type to use for default values |
| 149 |
|
| 150 |
Returns |
| 151 |
------- |
| 152 |
dict |
| 153 |
Scrubbed API call data |
| 154 |
""" |
| 155 |
def id_cleaner(key, value): |
| 156 |
if key.upper() in ID_KEYS: |
| 157 |
return f"{device_type or 'UNKNOWN'}-{key.upper()}" |
| 158 |
if key in API_DEFAULTS: |
| 159 |
return API_DEFAULTS[key] |
| 160 |
return value |
| 161 |
|
| 162 |
def nested_dict_iter(nested, mapper, last_key=None): |
| 163 |
if isinstance(nested, dict): |
| 164 |
if nested.get('deviceType') is not None: |
| 165 |
nonlocal device_type |
| 166 |
device_type = nested['deviceType'] |
| 167 |
out = {} |
| 168 |
for key, value in nested.items(): |
| 169 |
out[key] = nested_dict_iter(value, mapper, key) |
| 170 |
return out |
| 171 |
|
| 172 |
if isinstance(nested, list): |
| 173 |
return [nested_dict_iter(el, mapper, last_key) for el in nested] |
| 174 |
if not last_key: |
| 175 |
return nested |
| 176 |
return mapper(last_key, nested) |
| 177 |
return nested_dict_iter(api_dict, id_cleaner) |
| 178 |
|
| 179 |
|
| 180 |
def parse_args(mock_api): |
| 181 |
"""Parse arguments from mock API call. |
| 182 |
|
| 183 |
Arguments |
| 184 |
---------- |
| 185 |
mock_api : mock |
| 186 |
Mock object used to path call_api() method |
| 187 |
|
| 188 |
Returns |
| 189 |
------- |
| 190 |
dict |
| 191 |
dictionary of all call_api() arguments |
| 192 |
""" |
| 193 |
call_args = mock_api.call_args.args |
| 194 |
call_kwargs = mock_api.call_args.kwargs |
| 195 |
all_kwargs = dict(zip(CALL_API_ARGS, call_args)) |
| 196 |
all_kwargs.update(call_kwargs) |
| 197 |
if isinstance(all_kwargs.get("json_object"), DataClassORJSONMixin): |
| 198 |
all_kwargs["json_object"] = orjson.loads(all_kwargs["json_object"].to_json()) |
| 199 |
elif isinstance(all_kwargs.get("json_object"), dict): |
| 200 |
all_kwargs["json_object"] = orjson.loads(orjson.dumps(all_kwargs["json_object"])) |
| 201 |
return all_kwargs |
| 202 |
|
| 203 |
|
| 204 |
def assert_test(test_func, all_kwargs, dev_type=None, |
| 205 |
write_api=False, overwrite=False): |
| 206 |
"""Test pyvesync API calls against existing API. |
| 207 |
|
| 208 |
Set `write_api=True` to True to write API call data to YAML file. |
| 209 |
This will not overwrite existing data unless overwrite is True. |
| 210 |
The overwrite argument is only used when API changes, defaults |
| 211 |
to false for development testing. `overwrite=True` and `write_api=True` |
| 212 |
need to both be set to overwrite existing data. |
| 213 |
|
| 214 |
Arguments |
| 215 |
---------- |
| 216 |
test_func : method |
| 217 |
Method that is being tested |
| 218 |
all_kwargs : dict |
| 219 |
Dictionary of call_api() arguments |
| 220 |
dev_type : str, optional |
| 221 |
Device type being tested |
| 222 |
write_api : bool, optional |
| 223 |
Write API call data to YAML file, default to False |
| 224 |
overwrite : bool, optional |
| 225 |
Overwrite existing data ONLY USE FOR CHANGING API, |
| 226 |
default to False. Must be set with `write_api=True` |
| 227 |
|
| 228 |
Returns |
| 229 |
------- |
| 230 |
bool |
| 231 |
True if test passes, False if test fails |
| 232 |
|
| 233 |
Asserts |
| 234 |
------- |
| 235 |
Asserts that the API call data matches the expected data |
| 236 |
""" |
| 237 |
if all_kwargs.get('json_object') is not None: |
| 238 |
all_kwargs['json_object'] = api_scrub(all_kwargs['json_object'], dev_type) |
| 239 |
if all_kwargs.get('headers') is not None: |
| 240 |
all_kwargs['headers'] = api_scrub(all_kwargs['headers'], dev_type) |
| 241 |
mod = test_func.__self__.__module__.split(".")[-1] |
| 242 |
if dev_type is None: |
| 243 |
cls_name = test_func.__self__.__class__.__name__ |
| 244 |
else: |
| 245 |
cls_name = dev_type |
| 246 |
method_name = test_func.__name__ |
| 247 |
writer = YAMLWriter(mod, cls_name) |
| 248 |
if overwrite is True and write_api is True: |
| 249 |
writer.write_api(method_name, all_kwargs, overwrite) |
| 250 |
return True |
| 251 |
if writer.existing_api(method_name) is False: |
| 252 |
logger.warning("No existing, API data for %s %s %s", mod, cls_name, method_name) |
| 253 |
if write_api is True: |
| 254 |
logger.debug("Writing API data for %s %s %s", mod, cls_name, method_name) |
| 255 |
writer.write_api(method_name, all_kwargs, overwrite) |
| 256 |
return True |
| 257 |
else: |
| 258 |
logger.debug("Not writing API data for %s %s %s", mod, cls_name, method_name) |
| 259 |
if writer._existing_api is None: |
| 260 |
return False |
| 261 |
assert writer._existing_api == all_kwargs, dicts_equal(writer._existing_api, all_kwargs) |
| 262 |
return True |
| 263 |
|
| 264 |
|
| 265 |
def deep_diff(a: Any, b: Any, path: str = ""): |
| 266 |
"""Yield dicts describing differences between two (possibly nested) values.""" |
| 267 |
if type(a) is not type(b): |
| 268 |
yield { |
| 269 |
"path": path, "change": "type", |
| 270 |
"from": a, "to": b, |
| 271 |
"from_type": type(a).__name__, "to_type": type(b).__name__, |
| 272 |
} |
| 273 |
return |
| 274 |
|
| 275 |
if isinstance(a, dict): |
| 276 |
keys = set(a) | set(b) |
| 277 |
for k in sorted(keys, key=str): |
| 278 |
p = f"{path}.{k}" if path else str(k) |
| 279 |
if k not in b: |
| 280 |
yield {"path": p, "change": "removed", "value": a[k]} |
| 281 |
elif k not in a: |
| 282 |
yield {"path": p, "change": "added", "value": b[k]} |
| 283 |
else: |
| 284 |
yield from deep_diff(a[k], b[k], p) |
| 285 |
|
| 286 |
elif isinstance(a, (list, tuple)): |
| 287 |
for i, (va, vb) in enumerate(zip_longest(a, b, fillvalue=_SENTINEL)): |
| 288 |
p = f"{path}[{i}]" |
| 289 |
if va is _SENTINEL: |
| 290 |
yield {"path": p, "change": "added", "value": vb} |
| 291 |
elif vb is _SENTINEL: |
| 292 |
yield {"path": p, "change": "removed", "value": va} |
| 293 |
else: |
| 294 |
yield from deep_diff(va, vb, p) |
| 295 |
|
| 296 |
elif isinstance(a, set): |
| 297 |
if a != b: |
| 298 |
|
| 299 |
added = sorted(b - a, key=repr) |
| 300 |
removed = sorted(a - b, key=repr) |
| 301 |
yield {"path": path, "change": "set", "added": added, "removed": removed} |
| 302 |
|
| 303 |
elif a != b: |
| 304 |
yield {"path": path, "change": "modified", "from": a, "to": b} |
| 305 |
|
| 306 |
|
| 307 |
def format_diffs(diffs) -> str: |
| 308 |
sym = {"added": "+", "removed": "-", "modified": "~", "type": "±", "set": "∈"} |
| 309 |
out = [] |
| 310 |
for d in diffs: |
| 311 |
p = d["path"] or "<root>" |
| 312 |
c = d["change"] |
| 313 |
if c in ("added", "removed"): |
| 314 |
out.append(f"{sym[c]} {p}: {d['value']!r}") |
| 315 |
elif c == "modified": |
| 316 |
out.append(f"{sym[c]} {p}: {d['from']!r} -> {d['to']!r}") |
| 317 |
elif c == "type": |
| 318 |
out.append(f"{sym[c]} {p}: {d['from_type']} -> {d['to_type']} " |
| 319 |
f"({d['from']!r} -> {d['to']!r})") |
| 320 |
elif c == "set": |
| 321 |
out.append(f"{sym[c]} {p}: +{d['added']!r} -{d['removed']!r}") |
| 322 |
return "\n".join(out) |
| 323 |
|
| 324 |
|
| 325 |
def dicts_equal(a: dict, b: dict, *, show_diff: bool = True): |
| 326 |
"""Return (equal_bool, diffs). Optionally print a readable diff.""" |
| 327 |
diffs = list(deep_diff(a, b)) |
| 328 |
if show_diff and diffs: |
| 329 |
|
| 330 |
return 'Differences found:\n' + format_diffs(diffs) |
| 331 |
return "No differences found" |
| 332 |
|
| 333 |
|
| 334 |
def print_dataclass(d: dict[str, Any]) -> None: |
| 335 |
"""Prints dataclass(es) from nested dictionary.""" |
| 336 |
def py_type(v: Any) -> str: |
| 337 |
if isinstance(v, bool): |
| 338 |
return "bool" |
| 339 |
if isinstance(v, int): |
| 340 |
return "int" |
| 341 |
if isinstance(v, float): |
| 342 |
return "float" |
| 343 |
if isinstance(v, str): |
| 344 |
return "str" |
| 345 |
if isinstance(v, list): |
| 346 |
return "list[Any]" |
| 347 |
if isinstance(v, dict): |
| 348 |
return "dict[str, Any]" |
| 349 |
return "Any" |
| 350 |
|
| 351 |
def make_class_name(prefix: str) -> str: |
| 352 |
parts = prefix.split("_") |
| 353 |
return "".join(p.capitalize() for p in parts if p) |
| 354 |
|
| 355 |
def print_dataclass(name: str, mapping: dict[str, Any]) -> None: |
| 356 |
print("@dataclass") |
| 357 |
print(f"class {name}:") |
| 358 |
if not mapping: |
| 359 |
print(" pass") |
| 360 |
return |
| 361 |
|
| 362 |
nested: list[tuple[str, dict[str, Any]]] = [] |
| 363 |
|
| 364 |
for key, value in mapping.items(): |
| 365 |
if isinstance(value, dict): |
| 366 |
nested_name = make_class_name(f"{name}_{key}") |
| 367 |
print(f" {key}: {nested_name}") |
| 368 |
nested.append((nested_name, value)) |
| 369 |
else: |
| 370 |
print(f" {key}: {py_type(value)}") |
| 371 |
|
| 372 |
for nested_name, nested_dict in nested: |
| 373 |
print() |
| 374 |
print_dataclass(nested_name, nested_dict) |
| 375 |
|
| 376 |
print_dataclass("LehB381s", d) |