Replace assertTrue

This commit is contained in:
Šarūnas Nejus 2024-07-29 00:56:20 +01:00
parent 7703c9e338
commit 0ecc345143
No known key found for this signature in database
GPG key ID: DD28F6704DBE3435
31 changed files with 177 additions and 201 deletions

View file

@ -152,9 +152,7 @@ class Assertions:
"""A mixin with additional unit test assertions."""
def assertExists(self, path): # noqa
self.assertTrue(
os.path.exists(syspath(path)), f"file does not exist: {path!r}"
)
assert os.path.exists(syspath(path)), f"file does not exist: {path!r}"
def assertNotExists(self, path): # noqa
self.assertFalse(
@ -163,17 +161,15 @@ class Assertions:
def assertIsFile(self, path): # noqa
self.assertExists(path)
self.assertTrue(
os.path.isfile(syspath(path)),
"path exists, but is not a regular file: {!r}".format(path),
)
assert os.path.isfile(
syspath(path)
), "path exists, but is not a regular file: {!r}".format(path)
def assertIsDir(self, path): # noqa
self.assertExists(path)
self.assertTrue(
os.path.isdir(syspath(path)),
"path exists, but is not a directory: {!r}".format(path),
)
assert os.path.isdir(
syspath(path)
), "path exists, but is not a directory: {!r}".format(path)
def assert_equal_path(self, a, b):
"""Check that two paths are equal."""

View file

@ -300,7 +300,7 @@ class ConvertCliTest(ConvertTestCase, ConvertCommand):
with control_stdin("y"):
self.run_convert("--playlist", "playlist.m3u8")
m3u_created = os.path.join(self.convert_dest, b"playlist.m3u8")
self.assertTrue(os.path.exists(m3u_created))
assert os.path.exists(m3u_created)
def test_playlist_pretend(self):
self.run_convert("--playlist", "playlist.m3u8", "--pretend")

View file

@ -146,8 +146,8 @@ class EditCommandTest(EditMixin, BeetsTestCase):
self.assertEqual(len(self.lib.albums()), album_count)
self.assertEqual(len(self.lib.items()), track_count)
self.assertEqual(mock_write.call_count, write_call_count)
self.assertTrue(
all(i.title.startswith(title_starts_with) for i in self.lib.items())
assert all(
i.title.startswith(title_starts_with) for i in self.lib.items()
)
def test_title_edit_discard(self, mock_write):
@ -366,9 +366,7 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
"mb_albumartistids",
],
)
self.assertTrue(
all("Edited Track" in i.title for i in self.lib.items())
)
assert all("Edited Track" in i.title for i in self.lib.items())
# Ensure album is *not* fetched from a candidate.
self.assertEqual(self.lib.albums()[0].mb_albumid, "")
@ -391,7 +389,7 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
[],
self.IGNORED + ["albumartist", "mb_albumartistid"],
)
self.assertTrue(all("Tag Track" in i.title for i in self.lib.items()))
assert all("Tag Track" in i.title for i in self.lib.items())
# Ensure album is *not* fetched from a candidate.
self.assertEqual(self.lib.albums()[0].mb_albumid, "")
@ -409,10 +407,8 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
# Check that 'title' field is modified, and other fields come from
# the candidate.
self.assertTrue(
all("Edited Track " in i.title for i in self.lib.items())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
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.
self.assertIn("albumid", self.lib.albums()[0].mb_albumid)
@ -439,10 +435,8 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
# Check that 'title' field is modified, and other fields come from
# the candidate.
self.assertTrue(
all("Edited Track " in i.title for i in self.lib.items())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
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.
self.assertIn("albumid", self.lib.albums()[0].mb_albumid)
@ -460,10 +454,8 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
# Check that 'title' field is modified, and other fields come from
# the candidate.
self.assertTrue(
all("Edited Track " in i.title for i in self.lib.items())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
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.
self.assertIn("albumid", self.lib.albums()[0].mb_albumid)
@ -481,10 +473,8 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
# Check that 'title' field is modified, and other fields come from
# the candidate.
self.assertTrue(
all("Edited Track " in i.title for i in self.lib.items())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
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()
@ -511,6 +501,4 @@ class EditDuringImporterSingletonTest(EditDuringImporterTestCase):
["title"],
self.IGNORED + ["albumartist", "mb_albumartistid"],
)
self.assertTrue(
all("Edited Track" in i.title for i in self.lib.items())
)
assert all("Edited Track" in i.title for i in self.lib.items())

View file

@ -308,7 +308,7 @@ class ArtSimilarityTest(unittest.TestCase):
def test_compare_success_similar(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err")
self.assertTrue(self._similarity(20))
assert self._similarity(20)
def test_compare_success_different(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err")
@ -316,7 +316,7 @@ class ArtSimilarityTest(unittest.TestCase):
def test_compare_status1_similar(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10")
self.assertTrue(self._similarity(20))
assert self._similarity(20)
def test_compare_status1_different(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10")

View file

@ -160,12 +160,12 @@ class FtInTitlePluginTest(unittest.TestCase):
self.assertEqual(parts, ("Alice defeat Bob", None))
def test_contains_feat(self):
self.assertTrue(ftintitle.contains_feat("Alice ft. Bob"))
self.assertTrue(ftintitle.contains_feat("Alice feat. Bob"))
self.assertTrue(ftintitle.contains_feat("Alice feat Bob"))
self.assertTrue(ftintitle.contains_feat("Alice featuring Bob"))
self.assertTrue(ftintitle.contains_feat("Alice & Bob"))
self.assertTrue(ftintitle.contains_feat("Alice and Bob"))
self.assertTrue(ftintitle.contains_feat("Alice With Bob"))
assert ftintitle.contains_feat("Alice ft. Bob")
assert ftintitle.contains_feat("Alice feat. Bob")
assert ftintitle.contains_feat("Alice feat Bob")
assert ftintitle.contains_feat("Alice featuring Bob")
assert ftintitle.contains_feat("Alice & Bob")
assert ftintitle.contains_feat("Alice and Bob")
assert ftintitle.contains_feat("Alice With Bob")
self.assertFalse(ftintitle.contains_feat("Alice defeat Bob"))
self.assertFalse(ftintitle.contains_feat("Aliceft.Bob"))

View file

@ -104,7 +104,7 @@ class HookCommandTest(HookTestCase):
plugins.send(event, path=path)
else:
plugins.send(event)
self.assertTrue(os.path.isfile(path))
assert os.path.isfile(path)
@unittest.skipIf(sys.platform == "win32", "win32")
def test_hook_no_arguments(self):

View file

@ -20,11 +20,11 @@ class IHatePluginTest(unittest.TestCase):
# 1 query match.
match_pattern = ["artist:bad_artist", "artist:TestArtist"]
self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern))
assert IHatePlugin.do_i_hate_this(task, match_pattern)
# 2 query matches, either should trigger.
match_pattern = ["album:test", "artist:testartist"]
self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern))
assert IHatePlugin.do_i_hate_this(task, match_pattern)
# Query is blocked by AND clause.
match_pattern = ["album:notthis genre:testgenre"]
@ -42,4 +42,4 @@ class IHatePluginTest(unittest.TestCase):
"album:testalbum genre:testgenre",
"artist:testartist album:notthis",
]
self.assertTrue(IHatePlugin.do_i_hate_this(task, match_pattern))
assert IHatePlugin.do_i_hate_this(task, match_pattern)

View file

@ -27,7 +27,7 @@ class ImportfeedsTestTest(BeetsTestCase):
playlist_path = os.path.join(
self.feeds_dir, os.listdir(self.feeds_dir)[0]
)
self.assertTrue(playlist_path.endswith("album_name.m3u"))
assert playlist_path.endswith("album_name.m3u")
with open(playlist_path) as playlist:
self.assertIn(item_path, playlist.read())
@ -47,8 +47,8 @@ class ImportfeedsTestTest(BeetsTestCase):
self.feeds_dir, config["importfeeds"]["m3u_name"].get()
)
playlist_subdir = os.path.dirname(playlist)
self.assertTrue(os.path.isdir(playlist_subdir))
self.assertTrue(os.path.isfile(playlist))
assert os.path.isdir(playlist_subdir)
assert os.path.isfile(playlist)
def test_playlist_per_session(self):
config["importfeeds"]["formats"] = "m3u_session"
@ -63,6 +63,6 @@ class ImportfeedsTestTest(BeetsTestCase):
self.importfeeds.album_imported(self.lib, album)
date = datetime.datetime.now().strftime("%Y%m%d_%Hh%M")
playlist = os.path.join(self.feeds_dir, f"imports_{date}.m3u")
self.assertTrue(os.path.isfile(playlist))
assert os.path.isfile(playlist)
with open(playlist) as playlist_contents:
self.assertIn(item_path, playlist_contents.read())

View file

@ -49,7 +49,7 @@ class IPFSPluginTest(PluginTestCase):
found = True
except AttributeError:
pass
self.assertTrue(found)
assert found
def mk_test_album(self):
items = [_common.item() for _ in range(3)]

View file

@ -379,7 +379,7 @@ class LyricsPluginSourcesTest(LyricsGoogleBaseTest, LyricsAssertions):
for s in sources:
url = s["url"] + s["path"]
res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url))
self.assertTrue(google.is_lyrics(res), url)
assert google.is_lyrics(res), url
self.assertLyricsContentOk(s["title"], res, url)
@ -403,7 +403,7 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest, LyricsAssertions):
"""Test that lyrics of the mocked page are correctly scraped"""
url = self.source["url"] + self.source["path"]
res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url))
self.assertTrue(google.is_lyrics(res), url)
assert google.is_lyrics(res), url
self.assertLyricsContentOk(self.source["title"], res, url)
@patch.object(lyrics.Backend, "fetch_url", MockFetchUrl())
@ -419,12 +419,9 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest, LyricsAssertions):
soup = BeautifulSoup(
html, "html.parser", parse_only=SoupStrainer("title")
)
self.assertTrue(
google.is_page_candidate(
url, soup.title.string, s["title"], s["artist"]
),
url,
)
assert google.is_page_candidate(
url, soup.title.string, s["title"], s["artist"]
), url
def test_is_page_candidate_fuzzy_match(self):
"""Test matching html page title with song infos -- when song infos are
@ -435,10 +432,9 @@ class LyricsGooglePluginMachineryTest(LyricsGoogleBaseTest, LyricsAssertions):
url_title = "example.com | Beats song by John doe"
# very small diffs (typo) are ok eg 'beats' vs 'beets' with same artist
self.assertTrue(
google.is_page_candidate(url, url_title, s["title"], s["artist"]),
url,
)
assert google.is_page_candidate(
url, url_title, s["title"], s["artist"]
), url
# reject different title
url_title = "example.com | seets bong lyrics by John doe"
self.assertFalse(

View file

@ -377,10 +377,8 @@ class BPDTestHelper(PluginTestCase):
def _assert_ok(self, *responses):
for response in responses:
self.assertTrue(response is not None)
self.assertTrue(
response.ok, "Response failed: {}".format(response.err_data)
)
assert response is not None
assert response.ok, "Response failed: {}".format(response.err_data)
def _assert_failed(self, response, code, pos=None):
"""Check that a command failed with a specific error code. If this

View file

@ -114,16 +114,16 @@ class SmartPlaylistTest(BeetsTestCase):
query = Mock()
query.match.side_effect = {i: True}.__getitem__
self.assertTrue(spl.matches(i, query, None))
assert spl.matches(i, query, None)
self.assertFalse(spl.matches(a, query, None))
a_query = Mock()
a_query.match.side_effect = {a: True}.__getitem__
self.assertFalse(spl.matches(i, None, a_query))
self.assertTrue(spl.matches(a, None, a_query))
assert spl.matches(a, None, a_query)
self.assertTrue(spl.matches(i, query, a_query))
self.assertTrue(spl.matches(a, query, a_query))
assert spl.matches(i, query, a_query)
assert spl.matches(a, query, a_query)
def test_db_changes(self):
spl = SmartPlaylistPlugin()

View file

@ -47,7 +47,7 @@ class SpotifyPluginTest(BeetsTestCase):
opts = ArgumentsMock("fail", True)
self.assertFalse(self.spotify._parse_opts(opts))
opts = ArgumentsMock("list", False)
self.assertTrue(self.spotify._parse_opts(opts))
assert self.spotify._parse_opts(opts)
def test_empty_query(self):
self.assertIsNone(self.spotify._match_library_tracks(self.lib, "1=2"))

View file

@ -74,7 +74,7 @@ class ThumbnailsTest(BeetsTestCase):
mock_os.path.exists = exists
plugin = ThumbnailsPlugin()
mock_os.makedirs.assert_called_once_with(syspath(NORMAL_DIR))
self.assertTrue(plugin._check_local_ok())
assert plugin._check_local_ok()
# test metadata writer function
mock_os.path.exists = lambda _: True
@ -86,7 +86,7 @@ class ThumbnailsTest(BeetsTestCase):
mock_artresizer.shared.local = True
mock_artresizer.shared.can_write_metadata = True
self.assertTrue(ThumbnailsPlugin()._check_local_ok())
assert ThumbnailsPlugin()._check_local_ok()
# test URI getter function
giouri_inst = mock_giouri.return_value

View file

@ -85,7 +85,7 @@ class TypesPluginTest(PluginTestCase):
# Set true
self.modify("mybool=1", "artist:true")
true.load()
self.assertTrue(true["mybool"])
assert true["mybool"]
# Set false
self.modify("mybool=false", "artist:false")

View file

@ -331,7 +331,7 @@ class WebPluginTest(ItemInDBTestCase):
# Create an item with a file
ipath = os.path.join(self.temp_dir, b"testfile1.mp3")
shutil.copy(os.path.join(_common.RSRC, b"full.mp3"), ipath)
self.assertTrue(os.path.exists(ipath))
assert os.path.exists(ipath)
item_id = self.lib.add(Item.from_path(ipath))
# Check we can find the temporary item we just created
@ -350,7 +350,7 @@ class WebPluginTest(ItemInDBTestCase):
self.assertEqual(response.status_code, 404)
# Check the file has not gone
self.assertTrue(os.path.exists(ipath))
assert os.path.exists(ipath)
os.remove(ipath)
def test_delete_item_with_file(self):
@ -359,7 +359,7 @@ class WebPluginTest(ItemInDBTestCase):
# Create an item with a file
ipath = os.path.join(self.temp_dir, b"testfile2.mp3")
shutil.copy(os.path.join(_common.RSRC, b"full.mp3"), ipath)
self.assertTrue(os.path.exists(ipath))
assert os.path.exists(ipath)
item_id = self.lib.add(Item.from_path(ipath))
# Check we can find the temporary item we just created
@ -670,7 +670,7 @@ class WebPluginTest(ItemInDBTestCase):
def test_get_item_file(self):
ipath = os.path.join(self.temp_dir, b"testfile2.mp3")
shutil.copy(os.path.join(_common.RSRC, b"full.mp3"), ipath)
self.assertTrue(os.path.exists(ipath))
assert os.path.exists(ipath)
item_id = self.lib.add(Item.from_path(ipath))
response = self.client.get("/item/" + str(item_id) + "/file")

View file

@ -69,7 +69,7 @@ class PluralityTest(BeetsTestCase):
likelies, consensus = match.current_metadata(items)
self.assertEqual(likelies["artist"], "The Beatles")
self.assertEqual(likelies["album"], "The White Album")
self.assertTrue(consensus["artist"])
assert consensus["artist"]
def test_albumartist_consensus(self):
items = [
@ -464,7 +464,7 @@ class AlbumDistanceTest(BeetsTestCase):
va=False,
)
dist = self._dist(items, info)
self.assertTrue(0 < dist < 0.2)
assert 0 < dist < 0.2
def test_two_medium_release(self):
items = []
@ -993,8 +993,8 @@ class ApplyCompilationTest(BeetsTestCase, ApplyTestUtil):
va_info = self.info.copy()
va_info.va = True
self._apply(info=va_info)
self.assertTrue(self.items[0].comp)
self.assertTrue(self.items[1].comp)
assert self.items[0].comp
assert self.items[1].comp
class StringDistanceTest(unittest.TestCase):

View file

@ -139,7 +139,7 @@ class DateIntervalTest(unittest.TestCase):
date = _date(date_pattern)
(start, end) = _parse_periods(interval_pattern)
interval = DateInterval.from_periods(start, end)
self.assertTrue(interval.contains(date))
assert interval.contains(date)
def assertExcludes(self, interval_pattern, date_pattern): # noqa
date = _date(date_pattern)
@ -170,7 +170,7 @@ class DateQueryTest(ItemInDBTestCase):
def test_single_month_match_slow(self):
query = DateQuery("added", "2013-03")
self.assertTrue(query.match(self.i))
assert query.match(self.i)
def test_single_month_nonmatch_slow(self):
query = DateQuery("added", "2013-04")
@ -212,7 +212,7 @@ class DateQueryTestRelative(ItemInDBTestCase):
def test_single_month_match_slow(self):
query = DateQuery("added", self._now.strftime("%Y-%m"))
self.assertTrue(query.match(self.i))
assert query.match(self.i)
def test_single_month_nonmatch_slow(self):
query = DateQuery(

View file

@ -455,7 +455,7 @@ class FormatTest(unittest.TestCase):
model = ModelFixture1()
model.other_field = "caf\xe9".encode()
value = model.formatted().get("other_field")
self.assertTrue(isinstance(value, str))
assert isinstance(value, str)
self.assertEqual(value, "caf\xe9")
def test_format_unset_field(self):

View file

@ -146,7 +146,7 @@ class MoveTest(BeetsTestCase):
try:
self.i.move(operation=MoveOperation.COPY)
self.assertTrue(os.access(syspath(self.i.path), os.W_OK))
assert os.access(syspath(self.i.path), os.W_OK)
finally:
# Make everything writable so it can be cleaned up.
os.chmod(syspath(self.path), 0o777)
@ -166,7 +166,7 @@ class MoveTest(BeetsTestCase):
def test_link_arrives(self):
self.i.move(operation=MoveOperation.LINK)
self.assertExists(self.dest)
self.assertTrue(os.path.islink(syspath(self.dest)))
assert os.path.islink(syspath(self.dest))
self.assertEqual(
bytestring_path(os.readlink(syspath(self.dest))),
self.path,
@ -188,9 +188,9 @@ class MoveTest(BeetsTestCase):
self.assertExists(self.dest)
s1 = os.stat(syspath(self.path))
s2 = os.stat(syspath(self.dest))
self.assertTrue(
(s1[stat.ST_INO], s1[stat.ST_DEV])
== (s2[stat.ST_INO], s2[stat.ST_DEV])
assert (s1[stat.ST_INO], s1[stat.ST_DEV]) == (
s2[stat.ST_INO],
s2[stat.ST_DEV],
)
@unittest.skipUnless(_common.HAVE_HARDLINK, "need hardlinks")
@ -265,7 +265,7 @@ class AlbumFileTest(BeetsTestCase):
self.ai.store()
self.i.load()
self.assertTrue(b"newAlbumName" in self.i.path)
assert b"newAlbumName" in self.i.path
def test_albuminfo_move_moves_file(self):
oldpath = self.i.path
@ -295,8 +295,8 @@ class AlbumFileTest(BeetsTestCase):
self.ai.store()
self.i.load()
self.assertTrue(os.path.exists(oldpath))
self.assertTrue(os.path.exists(self.i.path))
assert os.path.exists(oldpath)
assert os.path.exists(self.i.path)
def test_albuminfo_move_to_custom_dir(self):
self.ai.move(basedir=self.otherdir)
@ -437,8 +437,8 @@ class ArtFileTest(BeetsTestCase):
ai.set_art(newart)
mode = stat.S_IMODE(os.stat(syspath(ai.artpath)).st_mode)
self.assertTrue(mode & stat.S_IRGRP)
self.assertTrue(os.access(syspath(ai.artpath), os.W_OK))
assert mode & stat.S_IRGRP
assert os.access(syspath(ai.artpath), os.W_OK)
finally:
# Make everything writable so it can be cleaned up.
@ -454,7 +454,7 @@ class ArtFileTest(BeetsTestCase):
self.ai.items()[0].move()
artpath = self.lib.albums()[0].artpath
self.assertTrue(b"different_album" in artpath)
assert b"different_album" in artpath
self.assertExists(artpath)
self.assertNotExists(oldartpath)

View file

@ -45,7 +45,7 @@ class HiddenFileTest(unittest.TestCase):
else:
raise e
self.assertTrue(hidden.is_hidden(f.name))
assert hidden.is_hidden(f.name)
def test_windows_hidden(self):
if not sys.platform == "win32":
@ -64,7 +64,7 @@ class HiddenFileTest(unittest.TestCase):
if not success:
self.skipTest("unable to set file attributes")
self.assertTrue(hidden.is_hidden(f.name))
assert hidden.is_hidden(f.name)
def test_other_hidden(self):
if sys.platform == "darwin" or sys.platform == "win32":
@ -73,4 +73,4 @@ class HiddenFileTest(unittest.TestCase):
with tempfile.NamedTemporaryFile(prefix=".tmp") as f:
fn = util.bytestring_path(f.name)
self.assertTrue(hidden.is_hidden(fn))
assert hidden.is_hidden(fn)

View file

@ -184,7 +184,7 @@ class NonAutotaggedImportTest(AsIsImporterMixin, ImportTestCase):
util.bytestring_path(f"{mediafile.title}.mp3"),
)
self.assertExists(filename)
self.assertTrue(os.path.islink(syspath(filename)))
assert os.path.islink(syspath(filename))
self.assert_equal_path(
util.bytestring_path(os.readlink(syspath(filename))),
mediafile.path,
@ -203,9 +203,9 @@ class NonAutotaggedImportTest(AsIsImporterMixin, ImportTestCase):
self.assertExists(filename)
s1 = os.stat(syspath(mediafile.path))
s2 = os.stat(syspath(filename))
self.assertTrue(
(s1[stat.ST_INO], s1[stat.ST_DEV])
== (s2[stat.ST_INO], s2[stat.ST_DEV])
assert (s1[stat.ST_INO], s1[stat.ST_DEV]) == (
s2[stat.ST_INO],
s2[stat.ST_DEV],
)
@unittest.skipUnless(_common.HAVE_REFLINK, "need reflinks")
@ -711,7 +711,7 @@ class ImportCompilationTest(ImportTestCase):
self.importer.add_choice(importer.action.ASIS)
self.importer.run()
for item in self.lib.items():
self.assertTrue(item.comp)
assert item.comp
def test_asis_sets_majority_albumartist(self):
self.import_media[0].artist = "Other Artist"
@ -786,7 +786,7 @@ class ImportCompilationTest(ImportTestCase):
item.artists, ["Another Artist", "Another Artist 2"]
)
self.assertTrue(asserted_multi_artists_0 and asserted_multi_artists_1)
assert asserted_multi_artists_0 and asserted_multi_artists_1
class ImportExistingTest(ImportTestCase):
@ -1037,7 +1037,7 @@ class InferAlbumDataTest(BeetsTestCase):
self.task.align_album_level_fields()
self.assertTrue(self.items[0].comp)
assert self.items[0].comp
self.assertEqual(self.items[0].albumartist, "Various Artists")
def test_asis_comp_applied_to_all_items(self):
@ -1048,7 +1048,7 @@ class InferAlbumDataTest(BeetsTestCase):
self.task.align_album_level_fields()
for item in self.items:
self.assertTrue(item.comp)
assert item.comp
self.assertEqual(item.albumartist, "Various Artists")
def test_asis_majority_artist_single_artist(self):

View file

@ -354,7 +354,7 @@ class DestinationTest(BeetsTestCase):
with _common.platform_posix():
self.i.track = 1
name = self.i.formatted().get("track")
self.assertTrue(name.startswith("0"))
assert name.startswith("0")
def test_get_formatted_uses_kbps_bitrate(self):
with _common.platform_posix():
@ -372,7 +372,7 @@ class DestinationTest(BeetsTestCase):
with _common.platform_posix():
self.i.added = 1368302461.210265
val = self.i.formatted().get("added")
self.assertTrue(val.startswith("2013"))
assert val.startswith("2013")
def test_get_formatted_none(self):
with _common.platform_posix():
@ -1071,15 +1071,15 @@ class PathStringTest(BeetsTestCase):
self.i = item(self.lib)
def test_item_path_is_bytestring(self):
self.assertTrue(isinstance(self.i.path, bytes))
assert isinstance(self.i.path, bytes)
def test_fetched_item_path_is_bytestring(self):
i = list(self.lib.items())[0]
self.assertTrue(isinstance(i.path, bytes))
assert isinstance(i.path, bytes)
def test_unicode_path_becomes_bytestring(self):
self.i.path = "unicodepath"
self.assertTrue(isinstance(self.i.path, bytes))
assert isinstance(self.i.path, bytes)
def test_unicode_in_database_becomes_bytestring(self):
self.lib._connection().execute(
@ -1089,7 +1089,7 @@ class PathStringTest(BeetsTestCase):
(self.i.id, "somepath"),
)
i = list(self.lib.items())[0]
self.assertTrue(isinstance(i.path, bytes))
assert isinstance(i.path, bytes)
def test_special_chars_preserved_in_database(self):
path = "b\xe1r".encode()
@ -1110,13 +1110,13 @@ class PathStringTest(BeetsTestCase):
def test_destination_returns_bytestring(self):
self.i.artist = "b\xe1r"
dest = self.i.destination()
self.assertTrue(isinstance(dest, bytes))
assert isinstance(dest, bytes)
def test_art_destination_returns_bytestring(self):
self.i.artist = "b\xe1r"
alb = self.lib.add_album([self.i])
dest = alb.art_destination("image.jpg")
self.assertTrue(isinstance(dest, bytes))
assert isinstance(dest, bytes)
def test_artpath_stores_special_chars(self):
path = b"b\xe1r"
@ -1129,17 +1129,17 @@ class PathStringTest(BeetsTestCase):
def test_sanitize_path_with_special_chars(self):
path = "b\xe1r?"
new_path = util.sanitize_path(path)
self.assertTrue(new_path.startswith("b\xe1r"))
assert new_path.startswith("b\xe1r")
def test_sanitize_path_returns_unicode(self):
path = "b\xe1r?"
new_path = util.sanitize_path(path)
self.assertTrue(isinstance(new_path, str))
assert isinstance(new_path, str)
def test_unicode_artpath_becomes_bytestring(self):
alb = self.lib.add_album([self.i])
alb.artpath = "somep\xe1th"
self.assertTrue(isinstance(alb.artpath, bytes))
assert isinstance(alb.artpath, bytes)
def test_unicode_artpath_in_database_decoded(self):
alb = self.lib.add_album([self.i])
@ -1147,7 +1147,7 @@ class PathStringTest(BeetsTestCase):
"update albums set artpath=? where id=?", ("somep\xe1th", alb.id)
)
alb = self.lib.get_album(alb.id)
self.assertTrue(isinstance(alb.artpath, bytes))
assert isinstance(alb.artpath, bytes)
class MtimeTest(BeetsTestCase):

View file

@ -48,7 +48,7 @@ class LoggingTest(BeetsTestCase):
l.warning("foo {0} {bar}", "oof", bar="baz")
handler.flush()
self.assertTrue(stream.getvalue(), "foo oof baz")
assert stream.getvalue(), "foo oof baz"
class LoggingLevelTest(AsIsImporterMixin, PluginMixin, ImportTestCase):
@ -217,7 +217,7 @@ class ConcurrentEventsTest(AsIsImporterMixin, ImportTestCase):
t1.start() # blocked. t1 tested its log level
while dp.t1_step != 1:
check_dp_exc()
self.assertTrue(t1.is_alive())
assert t1.is_alive()
self.assertEqual(dp._log.level, log.NOTSET)
self.config["verbose"] = 2
@ -225,7 +225,7 @@ class ConcurrentEventsTest(AsIsImporterMixin, ImportTestCase):
t2.start() # blocked. t2 tested its log level
while dp.t2_step != 1:
check_dp_exc()
self.assertTrue(t2.is_alive())
assert t2.is_alive()
self.assertEqual(dp._log.level, log.NOTSET)
dp.lock1.release() # dummy_event1 tests its log level + finishes
@ -233,7 +233,7 @@ class ConcurrentEventsTest(AsIsImporterMixin, ImportTestCase):
check_dp_exc()
t1.join(0.1)
self.assertFalse(t1.is_alive())
self.assertTrue(t2.is_alive())
assert t2.is_alive()
self.assertEqual(dp._log.level, log.NOTSET)
dp.lock2.release() # dummy_event2 tests its log level + finishes

View file

@ -49,7 +49,7 @@ class M3UFileTest(unittest.TestCase):
]
)
m3ufile.write()
self.assertTrue(path.exists(the_playlist_file))
assert path.exists(the_playlist_file)
rmtree(tempdir)
def test_playlist_write_unicode(self):
@ -64,7 +64,7 @@ class M3UFileTest(unittest.TestCase):
]
)
m3ufile.write()
self.assertTrue(path.exists(the_playlist_file))
assert path.exists(the_playlist_file)
rmtree(tempdir)
@unittest.skipUnless(sys.platform == "win32", "win32")
@ -82,7 +82,7 @@ class M3UFileTest(unittest.TestCase):
]
)
m3ufile.write()
self.assertTrue(path.exists(the_playlist_file))
assert path.exists(the_playlist_file)
m3ufile_read = M3UFile(the_playlist_file)
m3ufile_read.load()
self.assertEqual(
@ -140,7 +140,7 @@ class M3UFileTest(unittest.TestCase):
the_playlist_file = path.join(RSRC, b"playlist.m3u")
m3ufile = M3UFile(the_playlist_file)
m3ufile.load()
self.assertTrue(m3ufile.extm3u)
assert m3ufile.extm3u
def test_playlist_load_non_extm3u(self):
"""Test loading a playlist without an #EXTM3U header."""

View file

@ -342,7 +342,7 @@ class MBAlbumInfoTest(BeetsTestCase):
release = self._make_release(None)
release["artist-credit"][0]["artist"]["id"] = mb.VARIOUS_ARTISTS_ID
d = mb.album_info(release)
self.assertTrue(d.va)
assert d.va
def test_parse_artist_sort_name(self):
release = self._make_release(None)

View file

@ -382,7 +382,7 @@ class GetTest(DummyDataTestCase):
def test_numeric_search_positive(self):
q = dbcore.query.NumericQuery("year", "2001")
results = self.lib.items(q)
self.assertTrue(results)
assert results
def test_numeric_search_negative(self):
q = dbcore.query.NumericQuery("year", "1999")
@ -423,7 +423,7 @@ class MatchTest(BeetsTestCase):
def test_regex_match_positive(self):
q = dbcore.query.RegexpQuery("album", "^the album$")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
def test_regex_match_negative(self):
q = dbcore.query.RegexpQuery("album", "^album$")
@ -431,11 +431,11 @@ class MatchTest(BeetsTestCase):
def test_regex_match_non_string_value(self):
q = dbcore.query.RegexpQuery("disc", "^6$")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
def test_substring_match_positive(self):
q = dbcore.query.SubstringQuery("album", "album")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
def test_substring_match_negative(self):
q = dbcore.query.SubstringQuery("album", "ablum")
@ -443,13 +443,13 @@ class MatchTest(BeetsTestCase):
def test_substring_match_non_string_value(self):
q = dbcore.query.SubstringQuery("disc", "6")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
def test_exact_match_nocase_positive(self):
q = dbcore.query.StringQuery("genre", "the genre")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
q = dbcore.query.StringQuery("genre", "THE GENRE")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
def test_exact_match_nocase_negative(self):
q = dbcore.query.StringQuery("genre", "genre")
@ -457,7 +457,7 @@ class MatchTest(BeetsTestCase):
def test_year_match_positive(self):
q = dbcore.query.NumericQuery("year", "1")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
def test_year_match_negative(self):
q = dbcore.query.NumericQuery("year", "10")
@ -465,7 +465,7 @@ class MatchTest(BeetsTestCase):
def test_bitrate_range_positive(self):
q = dbcore.query.NumericQuery("bitrate", "100000..200000")
self.assertTrue(q.match(self.item))
assert q.match(self.item)
def test_bitrate_range_negative(self):
q = dbcore.query.NumericQuery("bitrate", "200000..300000")
@ -667,13 +667,13 @@ class PathQueryTest(ItemInDBTestCase, AssertsMixin):
is_path_query = beets.library.PathQuery.is_path_query
with self.force_implicit_query_detection():
self.assertTrue(is_path_query("/foo/bar"))
self.assertTrue(is_path_query("foo/bar"))
self.assertTrue(is_path_query("foo/"))
self.assertFalse(is_path_query("foo"))
self.assertTrue(is_path_query("foo/:bar"))
self.assertFalse(is_path_query("foo:bar/"))
self.assertFalse(is_path_query("foo:/bar"))
assert is_path_query("/foo/bar")
assert is_path_query("foo/bar")
assert is_path_query("foo/")
assert not is_path_query("foo")
assert is_path_query("foo/:bar")
assert not is_path_query("foo:bar/")
assert not is_path_query("foo:/bar")
# FIXME: shouldn't this also work on windows?
@unittest.skipIf(sys.platform == "win32", WIN32_NO_IMPLICIT_PATHS)
@ -687,15 +687,15 @@ class PathQueryTest(ItemInDBTestCase, AssertsMixin):
is_path_query = beets.library.PathQuery.is_path_query
path = self.touch(os.path.join(b"foo", b"bar"))
self.assertTrue(os.path.isabs(util.syspath(path)))
assert os.path.isabs(util.syspath(path))
path_str = path.decode("utf-8")
# The file itself.
self.assertTrue(is_path_query(path_str))
assert is_path_query(path_str)
# The parent directory.
parent = os.path.dirname(path_str)
self.assertTrue(is_path_query(parent))
assert is_path_query(parent)
# Some non-existent path.
self.assertFalse(is_path_query(path_str + "baz"))
@ -715,10 +715,10 @@ class PathQueryTest(ItemInDBTestCase, AssertsMixin):
cur_dir = os.getcwd()
try:
os.chdir(syspath(self.temp_dir))
self.assertTrue(is_path_query("foo/"))
self.assertTrue(is_path_query("foo/bar"))
self.assertTrue(is_path_query("foo/bar:tagada"))
self.assertFalse(is_path_query("bar"))
assert is_path_query("foo/")
assert is_path_query("foo/bar")
assert is_path_query("foo/bar:tagada")
assert not is_path_query("bar")
finally:
os.chdir(cur_dir)
@ -868,7 +868,7 @@ class NoneQueryTest(BeetsTestCase, AssertsMixin):
class NotQueryMatchTest(BeetsTestCase):
"""Test `query.NotQuery` matching against a single item, using the same
cases and assertions as on `MatchTest`, plus assertion on the negated
queries (ie. assertTrue(q) -> assertFalse(NotQuery(q))).
queries (ie. assert q -> assert not NotQuery(q)).
"""
def setUp(self):
@ -877,53 +877,53 @@ class NotQueryMatchTest(BeetsTestCase):
def test_regex_match_positive(self):
q = dbcore.query.RegexpQuery("album", "^the album$")
self.assertTrue(q.match(self.item))
self.assertFalse(dbcore.query.NotQuery(q).match(self.item))
assert q.match(self.item)
assert not dbcore.query.NotQuery(q).match(self.item)
def test_regex_match_negative(self):
q = dbcore.query.RegexpQuery("album", "^album$")
self.assertFalse(q.match(self.item))
self.assertTrue(dbcore.query.NotQuery(q).match(self.item))
assert not q.match(self.item)
assert dbcore.query.NotQuery(q).match(self.item)
def test_regex_match_non_string_value(self):
q = dbcore.query.RegexpQuery("disc", "^6$")
self.assertTrue(q.match(self.item))
self.assertFalse(dbcore.query.NotQuery(q).match(self.item))
assert q.match(self.item)
assert not dbcore.query.NotQuery(q).match(self.item)
def test_substring_match_positive(self):
q = dbcore.query.SubstringQuery("album", "album")
self.assertTrue(q.match(self.item))
self.assertFalse(dbcore.query.NotQuery(q).match(self.item))
assert q.match(self.item)
assert not dbcore.query.NotQuery(q).match(self.item)
def test_substring_match_negative(self):
q = dbcore.query.SubstringQuery("album", "ablum")
self.assertFalse(q.match(self.item))
self.assertTrue(dbcore.query.NotQuery(q).match(self.item))
assert not q.match(self.item)
assert dbcore.query.NotQuery(q).match(self.item)
def test_substring_match_non_string_value(self):
q = dbcore.query.SubstringQuery("disc", "6")
self.assertTrue(q.match(self.item))
self.assertFalse(dbcore.query.NotQuery(q).match(self.item))
assert q.match(self.item)
assert not dbcore.query.NotQuery(q).match(self.item)
def test_year_match_positive(self):
q = dbcore.query.NumericQuery("year", "1")
self.assertTrue(q.match(self.item))
self.assertFalse(dbcore.query.NotQuery(q).match(self.item))
assert q.match(self.item)
assert not dbcore.query.NotQuery(q).match(self.item)
def test_year_match_negative(self):
q = dbcore.query.NumericQuery("year", "10")
self.assertFalse(q.match(self.item))
self.assertTrue(dbcore.query.NotQuery(q).match(self.item))
assert not q.match(self.item)
assert dbcore.query.NotQuery(q).match(self.item)
def test_bitrate_range_positive(self):
q = dbcore.query.NumericQuery("bitrate", "100000..200000")
self.assertTrue(q.match(self.item))
self.assertFalse(dbcore.query.NotQuery(q).match(self.item))
assert q.match(self.item)
assert not dbcore.query.NotQuery(q).match(self.item)
def test_bitrate_range_negative(self):
q = dbcore.query.NumericQuery("bitrate", "200000..300000")
self.assertFalse(q.match(self.item))
self.assertTrue(dbcore.query.NotQuery(q).match(self.item))
assert not q.match(self.item)
assert dbcore.query.NotQuery(q).match(self.item)
def test_open_range(self):
q = dbcore.query.NumericQuery("bitrate", "100000..")

View file

@ -527,6 +527,6 @@ class NonExistingFieldTest(DummyDataTestCase):
"-bar+", beets.library.Item
)
self.assertEqual(len(query.subqueries), 1)
self.assertTrue(isinstance(query.subqueries[0], dbcore.query.TrueQuery))
self.assertTrue(isinstance(sort, dbcore.query.SlowFieldSort))
assert isinstance(query.subqueries[0], dbcore.query.TrueQuery)
assert isinstance(sort, dbcore.query.SlowFieldSort)
self.assertEqual(sort.field, "-bar")

View file

@ -53,8 +53,8 @@ class ParseTest(unittest.TestCase):
def _assert_symbol(self, obj, ident):
"""Assert that an object is a Symbol with the given identifier."""
self.assertTrue(
isinstance(obj, functemplate.Symbol), "not a Symbol: %s" % repr(obj)
assert isinstance(obj, functemplate.Symbol), "not a Symbol: %s" % repr(
obj
)
self.assertEqual(
obj.ident,
@ -66,9 +66,7 @@ class ParseTest(unittest.TestCase):
"""Assert that an object is a Call with the given identifier and
argument count.
"""
self.assertTrue(
isinstance(obj, functemplate.Call), "not a Call: %s" % repr(obj)
)
assert isinstance(obj, functemplate.Call), "not a Call: %s" % repr(obj)
self.assertEqual(
obj.ident,
ident,
@ -277,7 +275,7 @@ class EvalTest(unittest.TestCase):
def test_function_call_exception(self):
res = self._eval("%lower{a,b,c,d,e}")
self.assertTrue(isinstance(res, str))
assert isinstance(res, str)
def test_function_returning_integer(self):
self.assertEqual(self._eval("%len{foo}"), "3")

View file

@ -594,14 +594,14 @@ class UpdateTest(BeetsTestCase):
)
def test_delete_removes_item(self):
self.assertTrue(list(self.lib.items()))
assert list(self.lib.items())
util.remove(self.i.path)
util.remove(self.i2.path)
self._update()
self.assertFalse(list(self.lib.items()))
def test_delete_removes_album(self):
self.assertTrue(self.lib.albums())
assert self.lib.albums()
util.remove(self.i.path)
util.remove(self.i2.path)
self._update()
@ -1070,7 +1070,7 @@ class ConfigTest(TestPluginTestCase):
file.write("plugins: test")
self.run_command("--config", cli_config_path, "plugin", lib=None)
self.assertTrue(plugins.find_plugins()[0].is_test_plugin)
assert plugins.find_plugins()[0].is_test_plugin
self.unload_plugins()
def test_beetsdir_config(self):
@ -1151,13 +1151,13 @@ class ShowModelChangeTest(BeetsTestCase):
def test_string_fixed_field_change(self):
self.b.title = "x"
change, out = self._show()
self.assertTrue(change)
assert change
self.assertIn("title", out)
def test_int_fixed_field_change(self):
self.b.track = 9
change, out = self._show()
self.assertTrue(change)
assert change
self.assertIn("track", out)
def test_floats_close_to_identical(self):
@ -1171,7 +1171,7 @@ class ShowModelChangeTest(BeetsTestCase):
self.a.length = 1.00001
self.b.length = 2.00001
change, out = self._show()
self.assertTrue(change)
assert change
self.assertIn("length", out)
def test_both_values_shown(self):
@ -1241,27 +1241,27 @@ class ShowChangeTest(BeetsTestCase):
def test_item_data_change(self):
self.items[0].title = "different"
msg = self._show_change()
self.assertTrue("different" in msg and "the title" in msg)
assert "different" in msg and "the title" in msg
def test_item_data_change_with_unicode(self):
self.items[0].title = "caf\xe9"
msg = self._show_change()
self.assertTrue("caf\xe9" in msg and "the title" in msg)
assert "caf\xe9" in msg and "the title" in msg
def test_album_data_change_with_unicode(self):
msg = self._show_change(cur_artist="caf\xe9", cur_album="another album")
self.assertTrue("caf\xe9" in msg and "the artist" in msg)
assert "caf\xe9" in msg and "the artist" in msg
def test_item_data_change_title_missing(self):
self.items[0].title = ""
msg = re.sub(r" +", " ", self._show_change())
self.assertTrue("file.mp3" in msg and "the title" in msg)
assert "file.mp3" in msg and "the title" in msg
def test_item_data_change_title_missing_with_unicode_filename(self):
self.items[0].title = ""
self.items[0].path = "/path/to/caf\xe9.mp3".encode()
msg = re.sub(r" +", " ", self._show_change())
self.assertTrue("caf\xe9.mp3" in msg or "caf.mp3" in msg)
assert "caf\xe9.mp3" in msg or "caf.mp3" in msg
def test_colorize(self):
self.assertEqual("test", ui.uncolorize("test"))
@ -1530,7 +1530,7 @@ class CommonOptionsParserTest(BeetsTestCase):
parser = ui.CommonOptionsParser()
self.assertFalse(parser._album_flags)
parser.add_album_option()
self.assertTrue(bool(parser._album_flags))
assert bool(parser._album_flags)
self.assertEqual(parser.parse_args([]), ({"album": None}, []))
self.assertEqual(parser.parse_args(["-a"]), ({"album": True}, []))

View file

@ -163,8 +163,8 @@ class PathConversionTest(BeetsTestCase):
with _common.platform_windows():
path = os.path.join("a", "b", "c")
outpath = util.syspath(path)
self.assertTrue(isinstance(outpath, str))
self.assertTrue(outpath.startswith("\\\\?\\"))
assert isinstance(outpath, str)
assert outpath.startswith("\\\\?\\")
def test_syspath_windows_format_unc_path(self):
# The \\?\ prefix on Windows behaves differently with UNC
@ -172,7 +172,7 @@ class PathConversionTest(BeetsTestCase):
path = "\\\\server\\share\\file.mp3"
with _common.platform_windows():
outpath = util.syspath(path)
self.assertTrue(isinstance(outpath, str))
assert isinstance(outpath, str)
self.assertEqual(outpath, "\\\\?\\UNC\\server\\share\\file.mp3")
def test_syspath_posix_unchanged(self):