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

View file

@ -300,7 +300,7 @@ class ConvertCliTest(ConvertTestCase, ConvertCommand):
with control_stdin("y"): with control_stdin("y"):
self.run_convert("--playlist", "playlist.m3u8") self.run_convert("--playlist", "playlist.m3u8")
m3u_created = os.path.join(self.convert_dest, b"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): def test_playlist_pretend(self):
self.run_convert("--playlist", "playlist.m3u8", "--pretend") 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.albums()), album_count)
self.assertEqual(len(self.lib.items()), track_count) self.assertEqual(len(self.lib.items()), track_count)
self.assertEqual(mock_write.call_count, write_call_count) self.assertEqual(mock_write.call_count, write_call_count)
self.assertTrue( assert all(
all(i.title.startswith(title_starts_with) for i in self.lib.items()) i.title.startswith(title_starts_with) for i in self.lib.items()
) )
def test_title_edit_discard(self, mock_write): def test_title_edit_discard(self, mock_write):
@ -366,9 +366,7 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
"mb_albumartistids", "mb_albumartistids",
], ],
) )
self.assertTrue( assert all("Edited Track" in i.title for i in self.lib.items())
all("Edited Track" in i.title for i in self.lib.items())
)
# Ensure album is *not* fetched from a candidate. # Ensure album is *not* fetched from a candidate.
self.assertEqual(self.lib.albums()[0].mb_albumid, "") self.assertEqual(self.lib.albums()[0].mb_albumid, "")
@ -391,7 +389,7 @@ class EditDuringImporterNonSingletonTest(EditDuringImporterTestCase):
[], [],
self.IGNORED + ["albumartist", "mb_albumartistid"], 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. # Ensure album is *not* fetched from a candidate.
self.assertEqual(self.lib.albums()[0].mb_albumid, "") 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 # Check that 'title' field is modified, and other fields come from
# the candidate. # the candidate.
self.assertTrue( assert all("Edited Track " in i.title for i in self.lib.items())
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())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
# Ensure album is fetched from a candidate. # Ensure album is fetched from a candidate.
self.assertIn("albumid", self.lib.albums()[0].mb_albumid) 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 # Check that 'title' field is modified, and other fields come from
# the candidate. # the candidate.
self.assertTrue( assert all("Edited Track " in i.title for i in self.lib.items())
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())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
# Ensure album is fetched from a candidate. # Ensure album is fetched from a candidate.
self.assertIn("albumid", self.lib.albums()[0].mb_albumid) 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 # Check that 'title' field is modified, and other fields come from
# the candidate. # the candidate.
self.assertTrue( assert all("Edited Track " in i.title for i in self.lib.items())
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())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
# Ensure album is fetched from a candidate. # Ensure album is fetched from a candidate.
self.assertIn("albumid", self.lib.albums()[0].mb_albumid) 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 # Check that 'title' field is modified, and other fields come from
# the candidate. # the candidate.
self.assertTrue( assert all("Edited Track " in i.title for i in self.lib.items())
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())
)
self.assertTrue(all("match " in i.mb_trackid for i in self.lib.items()))
@_common.slow_test() @_common.slow_test()
@ -511,6 +501,4 @@ class EditDuringImporterSingletonTest(EditDuringImporterTestCase):
["title"], ["title"],
self.IGNORED + ["albumartist", "mb_albumartistid"], self.IGNORED + ["albumartist", "mb_albumartistid"],
) )
self.assertTrue( assert all("Edited Track" in i.title for i in self.lib.items())
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): def test_compare_success_similar(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err") 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): def test_compare_success_different(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 0, "10", "err") 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): def test_compare_status1_similar(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10") 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): def test_compare_status1_different(self, mock_extract, mock_subprocess):
self._mock_popens(mock_extract, mock_subprocess, 1, "out", "10") 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)) self.assertEqual(parts, ("Alice defeat Bob", None))
def test_contains_feat(self): def test_contains_feat(self):
self.assertTrue(ftintitle.contains_feat("Alice ft. Bob")) assert ftintitle.contains_feat("Alice ft. Bob")
self.assertTrue(ftintitle.contains_feat("Alice feat. Bob")) assert ftintitle.contains_feat("Alice feat. Bob")
self.assertTrue(ftintitle.contains_feat("Alice feat Bob")) assert ftintitle.contains_feat("Alice feat Bob")
self.assertTrue(ftintitle.contains_feat("Alice featuring Bob")) assert ftintitle.contains_feat("Alice featuring Bob")
self.assertTrue(ftintitle.contains_feat("Alice & Bob")) assert ftintitle.contains_feat("Alice & Bob")
self.assertTrue(ftintitle.contains_feat("Alice and Bob")) assert ftintitle.contains_feat("Alice and Bob")
self.assertTrue(ftintitle.contains_feat("Alice With Bob")) assert ftintitle.contains_feat("Alice With Bob")
self.assertFalse(ftintitle.contains_feat("Alice defeat Bob")) self.assertFalse(ftintitle.contains_feat("Alice defeat Bob"))
self.assertFalse(ftintitle.contains_feat("Aliceft.Bob")) self.assertFalse(ftintitle.contains_feat("Aliceft.Bob"))

View file

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

View file

@ -20,11 +20,11 @@ class IHatePluginTest(unittest.TestCase):
# 1 query match. # 1 query match.
match_pattern = ["artist:bad_artist", "artist:TestArtist"] 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. # 2 query matches, either should trigger.
match_pattern = ["album:test", "artist:testartist"] 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. # Query is blocked by AND clause.
match_pattern = ["album:notthis genre:testgenre"] match_pattern = ["album:notthis genre:testgenre"]
@ -42,4 +42,4 @@ class IHatePluginTest(unittest.TestCase):
"album:testalbum genre:testgenre", "album:testalbum genre:testgenre",
"artist:testartist album:notthis", "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( playlist_path = os.path.join(
self.feeds_dir, os.listdir(self.feeds_dir)[0] 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: with open(playlist_path) as playlist:
self.assertIn(item_path, playlist.read()) self.assertIn(item_path, playlist.read())
@ -47,8 +47,8 @@ class ImportfeedsTestTest(BeetsTestCase):
self.feeds_dir, config["importfeeds"]["m3u_name"].get() self.feeds_dir, config["importfeeds"]["m3u_name"].get()
) )
playlist_subdir = os.path.dirname(playlist) playlist_subdir = os.path.dirname(playlist)
self.assertTrue(os.path.isdir(playlist_subdir)) assert os.path.isdir(playlist_subdir)
self.assertTrue(os.path.isfile(playlist)) assert os.path.isfile(playlist)
def test_playlist_per_session(self): def test_playlist_per_session(self):
config["importfeeds"]["formats"] = "m3u_session" config["importfeeds"]["formats"] = "m3u_session"
@ -63,6 +63,6 @@ class ImportfeedsTestTest(BeetsTestCase):
self.importfeeds.album_imported(self.lib, album) self.importfeeds.album_imported(self.lib, album)
date = datetime.datetime.now().strftime("%Y%m%d_%Hh%M") date = datetime.datetime.now().strftime("%Y%m%d_%Hh%M")
playlist = os.path.join(self.feeds_dir, f"imports_{date}.m3u") 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: with open(playlist) as playlist_contents:
self.assertIn(item_path, playlist_contents.read()) self.assertIn(item_path, playlist_contents.read())

View file

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

View file

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

View file

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

View file

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

View file

@ -47,7 +47,7 @@ class SpotifyPluginTest(BeetsTestCase):
opts = ArgumentsMock("fail", True) opts = ArgumentsMock("fail", True)
self.assertFalse(self.spotify._parse_opts(opts)) self.assertFalse(self.spotify._parse_opts(opts))
opts = ArgumentsMock("list", False) opts = ArgumentsMock("list", False)
self.assertTrue(self.spotify._parse_opts(opts)) assert self.spotify._parse_opts(opts)
def test_empty_query(self): def test_empty_query(self):
self.assertIsNone(self.spotify._match_library_tracks(self.lib, "1=2")) 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 mock_os.path.exists = exists
plugin = ThumbnailsPlugin() plugin = ThumbnailsPlugin()
mock_os.makedirs.assert_called_once_with(syspath(NORMAL_DIR)) 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 # test metadata writer function
mock_os.path.exists = lambda _: True mock_os.path.exists = lambda _: True
@ -86,7 +86,7 @@ class ThumbnailsTest(BeetsTestCase):
mock_artresizer.shared.local = True mock_artresizer.shared.local = True
mock_artresizer.shared.can_write_metadata = True mock_artresizer.shared.can_write_metadata = True
self.assertTrue(ThumbnailsPlugin()._check_local_ok()) assert ThumbnailsPlugin()._check_local_ok()
# test URI getter function # test URI getter function
giouri_inst = mock_giouri.return_value giouri_inst = mock_giouri.return_value

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -45,7 +45,7 @@ class HiddenFileTest(unittest.TestCase):
else: else:
raise e raise e
self.assertTrue(hidden.is_hidden(f.name)) assert hidden.is_hidden(f.name)
def test_windows_hidden(self): def test_windows_hidden(self):
if not sys.platform == "win32": if not sys.platform == "win32":
@ -64,7 +64,7 @@ class HiddenFileTest(unittest.TestCase):
if not success: if not success:
self.skipTest("unable to set file attributes") 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): def test_other_hidden(self):
if sys.platform == "darwin" or sys.platform == "win32": if sys.platform == "darwin" or sys.platform == "win32":
@ -73,4 +73,4 @@ class HiddenFileTest(unittest.TestCase):
with tempfile.NamedTemporaryFile(prefix=".tmp") as f: with tempfile.NamedTemporaryFile(prefix=".tmp") as f:
fn = util.bytestring_path(f.name) 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"), util.bytestring_path(f"{mediafile.title}.mp3"),
) )
self.assertExists(filename) self.assertExists(filename)
self.assertTrue(os.path.islink(syspath(filename))) assert os.path.islink(syspath(filename))
self.assert_equal_path( self.assert_equal_path(
util.bytestring_path(os.readlink(syspath(filename))), util.bytestring_path(os.readlink(syspath(filename))),
mediafile.path, mediafile.path,
@ -203,9 +203,9 @@ class NonAutotaggedImportTest(AsIsImporterMixin, ImportTestCase):
self.assertExists(filename) self.assertExists(filename)
s1 = os.stat(syspath(mediafile.path)) s1 = os.stat(syspath(mediafile.path))
s2 = os.stat(syspath(filename)) s2 = os.stat(syspath(filename))
self.assertTrue( assert (s1[stat.ST_INO], s1[stat.ST_DEV]) == (
(s1[stat.ST_INO], s1[stat.ST_DEV]) s2[stat.ST_INO],
== (s2[stat.ST_INO], s2[stat.ST_DEV]) s2[stat.ST_DEV],
) )
@unittest.skipUnless(_common.HAVE_REFLINK, "need reflinks") @unittest.skipUnless(_common.HAVE_REFLINK, "need reflinks")
@ -711,7 +711,7 @@ class ImportCompilationTest(ImportTestCase):
self.importer.add_choice(importer.action.ASIS) self.importer.add_choice(importer.action.ASIS)
self.importer.run() self.importer.run()
for item in self.lib.items(): for item in self.lib.items():
self.assertTrue(item.comp) assert item.comp
def test_asis_sets_majority_albumartist(self): def test_asis_sets_majority_albumartist(self):
self.import_media[0].artist = "Other Artist" self.import_media[0].artist = "Other Artist"
@ -786,7 +786,7 @@ class ImportCompilationTest(ImportTestCase):
item.artists, ["Another Artist", "Another Artist 2"] 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): class ImportExistingTest(ImportTestCase):
@ -1037,7 +1037,7 @@ class InferAlbumDataTest(BeetsTestCase):
self.task.align_album_level_fields() 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") self.assertEqual(self.items[0].albumartist, "Various Artists")
def test_asis_comp_applied_to_all_items(self): def test_asis_comp_applied_to_all_items(self):
@ -1048,7 +1048,7 @@ class InferAlbumDataTest(BeetsTestCase):
self.task.align_album_level_fields() self.task.align_album_level_fields()
for item in self.items: for item in self.items:
self.assertTrue(item.comp) assert item.comp
self.assertEqual(item.albumartist, "Various Artists") self.assertEqual(item.albumartist, "Various Artists")
def test_asis_majority_artist_single_artist(self): def test_asis_majority_artist_single_artist(self):

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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