File: test_edit.py

package info (click to toggle)
beets 2.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,016 kB
  • sloc: python: 46,429; javascript: 8,018; xml: 334; sh: 261; makefile: 125
file content (465 lines) | stat: -rw-r--r-- 16,888 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# This file is part of beets.
# Copyright 2016, Adrian Sampson and Diego Moreda.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

import codecs
from unittest.mock import patch

from beets.dbcore.query import TrueQuery
from beets.library import Item
from beets.test import _common
from beets.test.helper import (
    AutotagImportTestCase,
    AutotagStub,
    BeetsTestCase,
    PluginMixin,
    TerminalImportMixin,
    control_stdin,
)


class ModifyFileMocker:
    """Helper for modifying a file, replacing or editing its contents. Used for
    mocking the calls to the external editor during testing.
    """

    def __init__(self, contents=None, replacements=None):
        """`self.contents` and `self.replacements` are initialized here, in
        order to keep the rest of the functions of this class with the same
        signature as `EditPlugin.get_editor()`, making mocking easier.
            - `contents`: string with the contents of the file to be used for
            `overwrite_contents()`
            - `replacement`: dict with the in-place replacements to be used for
            `replace_contents()`, in the form {'previous string': 'new string'}

        TODO: check if it can be solved more elegantly with a decorator
        """
        self.contents = contents
        self.replacements = replacements
        self.action = self.overwrite_contents
        if replacements:
            self.action = self.replace_contents

    # The two methods below mock the `edit` utility function in the plugin.

    def overwrite_contents(self, filename, log):
        """Modify `filename`, replacing its contents with `self.contents`. If
        `self.contents` is empty, the file remains unchanged.
        """
        if self.contents:
            with codecs.open(filename, "w", encoding="utf-8") as f:
                f.write(self.contents)

    def replace_contents(self, filename, log):
        """Modify `filename`, reading its contents and replacing the strings
        specified in `self.replacements`.
        """
        with codecs.open(filename, "r", encoding="utf-8") as f:
            contents = f.read()
        for old, new_ in self.replacements.items():
            contents = contents.replace(old, new_)
        with codecs.open(filename, "w", encoding="utf-8") as f:
            f.write(contents)


class EditMixin(PluginMixin):
    """Helper containing some common functionality used for the Edit tests."""

    plugin = "edit"

    def assertItemFieldsModified(
        self, library_items, items, fields=[], allowed=["path"]
    ):
        """Assert that items in the library (`lib_items`) have different values
        on the specified `fields` (and *only* on those fields), compared to
        `items`.

        An empty `fields` list results in asserting that no modifications have
        been performed. `allowed` is a list of field changes that are ignored
        (they may or may not have changed; the assertion doesn't care).
        """
        for lib_item, item in zip(library_items, items):
            diff_fields = [
                field
                for field in lib_item._fields
                if lib_item[field] != item[field]
            ]
            assert set(diff_fields).difference(allowed) == set(fields)

    def run_mocked_interpreter(self, modify_file_args={}, stdin=[]):
        """Run the edit command during an import session, with mocked stdin and
        yaml writing.
        """
        m = ModifyFileMocker(**modify_file_args)
        with patch("beetsplug.edit.edit", side_effect=m.action):
            with control_stdin("\n".join(stdin)):
                self.importer.run()

    def run_mocked_command(self, modify_file_args={}, stdin=[], args=[]):
        """Run the edit command, with mocked stdin and yaml writing, and
        passing `args` to `run_command`."""
        m = ModifyFileMocker(**modify_file_args)
        with patch("beetsplug.edit.edit", side_effect=m.action):
            with control_stdin("\n".join(stdin)):
                self.run_command("edit", *args)


@_common.slow_test()
@patch("beets.library.Item.write")
class EditCommandTest(EditMixin, BeetsTestCase):
    """Black box tests for `beetsplug.edit`. Command line interaction is
    simulated using `test.helper.control_stdin()`, and yaml editing via an
    external editor is simulated using `ModifyFileMocker`.
    """

    ALBUM_COUNT = 1
    TRACK_COUNT = 10

    def setUp(self):
        super().setUp()
        # Add an album, storing the original fields for comparison.
        self.album = self.add_album_fixture(track_count=self.TRACK_COUNT)
        self.album_orig = {f: self.album[f] for f in self.album._fields}
        self.items_orig = [
            {f: item[f] for f in item._fields} for item in self.album.items()
        ]

    def test_title_edit_discard(self, mock_write):
        """Edit title for all items in the library, then discard changes."""
        # Edit track titles.
        self.run_mocked_command(
            {"replacements": {"t\u00eftle": "modified t\u00eftle"}},
            # Cancel.
            ["c"],
        )

        assert mock_write.call_count == 0
        self.assertItemFieldsModified(self.album.items(), self.items_orig, [])

    def test_title_edit_apply(self, mock_write):
        """Edit title for all items in the library, then apply changes."""
        # Edit track titles.
        self.run_mocked_command(
            {"replacements": {"t\u00eftle": "modified t\u00eftle"}},
            # Apply changes.
            ["a"],
        )

        assert mock_write.call_count == self.TRACK_COUNT
        self.assertItemFieldsModified(
            self.album.items(), self.items_orig, ["title", "mtime"]
        )

    def test_single_title_edit_apply(self, mock_write):
        """Edit title for one item in the library, then apply changes."""
        # Edit one track title.
        self.run_mocked_command(
            {"replacements": {"t\u00eftle 9": "modified t\u00eftle 9"}},
            # Apply changes.
            ["a"],
        )

        assert mock_write.call_count == 1
        # No changes except on last item.
        self.assertItemFieldsModified(
            list(self.album.items())[:-1], self.items_orig[:-1], []
        )
        assert list(self.album.items())[-1].title == "modified t\u00eftle 9"

    def test_noedit(self, mock_write):
        """Do not edit anything."""
        # Do not edit anything.
        self.run_mocked_command(
            {"contents": None},
            # No stdin.
            [],
        )

        assert mock_write.call_count == 0
        self.assertItemFieldsModified(self.album.items(), self.items_orig, [])

    def test_album_edit_apply(self, mock_write):
        """Edit the album field for all items in the library, apply changes.
        By design, the album should not be updated.""
        """
        # Edit album.
        self.run_mocked_command(
            {"replacements": {"\u00e4lbum": "modified \u00e4lbum"}},
            # Apply changes.
            ["a"],
        )

        assert mock_write.call_count == self.TRACK_COUNT
        self.assertItemFieldsModified(
            self.album.items(), self.items_orig, ["album", "mtime"]
        )
        # Ensure album is *not* modified.
        self.album.load()
        assert self.album.album == "\u00e4lbum"

    def test_single_edit_add_field(self, mock_write):
        """Edit the yaml file appending an extra field to the first item, then
        apply changes."""
        # Append "foo: bar" to item with id == 2. ("id: 1" would match both
        # "id: 1" and "id: 10")
        self.run_mocked_command(
            {"replacements": {"id: 2": "id: 2\nfoo: bar"}},
            # Apply changes.
            ["a"],
        )

        assert self.lib.items("id:2")[0].foo == "bar"
        # Even though a flexible attribute was written (which is not directly
        # written to the tags), write should still be called since templates
        # might use it.
        assert mock_write.call_count == 1

    def test_a_album_edit_apply(self, mock_write):
        """Album query (-a), edit album field, apply changes."""
        self.run_mocked_command(
            {"replacements": {"\u00e4lbum": "modified \u00e4lbum"}},
            # Apply changes.
            ["a"],
            args=["-a"],
        )

        self.album.load()
        assert mock_write.call_count == self.TRACK_COUNT
        assert self.album.album == "modified \u00e4lbum"
        self.assertItemFieldsModified(
            self.album.items(), self.items_orig, ["album", "mtime"]
        )

    def test_a_albumartist_edit_apply(self, mock_write):
        """Album query (-a), edit albumartist field, apply changes."""
        self.run_mocked_command(
            {"replacements": {"album artist": "modified album artist"}},
            # Apply changes.
            ["a"],
            args=["-a"],
        )

        self.album.load()
        assert mock_write.call_count == self.TRACK_COUNT
        assert self.album.albumartist == "the modified album artist"
        self.assertItemFieldsModified(
            self.album.items(), self.items_orig, ["albumartist", "mtime"]
        )

    def test_malformed_yaml(self, mock_write):
        """Edit the yaml file incorrectly (resulting in a malformed yaml
        document)."""
        # Edit the yaml file to an invalid file.
        self.run_mocked_command(
            {"contents": "!MALFORMED"},
            # Edit again to fix? No.
            ["n"],
        )

        assert mock_write.call_count == 0

    def test_invalid_yaml(self, mock_write):
        """Edit the yaml file incorrectly (resulting in a well-formed but
        invalid yaml document)."""
        # Edit the yaml file to an invalid but parseable file.
        self.run_mocked_command(
            {"contents": "wellformed: yes, but invalid"},
            # No stdin.
            [],
        )

        assert mock_write.call_count == 0


@_common.slow_test()
class EditDuringImporterTestCase(
    EditMixin, TerminalImportMixin, AutotagImportTestCase
):
    """TODO"""

    matching = AutotagStub.GOOD

    IGNORED = ["added", "album_id", "id", "mtime", "path"]

    def setUp(self):
        super().setUp()
        # Create some mediafiles, and store them for comparison.
        self.prepare_album_for_import(1)
        self.items_orig = [Item.from_path(f.path) for f in self.import_media]


@_common.slow_test()
class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
    def setUp(self):
        super().setUp()
        self.importer = self.setup_importer()

    def test_edit_apply_asis(self):
        """Edit the album field for all items in the library, apply changes,
        using the original item tags.
        """
        # Edit track titles.
        self.run_mocked_interpreter(
            {"replacements": {"Tag Track": "Edited Track"}},
            # eDit, Apply changes.
            ["d", "a"],
        )

        # Check that only the 'title' field is modified.
        self.assertItemFieldsModified(
            self.lib.items(),
            self.items_orig,
            ["title"],
            self.IGNORED
            + [
                "albumartist",
                "mb_albumartistid",
                "mb_albumartistids",
            ],
        )
        assert all("Edited Track" in i.title for i in self.lib.items())

        # Ensure album is *not* fetched from a candidate.
        assert self.lib.albums()[0].mb_albumid == ""

    def test_edit_discard_asis(self):
        """Edit the album field for all items in the library, discard changes,
        using the original item tags.
        """
        # Edit track titles.
        self.run_mocked_interpreter(
            {"replacements": {"Tag Track": "Edited Track"}},
            # eDit, Cancel, Use as-is.
            ["d", "c", "u"],
        )

        # Check that nothing is modified, the album is imported ASIS.
        self.assertItemFieldsModified(
            self.lib.items(),
            self.items_orig,
            [],
            self.IGNORED + ["albumartist", "mb_albumartistid"],
        )
        assert all("Tag Track" in i.title for i in self.lib.items())

        # Ensure album is *not* fetched from a candidate.
        assert self.lib.albums()[0].mb_albumid == ""

    def test_edit_apply_candidate(self):
        """Edit the album field for all items in the library, apply changes,
        using a candidate.
        """
        # Edit track titles.
        self.run_mocked_interpreter(
            {"replacements": {"Applied Track": "Edited Track"}},
            # edit Candidates, 1, Apply changes.
            ["c", "1", "a"],
        )

        # Check that 'title' field is modified, and other fields come from
        # the candidate.
        assert all("Edited Track " in i.title for i in self.lib.items())
        assert all("match " in i.mb_trackid for i in self.lib.items())

        # Ensure album is fetched from a candidate.
        assert "albumid" in self.lib.albums()[0].mb_albumid

    def test_edit_retag_apply(self):
        """Import the album using a candidate, then retag and edit and apply
        changes.
        """
        self.run_mocked_interpreter(
            {},
            # 1, Apply changes.
            ["1", "a"],
        )

        # Retag and edit track titles.  On retag, the importer will reset items
        # ids but not the db connections.
        self.importer.paths = []
        self.importer.query = TrueQuery()
        self.run_mocked_interpreter(
            {"replacements": {"Applied Track": "Edited Track"}},
            # eDit, Apply changes.
            ["d", "a"],
        )

        # Check that 'title' field is modified, and other fields come from
        # the candidate.
        assert all("Edited Track " in i.title for i in self.lib.items())
        assert all("match " in i.mb_trackid for i in self.lib.items())

        # Ensure album is fetched from a candidate.
        assert "albumid" in self.lib.albums()[0].mb_albumid

    def test_edit_discard_candidate(self):
        """Edit the album field for all items in the library, discard changes,
        using a candidate.
        """
        # Edit track titles.
        self.run_mocked_interpreter(
            {"replacements": {"Applied Track": "Edited Track"}},
            # edit Candidates, 1, Apply changes.
            ["c", "1", "a"],
        )

        # Check that 'title' field is modified, and other fields come from
        # the candidate.
        assert all("Edited Track " in i.title for i in self.lib.items())
        assert all("match " in i.mb_trackid for i in self.lib.items())

        # Ensure album is fetched from a candidate.
        assert "albumid" in self.lib.albums()[0].mb_albumid

    def test_edit_apply_candidate_singleton(self):
        """Edit the album field for all items in the library, apply changes,
        using a candidate and singleton mode.
        """
        # Edit track titles.
        self.run_mocked_interpreter(
            {"replacements": {"Applied Track": "Edited Track"}},
            # edit Candidates, 1, Apply changes, aBort.
            ["c", "1", "a", "b"],
        )

        # Check that 'title' field is modified, and other fields come from
        # the candidate.
        assert all("Edited Track " in i.title for i in self.lib.items())
        assert all("match " in i.mb_trackid for i in self.lib.items())


@_common.slow_test()
class EditDuringImporterSingletonTest(EditDuringImporterTestCase):
    def setUp(self):
        super().setUp()
        self.importer = self.setup_singleton_importer()

    def test_edit_apply_asis_singleton(self):
        """Edit the album field for all items in the library, apply changes,
        using the original item tags and singleton mode.
        """
        # Edit track titles.
        self.run_mocked_interpreter(
            {"replacements": {"Tag Track": "Edited Track"}},
            # eDit, Apply changes, aBort.
            ["d", "a", "b"],
        )

        # Check that only the 'title' field is modified.
        self.assertItemFieldsModified(
            self.lib.items(),
            self.items_orig,
            ["title"],
            self.IGNORED + ["albumartist", "mb_albumartistid"],
        )
        assert all("Edited Track" in i.title for i in self.lib.items())