/
/
/
1"""Helper functions for nicovideo tests."""
2
3from __future__ import annotations
4
5from typing import TYPE_CHECKING, TypeVar
6from unittest.mock import Mock
7
8from music_assistant.providers.nicovideo.converters.manager import NicovideoConverterManager
9from tests.providers.nicovideo.types import JsonDict
10
11if TYPE_CHECKING:
12 from mashumaro import DataClassDictMixin
13 from pydantic import JsonValue
14
15T = TypeVar("T")
16
17
18def create_converter_manager() -> NicovideoConverterManager:
19 """Create a NicovideoConverterManager for testing."""
20 # Create mock provider
21 mock_provider = Mock()
22 mock_provider.instance_id = "nicovideo_test"
23 mock_provider.domain = "nicovideo"
24
25 # Create mock logger
26 mock_logger = Mock()
27
28 return NicovideoConverterManager(mock_provider, mock_logger)
29
30
31def sort_dict_keys_and_lists(obj: JsonValue) -> JsonValue:
32 """
33 Sort dictionary keys and list elements for consistent snapshot comparison.
34
35 This function ensures deterministic ordering by:
36 - Sorting dictionary keys alphabetically
37 - Sorting list elements by type and string representation
38
39 Particularly useful for handling serialized sets that would otherwise have
40 random ordering between test runs.
41 """
42 if isinstance(obj, dict):
43 # Sort dictionary keys and recursively process values
44 return {key: sort_dict_keys_and_lists(obj[key]) for key in sorted(obj.keys())}
45 if isinstance(obj, list):
46 # Recursively process list items first
47 sorted_items = [sort_dict_keys_and_lists(item) for item in obj]
48 try:
49 # Sort items for deterministic ordering (handles serialized sets)
50 return sorted(sorted_items, key=lambda x: (type(x).__name__, str(x)))
51 except TypeError, ValueError:
52 # If sorting fails, return in original order
53 return sorted_items
54 else:
55 # Return primitive values as-is
56 return obj
57
58
59def to_dict_for_snapshot(media_item: DataClassDictMixin) -> JsonDict:
60 """Convert DataClassDictMixin to dict with sorted keys and lists for snapshot comparison."""
61 # Get the standard to_dict representation
62 item_dict = media_item.to_dict()
63
64 # Recursively sort all nested structures, especially sets
65 sorted_result = sort_dict_keys_and_lists(item_dict)
66
67 # Ensure we return the expected dict type
68 assert isinstance(sorted_result, dict)
69 return sorted_result
70