Replace assertRaises

This commit is contained in:
Šarūnas Nejus 2024-08-05 17:42:25 +01:00
parent 9a05d27acf
commit 847e3858a6
No known key found for this signature in database
GPG key ID: DD28F6704DBE3435
23 changed files with 133 additions and 97 deletions

View file

@ -16,6 +16,8 @@
"""
import pytest
from beets.test.helper import PluginTestCase
from beets.ui import UserError
@ -87,16 +89,16 @@ class AdvancedRewritePluginTest(PluginTestCase):
assert item.artists == ["유빈", "미미"]
def test_fail_when_replacements_empty(self):
with self.assertRaises(
with pytest.raises(
UserError,
msg="Advanced rewrites must have at least one replacement",
match="Advanced rewrites must have at least one replacement",
), self.configure_plugin([{"match": "artist:A", "replacements": {}}]):
pass
def test_fail_when_rewriting_single_valued_field_with_list(self):
with self.assertRaises(
with pytest.raises(
UserError,
msg="Field artist is not a multi-valued field but a list was given: C, D",
match="Field artist is not a multi-valued field but a list was given: C, D",
), self.configure_plugin(
[
{

View file

@ -20,6 +20,7 @@ import shutil
from unittest.mock import patch
import confuse
import pytest
import responses
from beets import config, importer, logging, util
@ -251,17 +252,17 @@ class FSArtTest(UseThePlugin):
def test_non_image_file_not_identified(self):
_common.touch(os.path.join(self.dpath, b"a.txt"))
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(None, self.settings, [self.dpath]))
def test_cautious_skips_fallback(self):
_common.touch(os.path.join(self.dpath, b"a.jpg"))
self.settings.cautious = True
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(None, self.settings, [self.dpath]))
def test_empty_dir(self):
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(None, self.settings, [self.dpath]))
def test_precedence_amongst_correct_files(self):
@ -398,7 +399,7 @@ class AAOTest(UseThePlugin):
def test_aao_scraper_returns_no_result_when_no_image_present(self):
self.mock_response(self.AAO_URL, "blah blah")
album = _common.Bag(asin=self.ASIN)
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(album, self.settings, []))
@ -440,7 +441,7 @@ class ITunesStoreTest(UseThePlugin):
expected = "got no results"
with capture_log("beets.test_art") as logs:
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(self.album, self.settings, []))
assert expected in logs[1]
@ -454,7 +455,7 @@ class ITunesStoreTest(UseThePlugin):
expected = "iTunes search failed: 404 Client Error"
with capture_log("beets.test_art") as logs:
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(self.album, self.settings, []))
assert expected in logs[1]
@ -487,7 +488,7 @@ class ITunesStoreTest(UseThePlugin):
expected = "Malformed itunes candidate"
with capture_log("beets.test_art") as logs:
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(self.album, self.settings, []))
assert expected in logs[1]
@ -497,7 +498,7 @@ class ITunesStoreTest(UseThePlugin):
expected = "not found in json. Fields are"
with capture_log("beets.test_art") as logs:
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(self.album, self.settings, []))
assert expected in logs[1]
@ -507,7 +508,7 @@ class ITunesStoreTest(UseThePlugin):
expected = "Could not decode json response:"
with capture_log("beets.test_art") as logs:
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(self.album, self.settings, []))
assert expected in logs[1]
@ -538,14 +539,14 @@ class GoogleImageTest(UseThePlugin):
album = _common.Bag(albumartist="some artist", album="some album")
json = '{"error": {"errors": [{"reason": "some reason"}]}}'
self.mock_response(fetchart.GoogleImages.URL, json)
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(album, self.settings, []))
def test_google_art_returns_no_result_with_malformed_response(self):
album = _common.Bag(albumartist="some artist", album="some album")
json = """bla blup"""
self.mock_response(fetchart.GoogleImages.URL, json)
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(album, self.settings, []))
@ -695,7 +696,7 @@ class FanartTVTest(UseThePlugin):
fetchart.FanartTV.API_ALBUMS + "thereleasegroupid",
self.RESPONSE_ERROR,
)
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(album, self.settings, []))
def test_fanarttv_returns_no_result_with_malformed_response(self):
@ -704,7 +705,7 @@ class FanartTVTest(UseThePlugin):
fetchart.FanartTV.API_ALBUMS + "thereleasegroupid",
self.RESPONSE_MALFORMED,
)
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(album, self.settings, []))
def test_fanarttv_only_other_images(self):
@ -714,7 +715,7 @@ class FanartTVTest(UseThePlugin):
fetchart.FanartTV.API_ALBUMS + "thereleasegroupid",
self.RESPONSE_NO_ART,
)
with self.assertRaises(StopIteration):
with pytest.raises(StopIteration):
next(self.source.get(album, self.settings, []))
@ -1000,7 +1001,7 @@ class EnforceRatioConfigTest(BeetsTestCase):
if should_raise:
for v in values:
config["fetchart"]["enforce_ratio"] = v
with self.assertRaises(confuse.ConfigValueError):
with pytest.raises(confuse.ConfigValueError):
fetchart.FetchArtPlugin()
else:
for v in values:

View file

@ -15,6 +15,8 @@
"""Tests for the 'bucket' plugin."""
import pytest
from beets import config, ui
from beets.test.helper import BeetsTestCase
from beetsplug import bucket
@ -136,21 +138,21 @@ class BucketPluginTest(BeetsTestCase):
def test_bad_alpha_range_def(self):
"""If bad alpha range definition, a UserError is raised."""
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
self._setup_config(bucket_alpha=["$%"])
def test_bad_year_range_def_no4digits(self):
"""If bad year range definition, a UserError is raised.
Range origin must be expressed on 4 digits.
"""
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
self._setup_config(bucket_year=["62-64"])
def test_bad_year_range_def_nodigits(self):
"""If bad year range definition, a UserError is raised.
At least the range origin must be declared.
"""
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
self._setup_config(bucket_year=["nodigits"])
def check_span_from_str(self, sstr, dfrom, dto):

View file

@ -20,6 +20,7 @@ import unittest
from test.test_art_resize import DummyIMBackend
from unittest.mock import MagicMock, patch
import pytest
from mediafile import MediaFile
from beets import art, config, logging, ui
@ -122,7 +123,7 @@ class EmbedartCliTest(PluginMixin, FetchImageHelper, BeetsTestCase):
def test_art_file_missing(self):
self.add_album_fixture()
logging.getLogger("beets.embedart").setLevel(logging.DEBUG)
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
self.run_command("embedart", "-y", "-f", "/doesnotexist")
def test_embed_non_image_file(self):

View file

@ -20,6 +20,8 @@ import sys
import unittest
from unittest.mock import ANY, patch
import pytest
from beets.test.helper import CleanupModulesMixin, PluginTestCase, control_stdin
from beets.ui import UserError
from beets.util import open_anything
@ -139,5 +141,5 @@ class PlayPluginTest(CleanupModulesMixin, PluginTestCase):
def test_command_failed(self, open_mock):
open_mock.side_effect = OSError("some reason")
with self.assertRaises(UserError):
with pytest.raises(UserError):
self.run_command("play", "title:aNiceTitle")

View file

@ -19,6 +19,7 @@ import os
import shutil
import mediafile
import pytest
from beets.library import Item
from beets.plugins import BeetsPlugin
@ -115,11 +116,13 @@ class ExtendedFieldTestMixin(BeetsTestCase):
Item._media_fields.remove("customtag")
def test_invalid_descriptor(self):
with self.assertRaises(ValueError) as cm:
with pytest.raises(
ValueError, match="must be an instance of MediaField"
):
mediafile.MediaFile.add_field("somekey", True)
assert "must be an instance of MediaField" in str(cm.exception)
def test_overwrite_property(self):
with self.assertRaises(ValueError) as cm:
with pytest.raises(
ValueError, match='property "artist" already exists'
):
mediafile.MediaFile.add_field("artist", mediafile.MediaField())
assert 'property "artist" already exists' in str(cm.exception)

View file

@ -18,6 +18,8 @@ from shutil import rmtree
from tempfile import mkdtemp
from unittest.mock import MagicMock, Mock, PropertyMock
import pytest
from beets import config
from beets.dbcore import OrQuery
from beets.dbcore.query import FixedFieldSort, MultipleSort, NullSort
@ -347,7 +349,7 @@ class SmartPlaylistCLITest(PluginTestCase):
config["smartplaylist"]["playlist_dir"].set(fsdecode(self.temp_dir))
def test_splupdate(self):
with self.assertRaises(UserError):
with pytest.raises(UserError):
self.run_with_output("splupdate", "tagada")
self.run_with_output("splupdate", "my_playlist")

View file

@ -18,6 +18,8 @@ from shutil import rmtree
from tempfile import mkdtemp
from unittest.mock import Mock, call, patch
import pytest
from beets.test.helper import BeetsTestCase
from beets.util import bytestring_path, syspath
from beetsplug.thumbnails import (
@ -81,7 +83,7 @@ class ThumbnailsTest(BeetsTestCase):
mock_artresizer.shared.local = True
mock_artresizer.shared.can_write_metadata = False
with self.assertRaises(RuntimeError):
with pytest.raises(RuntimeError):
ThumbnailsPlugin()
mock_artresizer.shared.local = True

View file

@ -16,6 +16,7 @@
import time
from datetime import datetime
import pytest
from confuse import ConfigValueError
from beets.test.helper import PluginTestCase
@ -132,7 +133,7 @@ class TypesPluginTest(PluginTestCase):
def test_unknown_type_error(self):
self.config["types"] = {"flex": "unkown type"}
with self.assertRaises(ConfigValueError):
with pytest.raises(ConfigValueError):
self.run_command("ls")
def test_template_if_def(self):

View file

@ -18,6 +18,8 @@
import re
import unittest
import pytest
from beets import autotag, config
from beets.autotag import AlbumInfo, TrackInfo, match
from beets.autotag.hooks import Distance, string_dist
@ -46,7 +48,7 @@ class PluralityTest(BeetsTestCase):
assert freq == 2
def test_plurality_empty_sequence_raises_error(self):
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
plurality([])
def test_current_metadata_finds_pluralities(self):

View file

@ -1,6 +1,7 @@
import os
from unittest.mock import patch
import pytest
import yaml
from beets import config, ui
@ -110,12 +111,11 @@ class ConfigCommandTest(BeetsTestCase):
)
def test_config_editor_not_found(self):
with self.assertRaises(ui.UserError) as user_error:
msg_match = "Could not edit configuration.*here is problem"
with pytest.raises(ui.UserError, match=msg_match):
with patch("os.execlp") as execlp:
execlp.side_effect = OSError("here is problem")
self.run_command("config", "-e")
assert "Could not edit configuration" in str(user_error.exception)
assert "here is problem" in str(user_error.exception)
def test_edit_invalid_config_file(self):
with open(self.config_path, "w") as file:

View file

@ -19,6 +19,8 @@ import time
import unittest
from datetime import datetime, timedelta
import pytest
from beets.dbcore.query import (
DateInterval,
DateQuery,
@ -278,11 +280,11 @@ class DateQueryTestRelativeMore(ItemInDBTestCase):
class DateQueryConstructTest(unittest.TestCase):
def test_long_numbers(self):
with self.assertRaises(InvalidQueryArgumentValueError):
with pytest.raises(InvalidQueryArgumentValueError):
DateQuery("added", "1409830085..1412422089")
def test_too_many_components(self):
with self.assertRaises(InvalidQueryArgumentValueError):
with pytest.raises(InvalidQueryArgumentValueError):
DateQuery("added", "12-34-56-78")
def test_invalid_date_query(self):
@ -297,7 +299,7 @@ class DateQueryConstructTest(unittest.TestCase):
"..2aa",
]
for q in q_list:
with self.assertRaises(InvalidQueryArgumentValueError):
with pytest.raises(InvalidQueryArgumentValueError):
DateQuery("added", q)
def test_datetime_uppercase_t_separator(self):
@ -316,5 +318,5 @@ class DateQueryConstructTest(unittest.TestCase):
assert date_query.interval.end == datetime(2000, 1, 1, 13)
def test_datetime_invalid_separator(self):
with self.assertRaises(InvalidQueryArgumentValueError):
with pytest.raises(InvalidQueryArgumentValueError):
DateQuery("added", "2000-01-01x12")

View file

@ -20,6 +20,8 @@ import sqlite3
import unittest
from tempfile import mkstemp
import pytest
from beets import dbcore
from beets.test import _common
@ -340,7 +342,7 @@ class ModelTest(unittest.TestCase):
def test_delete_non_existent_attribute(self):
model = ModelFixture1()
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
del model["foo"]
def test_delete_fixed_attribute(self):
@ -386,21 +388,21 @@ class ModelTest(unittest.TestCase):
assert "flex_field" not in model2
def test_check_db_fails(self):
with self.assertRaisesRegex(ValueError, "no database"):
with pytest.raises(ValueError, match="no database"):
dbcore.Model()._check_db()
with self.assertRaisesRegex(ValueError, "no id"):
with pytest.raises(ValueError, match="no id"):
ModelFixture1(self.db)._check_db()
dbcore.Model(self.db)._check_db(need_id=False)
def test_missing_field(self):
with self.assertRaises(AttributeError):
with pytest.raises(AttributeError):
ModelFixture1(self.db).nonExistingKey
def test_computed_field(self):
model = ModelFixtureWithGetters()
assert model.aComputedField == "thing"
with self.assertRaisesRegex(KeyError, "computed field .+ deleted"):
with pytest.raises(KeyError, match="computed field .+ deleted"):
del model.aComputedField
def test_items(self):
@ -413,11 +415,11 @@ class ModelTest(unittest.TestCase):
def test_delete_internal_field(self):
model = dbcore.Model()
del model._db
with self.assertRaises(AttributeError):
with pytest.raises(AttributeError):
model._db
def test_parse_nonstring(self):
with self.assertRaisesRegex(TypeError, "must be a string"):
with pytest.raises(TypeError, match="must be a string"):
dbcore.Model._parse(None, 42)
@ -479,7 +481,7 @@ class FormattedMappingTest(unittest.TestCase):
def test_get_unset_field(self):
model = ModelFixture1()
formatted = model.formatted()
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
formatted["other_field"]
def test_get_method_with_default(self):
@ -755,7 +757,7 @@ class ResultsIteratorTest(unittest.TestCase):
def test_out_of_range(self):
objs = self.db._fetch(ModelFixture1)
with self.assertRaises(IndexError):
with pytest.raises(IndexError):
objs[100]
def test_no_results(self):

View file

@ -21,6 +21,8 @@ import stat
import unittest
from os.path import join
import pytest
import beets.library
from beets import util
from beets.test import _common
@ -576,16 +578,16 @@ class SafeMoveCopyTest(BeetsTestCase):
self.assertExists(self.path)
def test_unsuccessful_move(self):
with self.assertRaises(util.FilesystemError):
with pytest.raises(util.FilesystemError):
util.move(self.path, self.otherpath)
def test_unsuccessful_copy(self):
with self.assertRaises(util.FilesystemError):
with pytest.raises(util.FilesystemError):
util.copy(self.path, self.otherpath)
@unittest.skipUnless(_common.HAVE_REFLINK, "need reflink")
def test_unsuccessful_reflink(self):
with self.assertRaises(util.FilesystemError):
with pytest.raises(util.FilesystemError):
util.reflink(self.path, self.otherpath)
def test_self_move(self):

View file

@ -29,6 +29,7 @@ from tempfile import mkstemp
from unittest.mock import Mock, patch
from zipfile import ZipFile
import pytest
from mediafile import MediaFile
from beets import config, importer, logging, util
@ -574,7 +575,7 @@ class ImportTest(ImportTestCase):
self.importer.add_choice(importer.action.ASIS)
self.importer.run()
with self.assertRaises(AttributeError):
with pytest.raises(AttributeError):
self.lib.items().get().data_source
def test_set_fields(self):

View file

@ -12,8 +12,7 @@
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Tests for non-query database functions of Item.
"""
"""Tests for non-query database functions of Item."""
import os
import os.path
@ -25,6 +24,7 @@ import time
import unicodedata
import unittest
import pytest
from mediafile import MediaFile, UnreadableFileError
import beets.dbcore.query
@ -150,7 +150,8 @@ class GetSetTest(BeetsTestCase):
assert "title" not in self.i._dirty
def test_invalid_field_raises_attributeerror(self):
self.assertRaises(AttributeError, getattr, self.i, "xyzzy")
with pytest.raises(AttributeError):
self.i.xyzzy
def test_album_fallback(self):
# integration test of item-album fallback
@ -547,7 +548,7 @@ class ItemFormattedMappingTest(ItemInDBTestCase):
def test_get_unset_field(self):
formatted = self.i.formatted()
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
formatted["other_field"]
def test_get_method_with_default(self):
@ -1239,7 +1240,7 @@ class WriteTest(BeetsTestCase):
def test_write_nonexistant(self):
item = self.create_item()
item.path = b"/path/does/not/exist"
with self.assertRaises(beets.library.ReadError):
with pytest.raises(beets.library.ReadError):
item.write()
def test_no_write_permission(self):
@ -1248,7 +1249,8 @@ class WriteTest(BeetsTestCase):
os.chmod(path, stat.S_IRUSR)
try:
self.assertRaises(beets.library.WriteError, item.write)
with pytest.raises(beets.library.WriteError):
item.write()
finally:
# Restore write permissions so the file can be cleaned up.
@ -1307,13 +1309,13 @@ class ItemReadTest(unittest.TestCase):
def test_unreadable_raise_read_error(self):
unreadable = os.path.join(_common.RSRC, b"image-2x3.png")
item = beets.library.Item()
with self.assertRaises(beets.library.ReadError) as cm:
with pytest.raises(beets.library.ReadError) as exc_info:
item.read(unreadable)
self.assertIsInstance(cm.exception.reason, UnreadableFileError)
self.assertIsInstance(exc_info.value.reason, UnreadableFileError)
def test_nonexistent_raise_read_error(self):
item = beets.library.Item()
with self.assertRaises(beets.library.ReadError):
with pytest.raises(beets.library.ReadError):
item.read("/thisfiledoesnotexist")
@ -1329,12 +1331,11 @@ class FilesizeTest(BeetsTestCase):
class ParseQueryTest(unittest.TestCase):
def test_parse_invalid_query_string(self):
with self.assertRaises(beets.dbcore.InvalidQueryError) as raised:
with pytest.raises(beets.dbcore.query.ParsingError):
beets.library.parse_query_string('foo"', None)
self.assertIsInstance(raised.exception, beets.dbcore.query.ParsingError)
def test_parse_bytes(self):
with self.assertRaises(AssertionError):
with pytest.raises(AssertionError):
beets.library.parse_query_string(b"query", None)

View file

@ -20,6 +20,8 @@ from os import path
from shutil import rmtree
from tempfile import mkdtemp
import pytest
from beets.test._common import RSRC
from beets.util import bytestring_path
from beets.util.m3u import EmptyPlaylistError, M3UFile
@ -33,7 +35,7 @@ class M3UFileTest(unittest.TestCase):
tempdir = bytestring_path(mkdtemp())
the_playlist_file = path.join(tempdir, b"playlist.m3u8")
m3ufile = M3UFile(the_playlist_file)
with self.assertRaises(EmptyPlaylistError):
with pytest.raises(EmptyPlaylistError):
m3ufile.write()
rmtree(tempdir)

View file

@ -17,6 +17,8 @@
import unittest
import pytest
from beets.util import pipeline
@ -121,17 +123,20 @@ class ExceptionTest(unittest.TestCase):
self.pl = pipeline.Pipeline((_produce(), _exc_work(), _consume(self.l)))
def test_run_sequential(self):
self.assertRaises(ExceptionFixture, self.pl.run_sequential)
with pytest.raises(ExceptionFixture):
self.pl.run_sequential()
def test_run_parallel(self):
self.assertRaises(ExceptionFixture, self.pl.run_parallel)
with pytest.raises(ExceptionFixture):
self.pl.run_parallel()
def test_pull(self):
pl = pipeline.Pipeline((_produce(), _exc_work()))
pull = pl.pull()
for i in range(3):
next(pull)
self.assertRaises(ExceptionFixture, pull.__next__)
with pytest.raises(ExceptionFixture):
next(pull)
class ParallelExceptionTest(unittest.TestCase):
@ -142,7 +147,8 @@ class ParallelExceptionTest(unittest.TestCase):
)
def test_run_parallel(self):
self.assertRaises(ExceptionFixture, self.pl.run_parallel)
with pytest.raises(ExceptionFixture):
self.pl.run_parallel()
class ConstrainedThreadedPipelineTest(unittest.TestCase):
@ -158,7 +164,8 @@ class ConstrainedThreadedPipelineTest(unittest.TestCase):
# Raise an exception in a constrained pipeline.
l = []
pl = pipeline.Pipeline((_produce(1000), _exc_work(), _consume(l)))
self.assertRaises(ExceptionFixture, pl.run_parallel, 1)
with pytest.raises(ExceptionFixture):
pl.run_parallel(1)
def test_constrained_parallel(self):
l = []

View file

@ -18,6 +18,7 @@ import os
import unittest
from unittest.mock import ANY, Mock, patch
import pytest
from mediafile import MediaFile
from beets import config, plugins, ui
@ -141,7 +142,8 @@ class ItemTypeConflictTest(PluginLoaderTestCase):
self.advent_listener_plugin = AdventListenerPlugin
self.register_plugin(EventListenerPlugin)
self.register_plugin(AdventListenerPlugin)
self.assertRaises(plugins.PluginConflictException, plugins.types, Item)
with pytest.raises(plugins.PluginConflictException):
plugins.types(Item)
def test_match(self):
class EventListenerPlugin(plugins.BeetsPlugin):
@ -333,13 +335,13 @@ class ListenersTest(PluginLoaderTestCase):
plugins.send("event3", foo=5)
plugins.send("event4", foo=5)
with self.assertRaises(TypeError):
with pytest.raises(TypeError):
plugins.send("event5", foo=5)
plugins.send("event6", foo=5)
plugins.send("event7", foo=5)
with self.assertRaises(TypeError):
with pytest.raises(TypeError):
plugins.send("event8", foo=5)
plugins.send("event9", foo=5)

View file

@ -21,6 +21,8 @@ import unittest
from contextlib import contextmanager
from functools import partial
import pytest
import beets.library
from beets import dbcore, util
from beets.dbcore import types
@ -395,25 +397,15 @@ class GetTest(DummyDataTestCase):
q = "albumflex:foo"
results = self.lib.items(q)
self.assert_items_matched(
results,
[
"foo bar",
"baz qux",
],
)
self.assert_items_matched(results, ["foo bar", "baz qux"])
def test_invalid_query(self):
with self.assertRaises(InvalidQueryArgumentValueError) as raised:
with pytest.raises(InvalidQueryArgumentValueError, match="not an int"):
dbcore.query.NumericQuery("year", "199a")
assert "not an int" in str(raised.exception)
with self.assertRaises(InvalidQueryArgumentValueError) as raised:
msg_match = r"not a regular expression.*unterminated subpattern"
with pytest.raises(ParsingError, match=msg_match):
dbcore.query.RegexpQuery("year", "199(")
exception_text = str(raised.exception)
assert "not a regular expression" in exception_text
assert "unterminated subpattern" in exception_text
self.assertIsInstance(raised.exception, ParsingError)
class MatchTest(BeetsTestCase):

View file

@ -24,6 +24,7 @@ import sys
import unittest
from unittest.mock import Mock, patch
import pytest
from confuse import ConfigError
from mediafile import MediaFile
@ -785,7 +786,8 @@ class ImportTest(BeetsTestCase):
def test_quiet_timid_disallowed(self):
config["import"]["quiet"] = True
config["import"]["timid"] = True
self.assertRaises(ui.UserError, commands.import_files, None, [], None)
with pytest.raises(ui.UserError):
commands.import_files(None, [], None)
def test_parse_paths_from_logfile(self):
if os.path.__name__ == "ntpath":
@ -923,7 +925,7 @@ class ConfigTest(TestPluginTestCase):
with self.write_config_file() as config:
config.write("library: /xxx/yyy/not/a/real/path")
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
self.run_command("test", lib=None)
def test_user_config_file(self):
@ -1079,7 +1081,8 @@ class ConfigTest(TestPluginTestCase):
beetsdir = os.path.join(self.temp_dir, b"beetsfile")
open(beetsdir, "a").close()
os.environ["BEETSDIR"] = os.fsdecode(beetsdir)
self.assertRaises(ConfigError, self.run_command, "test")
with pytest.raises(ConfigError):
self.run_command("test")
def test_beetsdir_config_does_not_load_default_user_config(self):
os.environ["BEETSDIR"] = os.fsdecode(self.beetsdir)
@ -1496,7 +1499,7 @@ class CommonOptionsParserCliTest(BeetsTestCase):
l = self.run_with_output("help", "list")
assert "Usage:" in l
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
self.run_command("help", "this.is.not.a.real.command")
def test_stats(self):
@ -1568,7 +1571,7 @@ class CommonOptionsParserTest(BeetsTestCase):
assert config["format_album"].as_str() == "$baz"
def test_format_option_with_target(self):
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
ui.CommonOptionsParser().add_format_option(target="thingy")
parser = ui.CommonOptionsParser()

View file

@ -19,6 +19,8 @@
import os
import shutil
import pytest
from beets import library, ui
from beets.test import _common
from beets.test.helper import BeetsTestCase, ItemInDBTestCase
@ -49,11 +51,11 @@ class QueryTest(BeetsTestCase):
assert len(albums) == num_albums
def test_query_empty(self):
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
commands._do_query(self.lib, (), False)
def test_query_empty_album(self):
with self.assertRaises(ui.UserError):
with pytest.raises(ui.UserError):
commands._do_query(self.lib, (), True)
def test_query_item(self):

View file

@ -22,6 +22,8 @@ import sys
import unittest
from unittest.mock import Mock, patch
import pytest
from beets import util
from beets.test import _common
from beets.test.helper import BeetsTestCase
@ -111,10 +113,10 @@ class UtilTest(unittest.TestCase):
return m
mock_popen.side_effect = popen_fail
with self.assertRaises(subprocess.CalledProcessError) as exc_context:
with pytest.raises(subprocess.CalledProcessError) as exc_info:
util.command_output(["taga", "\xc3\xa9"])
assert exc_context.exception.returncode == 1
assert exc_context.exception.cmd == "taga \xc3\xa9"
assert exc_info.value.returncode == 1
assert exc_info.value.cmd == "taga \xc3\xa9"
def test_case_sensitive_default(self):
path = util.bytestring_path(