Debian Codegraph @

test/dbcore/test_sort.py

raw
1 """Various tests for querying the library database."""
2
3 import pytest
4
5 import beets.library
6 from beets import util
7 from beets.dbcore import types
8 from beets.dbcore.query import TrueQuery
9 from beets.dbcore.sort import FixedFieldSort, SlowFieldSort
10 from beets.library import Album, Item
11 from beets.test import _common
12
13 _p = pytest.param
14
15
16 def abs_test_path(path: str) -> bytes:
17 return util.normpath(path)
18
19
20 @pytest.fixture(scope="class")
21 def helper(class_helper):
22 return class_helper
23
24
25 @pytest.fixture(scope="class")
26 def setup_library(request: pytest.FixtureRequest, helper):
27 album_ids = [
28 helper.lib.add(
29 Album(
30 id=id_,
31 album=album,
32 genres=genres,
33 year=year,
34 flex1=flex1,
35 flex2=flex2,
36 albumartist=albumartist,
37 artpath=abs_test_path(f"{id_}cover.jpg"),
38 )
39 )
40 for id_, album, genres, year, flex1, flex2, albumartist in (
41 [1, "Album A", ["Rock"], 2001, "Flex1-1", "Flex2-A", "Foo"],
42 [2, "Album B", ["Rock"], 2002, "Flex1-2", "Flex2-A", "Bar"],
43 [3, "Album C", ["Jazz"], 2005, "Flex1-1", "Flex2-B", "Baz"],
44 )
45 ]
46
47 for item in [
48 _common.item(
49 id=1,
50 title="first",
51 artist="One",
52 album="Album A",
53 year=2001,
54 flex1="Flex1-0",
55 flex2="Flex2-A",
56 album_id=album_ids[0],
57 path=abs_test_path("/path0.mp3"),
58 track=1,
59 ),
60 _common.item(
61 id=2,
62 title="second",
63 artist="Two",
64 album="Album A",
65 year=2002,
66 flex1="Flex1-1",
67 flex2="Flex2-A",
68 album_id=album_ids[0],
69 path=abs_test_path("/patH1.mp3"),
70 track=2,
71 ),
72 _common.item(
73 id=3,
74 title="third",
75 artist="Three",
76 album="Album B",
77 year=2003,
78 flex1="Flex1-2",
79 flex2="Flex1-B",
80 album_id=album_ids[1],
81 path=abs_test_path("/paTH2.mp3"),
82 track=3,
83 ),
84 _common.item(
85 id=4,
86 title="fourth",
87 artist="Three",
88 album="Album C",
89 year=2004,
90 flex1="Flex1-2",
91 flex2="Flex1-C",
92 album_id=album_ids[2],
93 path=abs_test_path("/PATH3.mp3"),
94 track=4,
95 ),
96 ]:
97 helper.lib.add(item)
98
99 request.cls.lib = helper.lib
100
101
102 @pytest.mark.usefixtures("setup_library")
103 class TestSort:
104 @pytest.mark.parametrize(
105 "model,query,expected_ids",
106 [
107 _p(Album, "year+", [1, 2, 3], id="fixed"),
108 _p(Album, "flex1-", [2, 1, 3], id="flex"),
109 _p(Album, "path+", [1, 2, 3], id="calculated"),
110 _p(Album, "year-", [3, 2, 1], id="fixed-desc"),
111 _p(Album, "genres+ album+", [3, 1, 2], id="multi-fixed-field"),
112 _p(Album, "flex2+ flex1+", [1, 2, 3], id="multi-flex-field"),
113 _p(Album, "path+ year+", [1, 2, 3], id="computed"),
114 _p(Album, "year+ path+", [1, 2, 3], id="computed-reverse"),
115 _p(Item, "flex2- flex1+", [1, 2, 4, 3], id="item-multi-flex-field"),
116 _p(Item, "artpath+", [1, 2, 3, 4], id="item-album-field"),
117 _p(Item, "artpath-", [4, 3, 1, 2], id="item-album-field-reverse"),
118 ],
119 )
120 def test_sort(self, model, query, expected_ids):
121 results = self.lib._fetch(model, query, None)
122 assert [r.id for r in results] == expected_ids
123
124 def test_sort_path_field(self):
125 results = self.lib.items("", FixedFieldSort("path", True))
126 expected_paths = [
127 b"/path0.mp3",
128 b"/patH1.mp3",
129 b"/paTH2.mp3",
130 b"/PATH3.mp3",
131 ]
132 expected_paths_with_prefix = list(map(util.normpath, expected_paths))
133 assert [i.path for i in results] == expected_paths_with_prefix
134
135 def test_config_defaults(self):
136 artists = [r.artist for r in self.lib.items()]
137 albumartists = [r.albumartist for r in self.lib.albums()]
138
139 assert artists == ["One", "Three", "Three", "Two"]
140 assert albumartists == ["Bar", "Baz", "Foo"]
141
142 def test_config_overrides(self, config):
143 config.set({"sort_item": "artist-", "sort_album": "albumartist-"})
144
145 artists = [r.artist for r in self.lib.items()]
146 albumartists = [r.albumartist for r in self.lib.albums()]
147
148 assert artists == ["Two", "Three", "Three", "One"]
149 assert albumartists == ["Foo", "Baz", "Bar"]
150
151
152 class TestCaseSensitivity:
153 """If case_insensitive is false, lower-case values should be placed
154 after all upper-case values. E.g., `Foo Qux bar`
155 """
156
157 @pytest.fixture(autouse=True, scope="class")
158 def setup(self, helper):
159 helper.lib.add(Album(album="album", albumartist="bar"))
160 helper.lib.add(Album(album="Album", albumartist="Bar"))
161 helper.add_item(artist="artist", flex1="flex1", track=10)
162 helper.add_item(artist="Artist", flex1="Flex1", track=2)
163
164 @pytest.mark.parametrize(
165 "getter,query,attr,expected_insensitive,expected_sensitive",
166 [
167 _p(
168 "items",
169 "artist+",
170 "artist",
171 ["artist", "Artist"],
172 ["Artist", "artist"],
173 id="smart-artist-case",
174 ),
175 _p(
176 "albums",
177 "album+",
178 "album",
179 ["album", "Album"],
180 ["Album", "album"],
181 id="fixed-field-case",
182 ),
183 _p(
184 "items",
185 "flex1+",
186 "flex1",
187 ["flex1", "Flex1"],
188 ["Flex1", "flex1"],
189 id="flex-field-case",
190 ),
191 ],
192 )
193 def test_text_field_case_sorting(
194 self,
195 config,
196 getter,
197 query,
198 attr,
199 expected_insensitive,
200 expected_sensitive,
201 helper,
202 ):
203 config["sort_case_insensitive"] = True
204 results = getattr(helper.lib, getter)(query)
205 assert [r[attr] for r in results] == expected_insensitive
206
207 config["sort_case_insensitive"] = False
208 results = getattr(helper.lib, getter)(query)
209 assert [r[attr] for r in results] == expected_sensitive
210
211 def test_case_sensitive_only_affects_text(self, config, helper):
212 config["sort_case_insensitive"] = True
213 results = helper.lib.items("track+")
214 # If the numerical values were sorted as strings,
215 # then ['10', '2'] would be valid.
216 assert [r.track for r in results] == [2, 10]
217
218
219 @pytest.mark.usefixtures("setup_library")
220 class TestNonExistingField:
221 """Test sorting by non-existing fields"""
222
223 @pytest.mark.parametrize(
224 "q", ["foo+", "foo-", "--", "-+", "+-", "++", "-foo-", "-foo+", "---"]
225 )
226 def test_non_existing_fields_not_fail(self, q):
227 expected_ids = [i.id for i in self.lib.items("foo+")]
228
229 actual_ids = [i.id for i in self.lib.items(q)]
230
231 assert actual_ids == expected_ids
232
233 def test_combined_non_existing_field(self):
234 expected_ids = [i.id for i in self.lib.items("id+")]
235
236 actual_ids = [i.id for i in self.lib.items("foo+ id+")]
237
238 assert actual_ids == expected_ids
239
240 def test_field_present_in_some_items(self, monkeypatch):
241 """Test ordering by an int-type field not present on all items."""
242 monkeypatch.setitem(Item._types, "myint", types.Integer())
243
244 lower_item, higher_item, *items_without_val = self.lib.items("id+")
245 for item, value in zip((lower_item, higher_item), (2, 10)):
246 item.myint = value
247 item.store()
248
249 null_values_ids = [i.id for i in items_without_val]
250
251 ids_asc = [i.id for i in self.lib.items("myint+ id+")]
252 ids_desc = [i.id for i in self.lib.items("myint- id+")]
253
254 assert ids_asc == [*null_values_ids, lower_item.id, higher_item.id]
255 assert ids_desc == [higher_item.id, lower_item.id, *null_values_ids]
256
257 @pytest.mark.parametrize(
258 "field_type,lower,higher",
259 [
260 _p(types.NullInteger(), 2, 10, id="null-integer"),
261 _p(types.NullFloat(), 2.5, 10.5, id="null-float"),
262 ],
263 )
264 def test_nullable_field_present_in_some_items(
265 self, monkeypatch, field_type, lower, higher
266 ):
267 """Ordering by a nullable-typed field (whose null value is ``None``)
268 that is present on only some items should not raise. See #3461.
269 """
270 monkeypatch.setitem(Item._types, "mynull", field_type)
271
272 lower_item, higher_item, *items_without_val = self.lib.items("id+")
273 for item, value in zip((lower_item, higher_item), (lower, higher)):
274 item.mynull = value
275 item.store()
276
277 null_values_ids = [i.id for i in items_without_val]
278
279 ids_asc = [i.id for i in self.lib.items("mynull+ id+")]
280 ids_desc = [i.id for i in self.lib.items("mynull- id+")]
281
282 assert ids_asc == [*null_values_ids, lower_item.id, higher_item.id]
283 assert ids_desc == [higher_item.id, lower_item.id, *null_values_ids]
284
285 def test_negation_interaction(self):
286 """Test the handling of negation and sorting together.
287
288 If a string ends with a sorting suffix, it takes precedence over the
289 NotQuery parsing.
290 """
291 query, sort = beets.library.parse_query_string(
292 "-bar+", beets.library.Item
293 )
294 assert len(query.subqueries) == 1
295 assert isinstance(query.subqueries[0], TrueQuery)
296 assert isinstance(sort, SlowFieldSort)
297 assert sort.field == "-bar"