Create PluginTestCase to dedupe plugin setup

This commit is contained in:
Šarūnas Nejus 2024-07-06 21:47:30 +01:00
parent 16cf8dd937
commit 432da560e4
No known key found for this signature in database
GPG key ID: DD28F6704DBE3435
30 changed files with 117 additions and 233 deletions

View file

@ -225,6 +225,7 @@ class TestHelper(_common.Assertions):
sure you call ``unload_plugins()`` afterwards. sure you call ``unload_plugins()`` afterwards.
""" """
# FIXME this should eventually be handled by a plugin manager # FIXME this should eventually be handled by a plugin manager
plugins = (self.plugin,) if hasattr(self, "plugin") else plugins
beets.config["plugins"] = plugins beets.config["plugins"] = plugins
beets.plugins.load_plugins(plugins) beets.plugins.load_plugins(plugins)
beets.plugins.find_plugins() beets.plugins.find_plugins()
@ -242,7 +243,7 @@ class TestHelper(_common.Assertions):
Album._queries.update(beets.plugins.named_queries(Album)) Album._queries.update(beets.plugins.named_queries(Album))
def unload_plugins(self): def unload_plugins(self):
"""Unload all plugins and remove the from the configuration.""" """Unload all plugins and remove them from the configuration."""
# FIXME this should eventually be handled by a plugin manager # FIXME this should eventually be handled by a plugin manager
beets.config["plugins"] = [] beets.config["plugins"] = []
beets.plugins._classes = set() beets.plugins._classes = set()
@ -532,6 +533,22 @@ class ItemInDBTestCase(BeetsTestCase):
self.i = _common.item(self.lib) self.i = _common.item(self.lib)
class PluginMixin:
plugin: ClassVar[str]
def setUp(self):
super().setUp()
self.load_plugins()
def tearDown(self):
super().tearDown()
self.unload_plugins()
class PluginTestCase(PluginMixin, BeetsTestCase):
pass
class ImportHelper: class ImportHelper:
"""Provides tools to setup a library, a directory containing files that are """Provides tools to setup a library, a directory containing files that are
to be imported and an import session. The class also provides stubs for the to be imported and an import session. The class also provides stubs for the

View file

@ -18,22 +18,13 @@
from typing import Sequence, Tuple from typing import Sequence, Tuple
from beets.autotag.mb import VARIOUS_ARTISTS_ID from beets.autotag.mb import VARIOUS_ARTISTS_ID
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beetsplug.albumtypes import AlbumTypesPlugin from beetsplug.albumtypes import AlbumTypesPlugin
class AlbumTypesPluginTest(BeetsTestCase): class AlbumTypesPluginTest(PluginTestCase):
"""Tests for albumtypes plugin.""" """Tests for albumtypes plugin."""
plugin = "albumtypes"
def setUp(self):
"""Set up tests."""
super().setUp()
self.load_plugins("albumtypes")
def tearDown(self):
"""Tear down tests."""
self.unload_plugins()
super().tearDown()
def test_renames_types(self): def test_renames_types(self):
"""Tests if the plugin correctly renames the specified types.""" """Tests if the plugin correctly renames the specified types."""

View file

@ -6,18 +6,18 @@
import unittest import unittest
from beets import logging from beets import logging
from beets.test.helper import BeetsTestCase, capture_stdout from beets.test.helper import PluginTestCase, capture_stdout
class BareascPluginTest(BeetsTestCase): class BareascPluginTest(PluginTestCase):
"""Test bare ASCII query matching.""" """Test bare ASCII query matching."""
plugin = "bareasc"
def setUp(self): def setUp(self):
"""Set up test environment for bare ASCII query matching.""" """Set up test environment for bare ASCII query matching."""
super().setUp() super().setUp()
self.log = logging.getLogger("beets.web") self.log = logging.getLogger("beets.web")
self.config["bareasc"]["prefix"] = "#" self.config["bareasc"]["prefix"] = "#"
self.load_plugins("bareasc")
# Add library elements. Note that self.lib.add overrides any "id=<n>" # Add library elements. Note that self.lib.add overrides any "id=<n>"
# and assigns the next free id number. # and assigns the next free id number.

View file

@ -450,7 +450,6 @@ class BeatportTest(BeetsTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("beatport")
# Set up 'album'. # Set up 'album'.
response_release = self._make_release_response() response_release = self._make_release_response()
@ -466,10 +465,6 @@ class BeatportTest(BeetsTestCase):
# Set up 'test_tracks' # Set up 'test_tracks'
self.test_tracks = self.test_album.items() self.test_tracks = self.test_album.items()
def tearDown(self):
self.unload_plugins()
super().tearDown()
def mk_test_album(self): def mk_test_album(self):
items = [_common.item() for _ in range(6)] items = [_common.item() for _ in range(6)]
for item in items: for item in items:
@ -627,7 +622,6 @@ class BeatportResponseEmptyTest(BeetsTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("beatport")
# Set up 'tracks'. # Set up 'tracks'.
self.response_tracks = self._make_tracks_response() self.response_tracks = self._make_tracks_response()
@ -636,10 +630,6 @@ class BeatportResponseEmptyTest(BeetsTestCase):
# Make alias to be congruent with class `BeatportTest`. # Make alias to be congruent with class `BeatportTest`.
self.test_tracks = self.response_tracks self.test_tracks = self.response_tracks
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_response_tracks_empty(self): def test_response_tracks_empty(self):
response_tracks = [] response_tracks = []
tracks = [beatport.BeatportTrack(t) for t in response_tracks] tracks = [beatport.BeatportTrack(t) for t in response_tracks]

View file

@ -23,7 +23,7 @@ from mediafile import MediaFile
from beets import util from beets import util
from beets.test import _common from beets.test import _common
from beets.test.helper import BeetsTestCase, capture_log, control_stdin from beets.test.helper import PluginTestCase, capture_log, control_stdin
from beets.util import bytestring_path, displayable_path from beets.util import bytestring_path, displayable_path
@ -84,8 +84,9 @@ class ConvertMixin:
) )
class ConvertTestCase(BeetsTestCase, ConvertMixin): class ConvertTestCase(ConvertMixin, PluginTestCase):
db_on_disk = True db_on_disk = True
plugin = "convert"
@_common.slow_test() @_common.slow_test()
@ -93,7 +94,6 @@ class ImportConvertTest(ConvertTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.importer = self.create_importer() self.importer = self.create_importer()
self.load_plugins("convert")
self.config["convert"] = { self.config["convert"] = {
"dest": os.path.join(self.temp_dir, b"convert"), "dest": os.path.join(self.temp_dir, b"convert"),
@ -104,10 +104,6 @@ class ImportConvertTest(ConvertTestCase):
"quiet": False, "quiet": False,
} }
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_import_converted(self): def test_import_converted(self):
self.importer.run() self.importer.run()
item = self.lib.items().get() item = self.lib.items().get()
@ -172,7 +168,6 @@ class ConvertCliTest(ConvertTestCase, ConvertCommand):
super().setUp() super().setUp()
self.album = self.add_album_fixture(ext="ogg") self.album = self.add_album_fixture(ext="ogg")
self.item = self.album.items()[0] self.item = self.album.items()[0]
self.load_plugins("convert")
self.convert_dest = bytestring_path( self.convert_dest = bytestring_path(
os.path.join(self.temp_dir, b"convert_dest") os.path.join(self.temp_dir, b"convert_dest")
@ -191,10 +186,6 @@ class ConvertCliTest(ConvertTestCase, ConvertCommand):
}, },
} }
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_convert(self): def test_convert(self):
with control_stdin("y"): with control_stdin("y"):
self.run_convert() self.run_convert()
@ -319,7 +310,6 @@ class NeverConvertLossyFilesTest(ConvertTestCase, ConvertCommand):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("convert")
self.convert_dest = os.path.join(self.temp_dir, b"convert_dest") self.convert_dest = os.path.join(self.temp_dir, b"convert_dest")
self.config["convert"] = { self.config["convert"] = {
@ -332,10 +322,6 @@ class NeverConvertLossyFilesTest(ConvertTestCase, ConvertCommand):
}, },
} }
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_transcode_from_lossless(self): def test_transcode_from_lossless(self):
[item] = self.add_item_fixtures(ext="flac") [item] = self.add_item_fixtures(ext="flac")
with control_stdin("y"): with control_stdin("y"):

View file

@ -21,8 +21,8 @@ from beets.library import Item
from beets.test import _common from beets.test import _common
from beets.test.helper import ( from beets.test.helper import (
AutotagStub, AutotagStub,
BeetsTestCase,
ImportTestCase, ImportTestCase,
PluginTestCase,
TerminalImportMixin, TerminalImportMixin,
control_stdin, control_stdin,
) )
@ -73,9 +73,11 @@ class ModifyFileMocker:
f.write(contents) f.write(contents)
class EditMixin: class EditMixin(PluginTestCase):
"""Helper containing some common functionality used for the Edit tests.""" """Helper containing some common functionality used for the Edit tests."""
plugin = "edit"
def assertItemFieldsModified( # noqa def assertItemFieldsModified( # noqa
self, library_items, items, fields=[], allowed=["path"] self, library_items, items, fields=[], allowed=["path"]
): ):
@ -115,7 +117,7 @@ class EditMixin:
@_common.slow_test() @_common.slow_test()
@patch("beets.library.Item.write") @patch("beets.library.Item.write")
class EditCommandTest(BeetsTestCase, EditMixin): class EditCommandTest(EditMixin):
"""Black box tests for `beetsplug.edit`. Command line interaction is """Black box tests for `beetsplug.edit`. Command line interaction is
simulated using `test.helper.control_stdin()`, and yaml editing via an simulated using `test.helper.control_stdin()`, and yaml editing via an
external editor is simulated using `ModifyFileMocker`. external editor is simulated using `ModifyFileMocker`.
@ -126,7 +128,6 @@ class EditCommandTest(BeetsTestCase, EditMixin):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("edit")
# Add an album, storing the original fields for comparison. # Add an album, storing the original fields for comparison.
self.album = self.add_album_fixture(track_count=self.TRACK_COUNT) 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.album_orig = {f: self.album[f] for f in self.album._fields}
@ -137,7 +138,6 @@ class EditCommandTest(BeetsTestCase, EditMixin):
def tearDown(self): def tearDown(self):
EditPlugin.listeners = None EditPlugin.listeners = None
super().tearDown() super().tearDown()
self.unload_plugins()
def assertCounts( # noqa def assertCounts( # noqa
self, self,
@ -331,7 +331,6 @@ class EditDuringImporterTestCase(
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("edit")
# Create some mediafiles, and store them for comparison. # Create some mediafiles, and store them for comparison.
self._create_import_dir(3) self._create_import_dir(3)
self.items_orig = [Item.from_path(f.path) for f in self.media_files] self.items_orig = [Item.from_path(f.path) for f in self.media_files]
@ -341,7 +340,6 @@ class EditDuringImporterTestCase(
def tearDown(self): def tearDown(self):
EditPlugin.listeners = None EditPlugin.listeners = None
self.unload_plugins()
super().tearDown() super().tearDown()
self.matcher.restore() self.matcher.restore()

View file

@ -24,7 +24,7 @@ from mediafile import MediaFile
from beets import art, config, logging, ui from beets import art, config, logging, ui
from beets.test import _common from beets.test import _common
from beets.test.helper import BeetsTestCase, FetchImageHelper from beets.test.helper import BeetsTestCase, FetchImageHelper, PluginMixin
from beets.util import bytestring_path, displayable_path, syspath from beets.util import bytestring_path, displayable_path, syspath
from beets.util.artresizer import ArtResizer from beets.util.artresizer import ArtResizer
@ -40,7 +40,8 @@ def require_artresizer_compare(test):
return wrapper return wrapper
class EmbedartCliTest(FetchImageHelper, BeetsTestCase): class EmbedartCliTest(PluginMixin, FetchImageHelper, BeetsTestCase):
plugin = "embedart"
small_artpath = os.path.join(_common.RSRC, b"image-2x3.jpg") small_artpath = os.path.join(_common.RSRC, b"image-2x3.jpg")
abbey_artpath = os.path.join(_common.RSRC, b"abbey.jpg") abbey_artpath = os.path.join(_common.RSRC, b"abbey.jpg")
abbey_similarpath = os.path.join(_common.RSRC, b"abbey-similar.jpg") abbey_similarpath = os.path.join(_common.RSRC, b"abbey-similar.jpg")
@ -49,7 +50,6 @@ class EmbedartCliTest(FetchImageHelper, BeetsTestCase):
def setUp(self): def setUp(self):
super().setUp() # Converter is threaded super().setUp() # Converter is threaded
self.io.install() self.io.install()
self.load_plugins("embedart")
def _setup_data(self, artpath=None): def _setup_data(self, artpath=None):
if not artpath: if not artpath:
@ -57,10 +57,6 @@ class EmbedartCliTest(FetchImageHelper, BeetsTestCase):
with open(syspath(artpath), "rb") as f: with open(syspath(artpath), "rb") as f:
self.image_data = f.read() self.image_data = f.read()
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_embed_art_from_file_with_yes_input(self): def test_embed_art_from_file_with_yes_input(self):
self._setup_data() self._setup_data()
album = self.add_album_fixture() album = self.add_album_fixture()

View file

@ -2,14 +2,15 @@ import unittest
import responses import responses
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beetsplug import embyupdate from beetsplug import embyupdate
class EmbyUpdateTest(BeetsTestCase): class EmbyUpdateTest(PluginTestCase):
plugin = "embyupdate"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("embyupdate")
self.config["emby"] = { self.config["emby"] = {
"host": "localhost", "host": "localhost",
@ -18,10 +19,6 @@ class EmbyUpdateTest(BeetsTestCase):
"password": "password", "password": "password",
} }
def tearDown(self):
super().tearDown()
self.unload_plugins()
def test_api_url_only_name(self): def test_api_url_only_name(self):
self.assertEqual( self.assertEqual(
embyupdate.api_url( embyupdate.api_url(

View file

@ -22,19 +22,16 @@ import unittest
from xml.etree import ElementTree from xml.etree import ElementTree
from xml.etree.ElementTree import Element from xml.etree.ElementTree import Element
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
class ExportPluginTest(BeetsTestCase): class ExportPluginTest(PluginTestCase):
plugin = "export"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("export")
self.test_values = {"title": "xtitle", "album": "xalbum"} self.test_values = {"title": "xtitle", "album": "xalbum"}
def tearDown(self):
self.unload_plugins()
super().tearDown()
def execute_command(self, format_type, artist): def execute_command(self, format_type, artist):
query = ",".join(self.test_values.keys()) query = ",".join(self.test_values.keys())
out = self.run_with_output( out = self.run_with_output(

View file

@ -19,22 +19,19 @@ import sys
import unittest import unittest
from beets import util from beets import util
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
class FetchartCliTest(BeetsTestCase): class FetchartCliTest(PluginTestCase):
plugin = "fetchart"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("fetchart")
self.config["fetchart"]["cover_names"] = "c\xc3\xb6ver.jpg" self.config["fetchart"]["cover_names"] = "c\xc3\xb6ver.jpg"
self.config["art_filename"] = "mycover" self.config["art_filename"] = "mycover"
self.album = self.add_album() self.album = self.add_album()
self.cover_path = os.path.join(self.album.path, b"mycover.jpg") self.cover_path = os.path.join(self.album.path, b"mycover.jpg")
def tearDown(self):
self.unload_plugins()
super().tearDown()
def check_cover_is_stored(self): def check_cover_is_stored(self):
self.assertEqual(self.album["artpath"], self.cover_path) self.assertEqual(self.album["artpath"], self.cover_path)
with open(util.syspath(self.cover_path)) as f: with open(util.syspath(self.cover_path)) as f:

View file

@ -17,19 +17,12 @@
import unittest import unittest
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beetsplug import ftintitle from beetsplug import ftintitle
class FtInTitlePluginFunctional(BeetsTestCase): class FtInTitlePluginFunctional(PluginTestCase):
def setUp(self): plugin = "ftintitle"
"""Set up configuration"""
super().setUp()
self.load_plugins("ftintitle")
def tearDown(self):
self.unload_plugins()
super().tearDown()
def _ft_add_item(self, path, artist, title, aartist): def _ft_add_item(self, path, artist, title, aartist):
return self.add_item( return self.add_item(

View file

@ -19,7 +19,7 @@ import os
import unittest import unittest
from beets import importer from beets import importer
from beets.test.helper import AutotagStub, ImportTestCase from beets.test.helper import AutotagStub, ImportTestCase, PluginMixin
from beets.util import displayable_path, syspath from beets.util import displayable_path, syspath
from beetsplug.importadded import ImportAddedPlugin from beetsplug.importadded import ImportAddedPlugin
@ -40,14 +40,14 @@ def modify_mtimes(paths, offset=-60000):
os.utime(syspath(path), (mstat.st_atime, mstat.st_mtime + offset * i)) os.utime(syspath(path), (mstat.st_atime, mstat.st_mtime + offset * i))
class ImportAddedTest(ImportTestCase): class ImportAddedTest(PluginMixin, ImportTestCase):
# The minimum mtime of the files to be imported # The minimum mtime of the files to be imported
plugin = "importadded"
min_mtime = None min_mtime = None
def setUp(self): def setUp(self):
preserve_plugin_listeners() preserve_plugin_listeners()
super().setUp() super().setUp()
self.load_plugins("importadded")
self._create_import_dir(2) self._create_import_dir(2)
# Different mtimes on the files to be imported in order to test the # Different mtimes on the files to be imported in order to test the
# plugin # plugin
@ -61,7 +61,6 @@ class ImportAddedTest(ImportTestCase):
self.importer.add_choice(importer.action.APPLY) self.importer.add_choice(importer.action.APPLY)
def tearDown(self): def tearDown(self):
self.unload_plugins()
super().tearDown() super().tearDown()
self.matcher.restore() self.matcher.restore()

View file

@ -17,18 +17,12 @@ import unittest
from mediafile import MediaFile from mediafile import MediaFile
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beets.util import displayable_path from beets.util import displayable_path
class InfoTest(BeetsTestCase): class InfoTest(PluginTestCase):
def setUp(self): plugin = "info"
super().setUp()
self.load_plugins("info")
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_path(self): def test_path(self):
path = self.create_mediafile_fixture() path = self.create_mediafile_fixture()

View file

@ -17,20 +17,14 @@ import unittest
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from beets.test import _common from beets.test import _common
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beets.util import _fsencoding, bytestring_path from beets.util import _fsencoding, bytestring_path
from beetsplug.ipfs import IPFSPlugin from beetsplug.ipfs import IPFSPlugin
@patch("beets.util.command_output", Mock()) @patch("beets.util.command_output", Mock())
class IPFSPluginTest(BeetsTestCase): class IPFSPluginTest(PluginTestCase):
def setUp(self): plugin = "ipfs"
super().setUp()
self.load_plugins("ipfs")
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_stored_hashes(self): def test_stored_hashes(self):
test_album = self.mk_test_album() test_album = self.mk_test_album()

View file

@ -18,18 +18,12 @@ from unittest.mock import patch
from beets import util from beets import util
from beets.library import Item from beets.library import Item
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
@patch("beets.util.command_output") @patch("beets.util.command_output")
class KeyFinderTest(BeetsTestCase): class KeyFinderTest(PluginTestCase):
def setUp(self): plugin = "keyfinder"
super().setUp()
self.load_plugins("keyfinder")
def tearDown(self):
super().tearDown()
self.unload_plugins()
def test_add_key(self, command_output): def test_add_key(self, command_output):
item = Item(path="/file") item = Item(path="/file")

View file

@ -15,18 +15,19 @@
import unittest import unittest
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
class LimitPluginTest(BeetsTestCase): class LimitPluginTest(PluginTestCase):
"""Unit tests for LimitPlugin """Unit tests for LimitPlugin
Note: query prefix tests do not work correctly with `run_with_output`. Note: query prefix tests do not work correctly with `run_with_output`.
""" """
plugin = "limit"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("limit")
# we'll create an even number of tracks in the library # we'll create an even number of tracks in the library
self.num_test_items = 10 self.num_test_items = 10
@ -46,10 +47,6 @@ class LimitPluginTest(BeetsTestCase):
self.track_head_range = "track:.." + str(self.num_limit) self.track_head_range = "track:.." + str(self.num_limit)
self.track_tail_range = "track:" + str(self.num_limit + 1) + ".." self.track_tail_range = "track:" + str(self.num_limit + 1) + ".."
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_no_limit(self): def test_no_limit(self):
"""Returns all when there is no limit or filter.""" """Returns all when there is no limit or filter."""
result = self.run_with_output("lslimit") result = self.run_with_output("lslimit")

View file

@ -18,22 +18,23 @@ import unittest
from beets.test.helper import ( from beets.test.helper import (
AutotagStub, AutotagStub,
ImportTestCase, ImportTestCase,
PluginMixin,
TerminalImportMixin, TerminalImportMixin,
capture_stdout, capture_stdout,
control_stdin, control_stdin,
) )
class MBSubmitPluginTest(TerminalImportMixin, ImportTestCase): class MBSubmitPluginTest(PluginMixin, TerminalImportMixin, ImportTestCase):
plugin = "mbsubmit"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("mbsubmit")
self._create_import_dir(2) self._create_import_dir(2)
self._setup_import_session() self._setup_import_session()
self.matcher = AutotagStub().install() self.matcher = AutotagStub().install()
def tearDown(self): def tearDown(self):
self.unload_plugins()
super().tearDown() super().tearDown()
self.matcher.restore() self.matcher.restore()

View file

@ -19,21 +19,15 @@ from unittest.mock import patch
from beets import config from beets import config
from beets.library import Item from beets.library import Item
from beets.test.helper import ( from beets.test.helper import (
BeetsTestCase, PluginTestCase,
capture_log, capture_log,
generate_album_info, generate_album_info,
generate_track_info, generate_track_info,
) )
class MbsyncCliTest(BeetsTestCase): class MbsyncCliTest(PluginTestCase):
def setUp(self): plugin = "mbsync"
super().setUp()
self.load_plugins("mbsync")
def tearDown(self):
self.unload_plugins()
super().tearDown()
@patch("beets.autotag.mb.album_for_id") @patch("beets.autotag.mb.album_for_id")
@patch("beets.autotag.mb.track_for_id") @patch("beets.autotag.mb.track_for_id")

View file

@ -18,18 +18,12 @@ from unittest.mock import ANY, Mock, call, patch
from beets import util from beets import util
from beets.library import Item from beets.library import Item
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beetsplug.mpdstats import MPDStats from beetsplug.mpdstats import MPDStats
class MPDStatsTest(BeetsTestCase): class MPDStatsTest(PluginTestCase):
def setUp(self): plugin = "mpdstats"
super().setUp()
self.load_plugins("mpdstats")
def tearDown(self):
super().tearDown()
self.unload_plugins()
def test_update_rating(self): def test_update_rating(self):
item = Item(title="title", path="", id=1) item = Item(title="title", path="", id=1)

View file

@ -20,7 +20,7 @@ import unittest
from unittest.mock import patch from unittest.mock import patch
from beets.library import Item from beets.library import Item
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beetsplug import parentwork from beetsplug import parentwork
work = { work = {
@ -85,15 +85,8 @@ def mock_workid_response(mbid, includes):
return p_work return p_work
class ParentWorkIntegrationTest(BeetsTestCase): class ParentWorkIntegrationTest(PluginTestCase):
def setUp(self): plugin = "parentwork"
"""Set up configuration"""
super().setUp()
self.load_plugins("parentwork")
def tearDown(self):
self.unload_plugins()
super().tearDown()
# test how it works with real musicbrainz data # test how it works with real musicbrainz data
@unittest.skipUnless( @unittest.skipUnless(
@ -180,18 +173,18 @@ class ParentWorkIntegrationTest(BeetsTestCase):
) )
class ParentWorkTest(BeetsTestCase): class ParentWorkTest(PluginTestCase):
plugin = "parentwork"
def setUp(self): def setUp(self):
"""Set up configuration""" """Set up configuration"""
super().setUp() super().setUp()
self.load_plugins("parentwork")
self.patcher = patch( self.patcher = patch(
"musicbrainzngs.get_work_by_id", side_effect=mock_workid_response "musicbrainzngs.get_work_by_id", side_effect=mock_workid_response
) )
self.patcher.start() self.patcher.start()
def tearDown(self): def tearDown(self):
self.unload_plugins()
super().tearDown() super().tearDown()
self.patcher.stop() self.patcher.stop()

View file

@ -7,7 +7,7 @@ import unittest
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from beets.test._common import touch from beets.test._common import touch
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beets.util import displayable_path from beets.util import displayable_path
from beetsplug.permissions import ( from beetsplug.permissions import (
check_permissions, check_permissions,
@ -16,17 +16,14 @@ from beetsplug.permissions import (
) )
class PermissionsPluginTest(BeetsTestCase): class PermissionsPluginTest(PluginTestCase):
plugin = "permissions"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("permissions")
self.config["permissions"] = {"file": "777", "dir": "777"} self.config["permissions"] = {"file": "777", "dir": "777"}
def tearDown(self):
super().tearDown()
self.unload_plugins()
def test_permissions_on_album_imported(self): def test_permissions_on_album_imported(self):
self.do_thing(True) self.do_thing(True)

View file

@ -20,27 +20,23 @@ import sys
import unittest import unittest
from unittest.mock import ANY, patch from unittest.mock import ANY, patch
from beets.test.helper import BeetsTestCase, CleanupModulesMixin, control_stdin from beets.test.helper import CleanupModulesMixin, PluginTestCase, control_stdin
from beets.ui import UserError from beets.ui import UserError
from beets.util import open_anything from beets.util import open_anything
from beetsplug.play import PlayPlugin from beetsplug.play import PlayPlugin
@patch("beetsplug.play.util.interactive_open") @patch("beetsplug.play.util.interactive_open")
class PlayPluginTest(CleanupModulesMixin, BeetsTestCase): class PlayPluginTest(CleanupModulesMixin, PluginTestCase):
modules = (PlayPlugin.__module__,) modules = (PlayPlugin.__module__,)
plugin = "play"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("play")
self.item = self.add_item(album="a nice älbum", title="aNiceTitle") self.item = self.add_item(album="a nice älbum", title="aNiceTitle")
self.lib.add_album([self.item]) self.lib.add_album([self.item])
self.config["play"]["command"] = "echo" self.config["play"]["command"] = "echo"
def tearDown(self):
super().tearDown()
self.unload_plugins()
def run_and_assert( def run_and_assert(
self, self,
open_mock, open_mock,

View file

@ -32,7 +32,7 @@ from unittest import mock
import confuse import confuse
import yaml import yaml
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beets.util import bluelet from beets.util import bluelet
from beetsplug import bpd from beetsplug import bpd
@ -277,12 +277,12 @@ def start_server(args, assigned_port, listener_patch):
beets.ui.main(args) beets.ui.main(args)
class BPDTestHelper(BeetsTestCase): class BPDTestHelper(PluginTestCase):
db_on_disk = True db_on_disk = True
plugin = "bpd"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("bpd")
self.item1 = self.add_item( self.item1 = self.add_item(
title="Track One Title", title="Track One Title",
track=1, track=1,
@ -297,10 +297,6 @@ class BPDTestHelper(BeetsTestCase):
) )
self.lib.add_album([self.item1, self.item2]) self.lib.add_album([self.item1, self.item2])
def tearDown(self):
super().tearDown()
self.unload_plugins()
@contextmanager @contextmanager
def run_bpd( def run_bpd(
self, self,

View file

@ -2,11 +2,13 @@ import unittest
import responses import responses
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
from beetsplug.plexupdate import get_music_section, update_plex from beetsplug.plexupdate import get_music_section, update_plex
class PlexUpdateTest(BeetsTestCase): class PlexUpdateTest(PluginTestCase):
plugin = "plexupdate"
def add_response_get_music_section(self, section_name="Music"): def add_response_get_music_section(self, section_name="Music"):
"""Create response for mocking the get_music_section function.""" """Create response for mocking the get_music_section function."""
@ -74,14 +76,9 @@ class PlexUpdateTest(BeetsTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("plexupdate")
self.config["plex"] = {"host": "localhost", "port": 32400} self.config["plex"] = {"host": "localhost", "port": 32400}
def tearDown(self):
super().tearDown()
self.unload_plugins()
@responses.activate @responses.activate
def test_get_music_section(self): def test_get_music_section(self):
# Adding response. # Adding response.

View file

@ -23,7 +23,7 @@ from beets import config
from beets.dbcore import OrQuery from beets.dbcore import OrQuery
from beets.dbcore.query import FixedFieldSort, MultipleSort, NullSort from beets.dbcore.query import FixedFieldSort, MultipleSort, NullSort
from beets.library import Album, Item, parse_query_string from beets.library import Album, Item, parse_query_string
from beets.test.helper import BeetsTestCase from beets.test.helper import BeetsTestCase, PluginTestCase
from beets.ui import UserError from beets.ui import UserError
from beets.util import CHAR_REPLACE, bytestring_path, syspath from beets.util import CHAR_REPLACE, bytestring_path, syspath
from beetsplug.smartplaylist import SmartPlaylistPlugin from beetsplug.smartplaylist import SmartPlaylistPlugin
@ -338,7 +338,9 @@ class SmartPlaylistTest(BeetsTestCase):
self.assertEqual(content, b"http://beets:8337/item/3/file\n") self.assertEqual(content, b"http://beets:8337/item/3/file\n")
class SmartPlaylistCLITest(BeetsTestCase): class SmartPlaylistCLITest(PluginTestCase):
plugin = "smartplaylist"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
@ -350,11 +352,6 @@ class SmartPlaylistCLITest(BeetsTestCase):
] ]
) )
config["smartplaylist"]["playlist_dir"].set(fsdecode(self.temp_dir)) config["smartplaylist"]["playlist_dir"].set(fsdecode(self.temp_dir))
self.load_plugins("smartplaylist")
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_splupdate(self): def test_splupdate(self):
with self.assertRaises(UserError): with self.assertRaises(UserError):

View file

@ -19,17 +19,11 @@ from datetime import datetime
from confuse import ConfigValueError from confuse import ConfigValueError
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
class TypesPluginTest(BeetsTestCase): class TypesPluginTest(PluginTestCase):
def setUp(self): plugin = "types"
super().setUp()
self.load_plugins("types")
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_integer_modify_and_query(self): def test_integer_modify_and_query(self):
self.config["types"] = {"myint": "int"} self.config["types"] = {"myint": "int"}

View file

@ -38,25 +38,22 @@ from beets.test.helper import (
AutotagStub, AutotagStub,
BeetsTestCase, BeetsTestCase,
ImportTestCase, ImportTestCase,
PluginMixin,
capture_log, capture_log,
has_program, has_program,
) )
from beets.util import bytestring_path, displayable_path, syspath from beets.util import bytestring_path, displayable_path, syspath
class ScrubbedImportTest(ImportTestCase): class ScrubbedImportTest(PluginMixin, ImportTestCase):
db_on_disk = True db_on_disk = True
plugin = "scrub"
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("scrub")
self._create_import_dir(2) self._create_import_dir(2)
self._setup_import_session(autotag=False) self._setup_import_session(autotag=False)
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_tags_not_scrubbed(self): def test_tags_not_scrubbed(self):
config["plugins"] = ["scrub"] config["plugins"] = ["scrub"]
config["scrub"]["auto"] = False config["scrub"]["auto"] = False

View file

@ -10,7 +10,7 @@ import beets.logging as blog
import beetsplug import beetsplug
from beets import plugins, ui from beets import plugins, ui
from beets.test import _common, helper from beets.test import _common, helper
from beets.test.helper import BeetsTestCase from beets.test.helper import BeetsTestCase, PluginTestCase
class LoggingTest(BeetsTestCase): class LoggingTest(BeetsTestCase):
@ -47,7 +47,8 @@ class LoggingTest(BeetsTestCase):
self.assertTrue(stream.getvalue(), "foo oof baz") self.assertTrue(stream.getvalue(), "foo oof baz")
class LoggingLevelTest(BeetsTestCase): class LoggingLevelTest(PluginTestCase):
plugin = "dummy"
class DummyModule: class DummyModule:
class DummyPlugin(plugins.BeetsPlugin): class DummyPlugin(plugins.BeetsPlugin):
def __init__(self): def __init__(self):
@ -75,10 +76,8 @@ class LoggingLevelTest(BeetsTestCase):
sys.modules["beetsplug.dummy"] = self.DummyModule sys.modules["beetsplug.dummy"] = self.DummyModule
beetsplug.dummy = self.DummyModule beetsplug.dummy = self.DummyModule
super().setUp() super().setUp()
self.load_plugins("dummy")
def tearDown(self): def tearDown(self):
self.unload_plugins()
super().tearDown() super().tearDown()
del beetsplug.dummy del beetsplug.dummy
sys.modules.pop("beetsplug.dummy") sys.modules.pop("beetsplug.dummy")

View file

@ -21,7 +21,7 @@ from datetime import datetime
from beets.library import Item from beets.library import Item
from beets.test import _common from beets.test import _common
from beets.test.helper import BeetsTestCase from beets.test.helper import PluginTestCase
def _parsetime(s): def _parsetime(s):
@ -32,7 +32,8 @@ def _is_windows():
return platform.system() == "Windows" return platform.system() == "Windows"
class MetaSyncTest(BeetsTestCase): class MetaSyncTest(PluginTestCase):
plugin = "metasync"
itunes_library_unix = os.path.join(_common.RSRC, b"itunes_library_unix.xml") itunes_library_unix = os.path.join(_common.RSRC, b"itunes_library_unix.xml")
itunes_library_windows = os.path.join( itunes_library_windows = os.path.join(
_common.RSRC, b"itunes_library_windows.xml" _common.RSRC, b"itunes_library_windows.xml"
@ -40,7 +41,6 @@ class MetaSyncTest(BeetsTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.load_plugins("metasync")
self.config["metasync"]["source"] = "itunes" self.config["metasync"]["source"] = "itunes"
@ -83,10 +83,6 @@ class MetaSyncTest(BeetsTestCase):
for item in items: for item in items:
self.lib.add(item) self.lib.add(item)
def tearDown(self):
self.unload_plugins()
super().tearDown()
def test_load_item_types(self): def test_load_item_types(self):
# This test also verifies that the MetaSources have loaded correctly # This test also verifies that the MetaSources have loaded correctly
self.assertIn("amarok_score", Item._types) self.assertIn("amarok_score", Item._types)

View file

@ -31,12 +31,9 @@ from beets.importer import (
from beets.library import Item from beets.library import Item
from beets.plugins import MetadataSourcePlugin from beets.plugins import MetadataSourcePlugin
from beets.test import helper from beets.test import helper
from beets.test.helper import ( from beets.test.helper import AutotagStub, ImportHelper
AutotagStub, from beets.test.helper import PluginTestCase as BasePluginTestCase
BeetsTestCase, from beets.test.helper import TerminalImportMixin
ImportHelper,
TerminalImportMixin,
)
from beets.util import displayable_path, syspath from beets.util import displayable_path, syspath
from beets.util.id_extractors import ( from beets.util.id_extractors import (
beatport_id_regex, beatport_id_regex,
@ -45,11 +42,10 @@ from beets.util.id_extractors import (
) )
class PluginLoaderTestCase(BeetsTestCase): class PluginLoaderTestCase(BasePluginTestCase):
def setup_plugin_loader(self): def setup_plugin_loader(self):
# FIXME the mocking code is horrific, but this is the lowest and # FIXME the mocking code is horrific, but this is the lowest and
# earliest level of the plugin mechanism we can hook into. # earliest level of the plugin mechanism we can hook into.
self.load_plugins()
self._plugin_loader_patch = patch("beets.plugins.load_plugins") self._plugin_loader_patch = patch("beets.plugins.load_plugins")
self._plugin_classes = set() self._plugin_classes = set()
load_plugins = self._plugin_loader_patch.start() load_plugins = self._plugin_loader_patch.start()
@ -58,17 +54,16 @@ class PluginLoaderTestCase(BeetsTestCase):
plugins._classes.update(self._plugin_classes) plugins._classes.update(self._plugin_classes)
load_plugins.side_effect = myload load_plugins.side_effect = myload
super().setUp()
def teardown_plugin_loader(self): def teardown_plugin_loader(self):
self._plugin_loader_patch.stop() self._plugin_loader_patch.stop()
self.unload_plugins()
def register_plugin(self, plugin_class): def register_plugin(self, plugin_class):
self._plugin_classes.add(plugin_class) self._plugin_classes.add(plugin_class)
def setUp(self): def setUp(self):
self.setup_plugin_loader() self.setup_plugin_loader()
super().setUp()
def tearDown(self): def tearDown(self):
self.teardown_plugin_loader() self.teardown_plugin_loader()
@ -174,7 +169,6 @@ class EventsTest(PluginImportTestCase):
with helper.capture_log() as logs: with helper.capture_log() as logs:
self.importer.run() self.importer.run()
self.unload_plugins()
# Exactly one event should have been imported (for the album). # Exactly one event should have been imported (for the album).
# Sentinels do not get emitted. # Sentinels do not get emitted.
@ -226,7 +220,6 @@ class EventsTest(PluginImportTestCase):
with helper.capture_log() as logs: with helper.capture_log() as logs:
self.importer.run() self.importer.run()
self.unload_plugins()
# Exactly one event should have been imported (for the album). # Exactly one event should have been imported (for the album).
# Sentinels do not get emitted. # Sentinels do not get emitted.