Speed up a couple of tests (#5799)

Speed up tests by using `unittest.TestCase` for tests that don't require
directory setup

This PR improves test performance by switching several test classes from
`BeetsTestCase` to standard `unittest.TestCase` when they don't require
the directory setup and teardown overhead. The changes focus on test
classes that:

1. Only test utility functions
2. Don't need temporary directories
3. Don't interact with the filesystem

The PR removes unnecessary imports of `BeetsTestCase` and adds direct
imports of `unittest` where needed. This change reduces the test
execution time by avoiding the expensive setup/teardown steps for tests
that don't require them.
This commit is contained in:
Šarūnas Nejus 2025-05-26 14:32:36 +01:00 committed by GitHub
commit 60f24cdc74
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 32 additions and 35 deletions

View file

@ -18,6 +18,7 @@ from __future__ import annotations
import os
import shutil
import unittest
from typing import TYPE_CHECKING
from unittest.mock import patch
@ -1012,7 +1013,7 @@ class ArtForAlbumTest(UseThePlugin):
self._assert_image_operated(self.IMG_348x348, self.RESIZE_OP, True)
class DeprecatedConfigTest(BeetsTestCase):
class DeprecatedConfigTest(unittest.TestCase):
"""While refactoring the plugin, the remote_priority option was deprecated,
and a new codepath should translate its effect. Check that it actually does
so.
@ -1030,7 +1031,7 @@ class DeprecatedConfigTest(BeetsTestCase):
assert isinstance(self.plugin.sources[-1], fetchart.FileSystem)
class EnforceRatioConfigTest(BeetsTestCase):
class EnforceRatioConfigTest(unittest.TestCase):
"""Throw some data at the regexes."""
def _load_with_config(self, values, should_raise):

View file

@ -14,6 +14,7 @@
"""Tests for the 'beatport' plugin."""
import unittest
from datetime import timedelta
from beets.test import _common
@ -585,7 +586,7 @@ class BeatportTest(BeetsTestCase):
assert track.genre == test_track.genre
class BeatportResponseEmptyTest(BeetsTestCase):
class BeatportResponseEmptyTest(unittest.TestCase):
def _make_tracks_response(self):
results = [
{

View file

@ -18,7 +18,6 @@ from unittest.mock import Mock
import pytest
from beets import config
from beets.test import _common
from beets.test.helper import BeetsTestCase
from beetsplug import lastgenre
@ -32,12 +31,12 @@ class LastGenrePluginTest(BeetsTestCase):
def _setup_config(
self, whitelist=False, canonical=False, count=1, prefer_specific=False
):
config["lastgenre"]["canonical"] = canonical
config["lastgenre"]["count"] = count
config["lastgenre"]["prefer_specific"] = prefer_specific
self.config["lastgenre"]["canonical"] = canonical
self.config["lastgenre"]["count"] = count
self.config["lastgenre"]["prefer_specific"] = prefer_specific
if isinstance(whitelist, (bool, (str,))):
# Filename, default, or disabled.
config["lastgenre"]["whitelist"] = whitelist
self.config["lastgenre"]["whitelist"] = whitelist
self.plugin.setup()
if not isinstance(whitelist, (bool, (str,))):
# Explicit list of genres.
@ -463,11 +462,10 @@ def test_get_genre(config_values, item_genre, mock_genres, expected_result):
lastgenre.LastGenrePlugin.fetch_album_genre = mock_fetch_album_genre
lastgenre.LastGenrePlugin.fetch_artist_genre = mock_fetch_artist_genre
# Configure
config["lastgenre"] = config_values
# Initialize plugin instance and item
plugin = lastgenre.LastGenrePlugin()
# Configure
plugin.config.set(config_values)
item = _common.item()
item.genre = item_genre

View file

@ -14,6 +14,7 @@
"""Tests for MusicBrainz API wrapper."""
import unittest
from unittest import mock
import pytest
@ -665,7 +666,7 @@ class MBAlbumInfoTest(MusicBrainzTestCase):
assert t[1].trackdisambig == "SECOND TRACK"
class ArtistFlatteningTest(BeetsTestCase):
class ArtistFlatteningTest(unittest.TestCase):
def _credit_dict(self, suffix=""):
return {
"artist": {

View file

@ -1,11 +1,11 @@
"""Tests for the 'subsonic' plugin."""
import unittest
from urllib.parse import parse_qs, urlparse
import responses
from beets import config
from beets.test.helper import BeetsTestCase
from beetsplug import subsonicupdate
@ -24,7 +24,7 @@ def _params(url):
return parse_qs(urlparse(url).query)
class SubsonicPluginTest(BeetsTestCase):
class SubsonicPluginTest(unittest.TestCase):
"""Test class for subsonicupdate."""
@responses.activate

View file

@ -1,11 +1,12 @@
"""Tests for the 'the' plugin"""
import unittest
from beets import config
from beets.test.helper import BeetsTestCase
from beetsplug.the import FORMAT, PATTERN_A, PATTERN_THE, ThePlugin
class ThePluginTest(BeetsTestCase):
class ThePluginTest(unittest.TestCase):
def test_unthe_with_default_patterns(self):
assert ThePlugin().unthe("", PATTERN_THE) == ""
assert (

View file

@ -200,7 +200,7 @@ class MoveTest(BeetsTestCase):
assert self.i.path == util.normpath(self.dest)
class HelperTest(BeetsTestCase):
class HelperTest(unittest.TestCase):
def test_ancestry_works_on_file(self):
p = "/a/b/c"
a = ["/", "/a", "/a/b"]

View file

@ -924,7 +924,7 @@ class ChooseCandidateTest(AutotagImportTestCase):
assert self.lib.albums().get().album == "Applied Album MM"
class InferAlbumDataTest(BeetsTestCase):
class InferAlbumDataTest(unittest.TestCase):
def setUp(self):
super().setUp()
@ -1220,7 +1220,7 @@ class ImportDuplicateSingletonTest(ImportTestCase):
return item
class TagLogTest(BeetsTestCase):
class TagLogTest(unittest.TestCase):
def test_tag_log_line(self):
sio = StringIO()
handler = logging.StreamHandler(sio)

View file

@ -3,21 +3,17 @@
import logging as log
import sys
import threading
import unittest
from io import StringIO
import beets.logging as blog
import beetsplug
from beets import plugins, ui
from beets.test import _common, helper
from beets.test.helper import (
AsIsImporterMixin,
BeetsTestCase,
ImportTestCase,
PluginMixin,
)
from beets.test.helper import AsIsImporterMixin, ImportTestCase, PluginMixin
class LoggingTest(BeetsTestCase):
class LoggingTest(unittest.TestCase):
def test_logging_management(self):
l1 = log.getLogger("foo123")
l2 = blog.getLogger("foo123")

View file

@ -373,7 +373,7 @@ class GetTest(DummyDataTestCase):
dbcore.query.RegexpQuery("year", "199(")
class MatchTest(BeetsTestCase):
class MatchTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.item = _common.item()
@ -811,7 +811,7 @@ class NoneQueryTest(BeetsTestCase, AssertsMixin):
self.assertInResult(item, matched)
class NotQueryMatchTest(BeetsTestCase):
class NotQueryMatchTest(unittest.TestCase):
"""Test `query.NotQuery` matching against a single item, using the same
cases and assertions as on `MatchTest`, plus assertion on the negated
queries (ie. assert q -> assert not NotQuery(q)).

View file

@ -378,7 +378,7 @@ class ConfigSortTest(DummyDataTestCase):
assert results[0].albumartist > results[1].albumartist
class CaseSensitivityTest(DummyDataTestCase, BeetsTestCase):
class CaseSensitivityTest(DummyDataTestCase):
"""If case_insensitive is false, lower-case values should be placed
after all upper-case values. E.g., `Foo Qux bar`
"""

View file

@ -1337,7 +1337,7 @@ class ShowChangeTest(BeetsTestCase):
@patch("beets.library.Item.try_filesize", Mock(return_value=987))
class SummarizeItemsTest(BeetsTestCase):
class SummarizeItemsTest(unittest.TestCase):
def setUp(self):
super().setUp()
item = library.Item()
@ -1374,7 +1374,7 @@ class SummarizeItemsTest(BeetsTestCase):
assert summary == "3 items, G 2, F 1, 4kbps, 32:42, 2.9 KiB"
class PathFormatTest(BeetsTestCase):
class PathFormatTest(unittest.TestCase):
def test_custom_paths_prepend(self):
default_formats = ui.get_path_formats()
@ -1521,7 +1521,7 @@ class CommonOptionsParserCliTest(BeetsTestCase):
# assert 'plugins: ' in output
class CommonOptionsParserTest(BeetsTestCase):
class CommonOptionsParserTest(unittest.TestCase):
def test_album_option(self):
parser = ui.CommonOptionsParser()
assert not parser._album_flags
@ -1614,7 +1614,7 @@ class CommonOptionsParserTest(BeetsTestCase):
)
class EncodingTest(BeetsTestCase):
class EncodingTest(unittest.TestCase):
"""Tests for the `terminal_encoding` config option and our
`_in_encoding` and `_out_encoding` utility functions.
"""

View file

@ -25,7 +25,6 @@ import pytest
from beets import util
from beets.test import _common
from beets.test.helper import BeetsTestCase
class UtilTest(unittest.TestCase):
@ -132,7 +131,7 @@ class UtilTest(unittest.TestCase):
pass
class PathConversionTest(BeetsTestCase):
class PathConversionTest(unittest.TestCase):
def test_syspath_windows_format(self):
with _common.platform_windows():
path = os.path.join("a", "b", "c")