Debian Codegraph @

test/plugins/test_random.py

raw
1 """Test the beets.random utilities associated with the random plugin."""
2
3 import math
4 import random
5
6 import pytest
7
8 from beetsplug.random import _equal_chance_permutation, random_objs
9
10
11 @pytest.fixture(scope="class")
12 def helper(class_helper):
13 """Use class scope because each random test class owns its item list.
14
15 The helper creates lightweight item objects for class setup; tests do not
16 need a fresh beets temp dir per method or shared state between classes.
17 """
18 return class_helper
19
20
21 @pytest.fixture(scope="module", autouse=True)
22 def seed_random():
23 random.seed(12345)
24
25
26 class TestEqualChancePermutation:
27 """Test the _equal_chance_permutation function."""
28
29 @pytest.fixture(autouse=True)
30 def setup(self, helper):
31 """Set up the test environment with items."""
32 self.lib = helper.lib
33 self.artist1 = "Artist 1"
34 self.artist2 = "Artist 2"
35 self.item1 = helper.create_item(artist=self.artist1)
36 self.item2 = helper.create_item(artist=self.artist2)
37 self.items = [self.item1, self.item2]
38 for _ in range(8):
39 self.items.append(helper.create_item(artist=self.artist2))
40
41 def _stats(self, data):
42 mean = sum(data) / len(data)
43 stdev = math.sqrt(sum((p - mean) ** 2 for p in data) / (len(data) - 1))
44 quot, rem = divmod(len(data), 2)
45 if rem:
46 median = sorted(data)[quot]
47 else:
48 median = sum(sorted(data)[quot - 1 : quot + 1]) / 2
49 return mean, stdev, median
50
51 def test_equal_permutation(self):
52 """We have a list of items where only one item is from artist1 and the
53 rest are from artist2. If we permute weighted by the artist field then
54 the solo track will almost always end up near the start. If we use a
55 different field then it'll be in the middle on average.
56 """
57
58 def experiment(field, histogram=False):
59 """Permutes the list of items 500 times and calculates the position
60 of self.item1 each time. Returns stats about that position.
61 """
62 positions = []
63 for _ in range(500):
64 shuffled = list(
65 _equal_chance_permutation(self.items, field=field)
66 )
67 positions.append(shuffled.index(self.item1))
68 # Print a histogram (useful for debugging).
69 if histogram:
70 for i in range(len(self.items)):
71 print(f"{i:2d} {'*' * positions.count(i)}")
72 return self._stats(positions)
73
74 _, stdev1, median1 = experiment("artist")
75 _, stdev2, median2 = experiment("track")
76 assert 0 == pytest.approx(median1, abs=1)
77 assert len(self.items) // 2 == pytest.approx(median2, abs=1)
78 assert stdev2 > stdev1
79
80 @pytest.mark.parametrize(
81 "input_items, field, expected",
82 [
83 ([], "artist", []),
84 ([{"artist": "Artist 1"}], "artist", [{"artist": "Artist 1"}]),
85 # Missing field should not raise an error, but return empty
86 ([{"artist": "Artist 1"}], "nonexistent", []),
87 # Multiple items with the same field value
88 (
89 [{"artist": "Artist 1"}, {"artist": "Artist 1"}],
90 "artist",
91 [{"artist": "Artist 1"}, {"artist": "Artist 1"}],
92 ),
93 ],
94 )
95 def test_equal_permutation_items(
96 self, input_items, field, expected, helper
97 ):
98 """Test _equal_chance_permutation with empty input."""
99 result = list(
100 _equal_chance_permutation(
101 [helper.create_item(**i) for i in input_items], field
102 )
103 )
104
105 for item in expected:
106 for key, value in item.items():
107 assert any(getattr(r, key) == value for r in result)
108 assert len(result) == len(expected)
109
110
111 class TestRandomObjs:
112 """Test the random_objs function."""
113
114 @pytest.fixture(autouse=True)
115 def setup(self, helper):
116 """Set up the test environment with items."""
117 self.lib = helper.lib
118 self.artist1 = "Artist 1"
119 self.artist2 = "Artist 2"
120 self.items = [
121 helper.create_item(artist=self.artist1, length=180), # 3 minutes
122 helper.create_item(artist=self.artist2, length=240), # 4 minutes
123 helper.create_item(artist=self.artist2, length=300), # 5 minutes
124 ]
125
126 def test_random_selection_by_count(self):
127 """Test selecting a specific number of items."""
128 selected = list(random_objs(self.items, "artist", number=2))
129 assert len(selected) == 2
130 assert all(item in self.items for item in selected)
131
132 def test_random_selection_by_time(self):
133 """Test selecting items constrained by total time (minutes)."""
134 selected = list(
135 random_objs(self.items, "artist", time_minutes=6)
136 ) # 6 minutes
137 total_time = (
138 sum(item.length for item in selected) / 60
139 ) # Convert to minutes
140 assert total_time <= 6
141
142 def test_equal_chance_permutation(self, helper):
143 """Test equal chance permutation ensures balanced artist selection."""
144 # Add more items to make the test meaningful
145 for _ in range(5):
146 self.items.append(
147 helper.create_item(artist=self.artist1, length=180)
148 )
149
150 selected = list(
151 random_objs(self.items, "artist", number=10, equal_chance=True)
152 )
153 artist_counts = {}
154 for item in selected:
155 artist_counts[item.artist] = artist_counts.get(item.artist, 0) + 1
156
157 # Ensure both artists are represented (not strictly equal due to randomness)
158 assert len(artist_counts) >= 2
159
160 def test_empty_input_list(self):
161 """Test behavior with an empty input list."""
162 selected = list(random_objs([], "artist", number=1))
163 assert len(selected) == 0
164
165 def test_no_constraints_returns_all(self):
166 """Test that no constraints return all items in random order."""
167 selected = list(random_objs(self.items, "artist", number=3))
168 assert len(selected) == len(self.items)
169 assert set(selected) == set(self.items)