Debian Codegraph @

test/library/test_migrations.py

raw
1 import os
2 import textwrap
3 from pathlib import Path
4 from typing import ClassVar
5
6 import pytest
7
8 from beets.dbcore import types
9 from beets.library import Album, Item, migrations
10 from beets.test.helper import TestHelper
11 from beets.util import cached_classproperty, path_as_posix
12
13 Migration = tuple[
14 type[migrations.Migration], tuple[type[Item] | type[Album], ...]
15 ]
16
17
18 class MigrationTestHelper(TestHelper):
19 """Provide a shared harness for exercising one library migration at a time.
20
21 The helper builds a library that starts in a pre-migration state, then
22 re-enables the migration under test so each subclass can verify the data
23 transformation in isolation.
24 """
25
26 migration: ClassVar[Migration]
27
28 @classmethod
29 def setup_previous_state(cls, monkeypatch: pytest.MonkeyPatch) -> None:
30 """Shape the library into the legacy state expected by the migration.
31
32 Subclasses override this hook to create older schema or metadata
33 layouts before the test library is initialized.
34 """
35
36 @pytest.fixture(autouse=True)
37 def setup(self, monkeypatch):
38 """Initialize the test library around the migration under test.
39
40 The fixture first prevents automatic migrations so legacy test data can
41 be created safely, then restores the target migration and tears down the
42 temporary library after each test.
43 """
44 # do not apply migrations upon library initialization
45 monkeypatch.setattr("beets.library.library.Library._migrations", ())
46 self.setup_previous_state(monkeypatch)
47
48 self.setup_beets()
49
50 # and now configure the migrations to be tested
51 monkeypatch.setattr(
52 "beets.library.library.Library._migrations", (self.migration,)
53 )
54 try:
55 yield
56 finally:
57 self.teardown_beets()
58
59
60 class TestMultiGenreFieldMigration(MigrationTestHelper):
61 """Verify legacy single-value genres are promoted to multi-value fields."""
62
63 migration = (migrations.MultiGenreFieldMigration, (Item, Album))
64
65 @classmethod
66 def setup_previous_state(cls, monkeypatch: pytest.MonkeyPatch) -> None:
67 """Expose the legacy genre columns required to exercise the migration."""
68 # add genre field to both models to make sure this column is created
69 monkeypatch.setattr(
70 "beets.library.models.Item._fields",
71 {**Item._fields, "genre": types.STRING},
72 )
73 monkeypatch.setattr(
74 "beets.library.models.Album._fields",
75 {**Album._fields, "genre": types.STRING},
76 )
77 monkeypatch.setattr(
78 "beets.library.models.Album.item_keys", {*Album.item_keys, "genre"}
79 )
80
81 def test_migrate(self):
82 """Ensure genre data is split once and preserved when already populated."""
83 self.config["lastgenre"]["separator"] = " - "
84
85 expected_item_genres = []
86 for genre, initial_genres, expected_genres in [
87 # already existing value is not overwritten
88 ("Item Rock", ("Ignored",), ("Ignored",)),
89 ("", (), ()),
90 ("Rock", (), ("Rock",)),
91 # multiple genres are split on one of default separators
92 ("Item Rock; Alternative", (), ("Item Rock", "Alternative")),
93 # multiple genres are split the first (lastgenre) separator ONLY
94 ("Item - Rock, Alternative", (), ("Item", "Rock, Alternative")),
95 ]:
96 self.add_item(genre=genre, genres=initial_genres)
97 expected_item_genres.append(expected_genres)
98
99 unmigrated_album = self.add_album(
100 genre="Album Rock / Alternative", genres=[]
101 )
102 expected_item_genres.append(("Album Rock", "Alternative"))
103
104 self.lib._migrate()
105
106 actual_item_genres = [tuple(i.genres) for i in self.lib.items()]
107 assert actual_item_genres == expected_item_genres
108
109 unmigrated_album.load()
110 assert unmigrated_album.genres == ["Album Rock", "Alternative"]
111
112 # remove cached initial db tables data
113 del self.lib.db_tables
114 assert self.lib.migration_exists("multi_genre_field", "items")
115 assert self.lib.migration_exists("multi_genre_field", "albums")
116
117
118 class MultiArtistFieldMigrationTestMixin(MigrationTestHelper):
119 """Share coverage for migrations that split artist-like text into lists."""
120
121 str_field: ClassVar[str]
122 list_field: ClassVar[str]
123 migration_cls: ClassVar[type[migrations.MultiValueFieldMigration]]
124
125 @cached_classproperty
126 def migration(cls) -> Migration:
127 """Bind each concrete test class to its corresponding migration."""
128 return (cls.migration_cls, (Item,))
129
130 @classmethod
131 def setup_previous_state(cls, monkeypatch: pytest.MonkeyPatch) -> None:
132 """Expose the legacy scalar field expected by the migration."""
133 # add legacy str field to make sure this column is created
134 monkeypatch.setattr(
135 "beets.library.models.Item._fields",
136 {**Item._fields, cls.str_field: types.STRING},
137 )
138
139 def test_migrate(self):
140 """Ensure existing list values win and legacy text splits consistently."""
141 expected_list_values = []
142 for str_value, initial_list_value, expected_list_value in [
143 # already existing value is not overwritten
144 ("Artist", ("Ignored",), ("Ignored",)),
145 ("", (), ()),
146 ("Artist", (), ("Artist",)),
147 # multiple values are split on one of separators
148 ("Artist; Another Artist", (), ("Artist", "Another Artist")),
149 # multiple values are split by the existing separator ONLY
150 ("Artist, Another; Artist", (), ("Artist, Another", "Artist")),
151 ]:
152 data = {
153 self.str_field: str_value,
154 self.list_field: initial_list_value,
155 }
156 self.add_item(**data)
157 expected_list_values.append(expected_list_value)
158
159 self.lib._migrate()
160
161 actual_list_values = [
162 tuple(i[self.list_field]) for i in self.lib.items()
163 ]
164 assert actual_list_values == expected_list_values
165
166 # remove cached initial db tables data
167 del self.lib.db_tables
168 assert self.lib.migration_exists(
169 f"multi_{self.str_field}_field", "items"
170 )
171
172
173 class TestMultiRemixerFieldMigration(MultiArtistFieldMigrationTestMixin):
174 str_field = "remixer"
175 list_field = "remixers"
176 migration_cls = migrations.MultiRemixerFieldMigration
177
178
179 class TestMultiLyricistFieldMigration(MultiArtistFieldMigrationTestMixin):
180 str_field = "lyricist"
181 list_field = "lyricists"
182 migration_cls = migrations.MultiLyricistFieldMigration
183
184
185 class TestMultiComposerFieldMigration(MultiArtistFieldMigrationTestMixin):
186 str_field = "composer"
187 list_field = "composers"
188 migration_cls = migrations.MultiComposerFieldMigration
189
190
191 class TestMultiArrangerFieldMigration(MultiArtistFieldMigrationTestMixin):
192 str_field = "arranger"
193 list_field = "arrangers"
194 migration_cls = migrations.MultiArrangerFieldMigration
195
196
197 class TestLyricsMetadataInFlexFieldsMigration(MigrationTestHelper):
198 """Verify embedded lyrics metadata moves into dedicated flexible fields."""
199
200 migration = (migrations.LyricsMetadataInFlexFieldsMigration, (Item,))
201
202 def test_migrate(self, is_importable):
203 """Ensure extracted metadata is preserved without mutating plain lyrics."""
204 lyrics_item = self.add_item(
205 lyrics=textwrap.dedent("""
206 [00:00.00] Some synced lyrics / Quelques paroles synchronisées
207 [00:00.50]
208 [00:01.00] Some more synced lyrics / Quelques paroles plus synchronisées
209
210 Source: https://lrclib.net/api/1/""")
211 )
212 instrumental_lyrics_item = self.add_item(lyrics="[Instrumental]")
213
214 self.lib._migrate()
215
216 lyrics_item.load()
217
218 assert lyrics_item.lyrics == textwrap.dedent(
219 """
220 [00:00.00] Some synced lyrics / Quelques paroles synchronisées
221 [00:00.50]
222 [00:01.00] Some more synced lyrics / Quelques paroles plus synchronisées"""
223 )
224 assert lyrics_item.lyrics_backend == "lrclib"
225 assert lyrics_item.lyrics_url == "https://lrclib.net/api/1/"
226
227 if is_importable("langdetect"):
228 assert lyrics_item.lyrics_language == "EN"
229 assert lyrics_item.lyrics_translation_language == "FR"
230 else:
231 with pytest.raises(AttributeError):
232 instrumental_lyrics_item.lyrics_language
233 with pytest.raises(AttributeError):
234 instrumental_lyrics_item.lyrics_translation_language
235
236 with pytest.raises(AttributeError):
237 instrumental_lyrics_item.lyrics_backend
238 with pytest.raises(AttributeError):
239 instrumental_lyrics_item.lyrics_url
240 with pytest.raises(AttributeError):
241 instrumental_lyrics_item.lyrics_language
242 with pytest.raises(AttributeError):
243 instrumental_lyrics_item.lyrics_translation_language
244
245 # remove cached initial db tables data
246 del self.lib.db_tables
247 assert self.lib.migration_exists(
248 "lyrics_metadata_in_flex_fields", "items"
249 )
250
251
252 class TestRemoveInheritedArtpathMigration(MigrationTestHelper):
253 """Verify inherited artpath flex attributes are removed from items."""
254
255 migration = (migrations.RemoveInheritedArtpathMigration, (Item,))
256
257 def test_migrate(self):
258 """Ensure the inherited artpath flex attribute is removed from items."""
259 item = self.add_item(artpath="/abs/path/to/cover.jpg")
260
261 self.lib._migrate()
262
263 item.load()
264 with pytest.raises(AttributeError):
265 item.artpath
266
267 # remove cached initial db tables data
268 del self.lib.db_tables
269 assert self.lib.migration_exists("remove_inherited_artpath", "items")
270
271
272 class TestRelativePathMigration(MigrationTestHelper):
273 """Verify stored item paths are rewritten to library-relative values."""
274
275 migration = (migrations.RelativePathMigration, (Item,))
276
277 def test_migrate(self):
278 """Ensure stored paths become relative while the public API stays stable."""
279 relative_path = str(Path("foo") / "bar" / "baz.mp3")
280 abs_string_path = str(self.lib_path / relative_path)
281 abs_bytes_path = os.fsencode(abs_string_path)
282
283 # need to insert the path directly into the database to bypass the path setter
284 self.lib._connection().executemany(
285 "INSERT INTO items (id, path) VALUES (?, ?)",
286 (
287 (1, abs_bytes_path),
288 # add a string path to ensure the migration handles it
289 (2, abs_string_path),
290 ),
291 )
292 old_stored_path = (
293 self.lib._connection()
294 .execute("select path from items where id=?", (1,))
295 .fetchone()[0]
296 )
297 assert old_stored_path == abs_bytes_path
298
299 self.lib._migrate()
300
301 item = self.lib.get_item(1)
302 assert item
303
304 # and now we have a relative path
305 stored_path = (
306 self.lib._connection()
307 .execute("select path from items where id=?", (item.id,))
308 .fetchone()[0]
309 )
310 assert stored_path == path_as_posix(os.fsencode(relative_path))
311 # and the item.path property still returns an absolute path
312 assert item.path == abs_bytes_path
313
314 # also check the string path was migrated correctly
315 str_item = self.lib.get_item(2)
316 assert str_item
317 assert str_item.path == abs_bytes_path
318
319
320 class TestMigrationBackup(MigrationTestHelper):
321 """Tests for the backup-before-migration feature."""
322
323 migration = (migrations.LyricsMetadataInFlexFieldsMigration, (Item,))
324 db_on_disk = True
325
326 @classmethod
327 def setup_previous_state(cls, monkeypatch):
328 monkeypatch.setattr(
329 "beets.library.models.Item._fields",
330 {**Item._fields, "lyrics": types.STRING},
331 )
332
333 @pytest.mark.parametrize(
334 "config_value, expected_count", [(True, 1), (False, 0)]
335 )
336 def test_backup_config(self, config_value, expected_count):
337 self.config["create_backup_before_migrations"] = config_value
338 self.add_item(lyrics="some lyrics")
339 db_path = self.lib.path
340
341 self.lib._migrate()
342
343 backups = [
344 f
345 for f in db_path.parent.iterdir()
346 if os.fsdecode(f).endswith(".bak")
347 ]
348 assert len(backups) == expected_count
349
350
351 class TestInstrumentalLyricsInFlexFieldMigration(MigrationTestHelper):
352 """Verify legacy instrumental markers move out of canonical lyrics."""
353
354 migration = (migrations.InstrumentalLyricsInFlexFieldMigration, (Item,))
355
356 def test_migrate(self):
357 """Ensure exact instrumental markers become metadata, not lyric text."""
358 instrumental_item = self.add_item(lyrics="[Instrumental]")
359 regular_item = self.add_item(lyrics="Regular lyrics")
360
361 self.lib._migrate()
362
363 instrumental_item.load()
364 regular_item.load()
365
366 assert instrumental_item.lyrics == ""
367 assert instrumental_item.lyrics_instrumental == "1"
368 assert regular_item.lyrics == "Regular lyrics"
369
370 with pytest.raises(AttributeError, match="lyrics_instrumental"):
371 regular_item.lyrics_instrumental
372
373 # remove cached initial db tables data
374 del self.lib.db_tables
375 assert self.lib.migration_exists(
376 "instrumental_lyrics_in_flex_field", "items"
377 )