mirror of
https://github.com/beetbox/beets.git
synced 2026-01-28 11:07:01 +01:00
Update code to match pep8 naming standards
This commit is contained in:
parent
144c732ab0
commit
b1c58e99ec
24 changed files with 104 additions and 101 deletions
|
|
@ -297,7 +297,7 @@ class Distance(object):
|
||||||
self._penalties = {}
|
self._penalties = {}
|
||||||
|
|
||||||
@LazyClassProperty
|
@LazyClassProperty
|
||||||
def _weights(cls):
|
def _weights(self):
|
||||||
"""A dictionary from keys to floating-point weights.
|
"""A dictionary from keys to floating-point weights.
|
||||||
"""
|
"""
|
||||||
weights_view = config['match']['distance_weights']
|
weights_view = config['match']['distance_weights']
|
||||||
|
|
|
||||||
|
|
@ -209,13 +209,13 @@ class Model(object):
|
||||||
# Essential field accessors.
|
# Essential field accessors.
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _type(self, key):
|
def _type(cls, key):
|
||||||
"""Get the type of a field, a `Type` instance.
|
"""Get the type of a field, a `Type` instance.
|
||||||
|
|
||||||
If the field has no explicit type, it is given the base `Type`,
|
If the field has no explicit type, it is given the base `Type`,
|
||||||
which does no conversion.
|
which does no conversion.
|
||||||
"""
|
"""
|
||||||
return self._fields.get(key) or self._types.get(key) or types.DEFAULT
|
return cls._fields.get(key) or cls._types.get(key) or types.DEFAULT
|
||||||
|
|
||||||
def __getitem__(self, key):
|
def __getitem__(self, key):
|
||||||
"""Get the value for a field. Raise a KeyError if the field is
|
"""Get the value for a field. Raise a KeyError if the field is
|
||||||
|
|
@ -274,11 +274,11 @@ class Model(object):
|
||||||
return base_keys
|
return base_keys
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def all_keys(self):
|
def all_keys(cls):
|
||||||
"""Get a list of available keys for objects of this type.
|
"""Get a list of available keys for objects of this type.
|
||||||
Includes fixed and computed fields.
|
Includes fixed and computed fields.
|
||||||
"""
|
"""
|
||||||
return list(self._fields) + self._getters().keys()
|
return list(cls._fields) + cls._getters().keys()
|
||||||
|
|
||||||
# Act like a dictionary.
|
# Act like a dictionary.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -146,9 +146,9 @@ class NoneQuery(FieldQuery):
|
||||||
return self.field + " IS NULL", ()
|
return self.field + " IS NULL", ()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def match(self, item):
|
def match(cls, item):
|
||||||
try:
|
try:
|
||||||
return item[self.field] is None
|
return item[cls.field] is None
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
@ -841,8 +841,8 @@ class SlowFieldSort(FieldSort):
|
||||||
|
|
||||||
class NullSort(Sort):
|
class NullSort(Sort):
|
||||||
"""No sorting. Leave results unsorted."""
|
"""No sorting. Leave results unsorted."""
|
||||||
def sort(items):
|
def sort(self):
|
||||||
return items
|
return self
|
||||||
|
|
||||||
def __nonzero__(self):
|
def __nonzero__(self):
|
||||||
return self.__bool__()
|
return self.__bool__()
|
||||||
|
|
|
||||||
|
|
@ -126,7 +126,7 @@ my_manager = copy(Logger.manager)
|
||||||
my_manager.loggerClass = BeetsLogger
|
my_manager.loggerClass = BeetsLogger
|
||||||
|
|
||||||
|
|
||||||
def getLogger(name=None):
|
def getLogger(name=None): # noqa
|
||||||
if name:
|
if name:
|
||||||
return my_manager.getLogger(name)
|
return my_manager.getLogger(name)
|
||||||
else:
|
else:
|
||||||
|
|
|
||||||
|
|
@ -149,15 +149,15 @@ class Shareable(type):
|
||||||
lazily-created shared instance of ``MyClass`` while calling
|
lazily-created shared instance of ``MyClass`` while calling
|
||||||
``MyClass()`` to construct a new object works as usual.
|
``MyClass()`` to construct a new object works as usual.
|
||||||
"""
|
"""
|
||||||
def __init__(cls, name, bases, dict):
|
def __init__(self, name, bases, dict):
|
||||||
super(Shareable, cls).__init__(name, bases, dict)
|
super(Shareable, self).__init__(name, bases, dict)
|
||||||
cls._instance = None
|
self._instance = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def shared(cls):
|
def shared(self):
|
||||||
if cls._instance is None:
|
if self._instance is None:
|
||||||
cls._instance = cls()
|
self._instance = self()
|
||||||
return cls._instance
|
return self._instance
|
||||||
|
|
||||||
|
|
||||||
class ArtResizer(object):
|
class ArtResizer(object):
|
||||||
|
|
@ -218,18 +218,18 @@ class ArtResizer(object):
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _check_method():
|
def _check_method():
|
||||||
"""Return a tuple indicating an available method and its version."""
|
"""Return a tuple indicating an available method and its version."""
|
||||||
version = has_IM()
|
version = get_image_magick_version()
|
||||||
if version:
|
if version:
|
||||||
return IMAGEMAGICK, version
|
return IMAGEMAGICK, version
|
||||||
|
|
||||||
version = has_PIL()
|
version = get_pil_version()
|
||||||
if version:
|
if version:
|
||||||
return PIL, version
|
return PIL, version
|
||||||
|
|
||||||
return WEBPROXY, (0)
|
return WEBPROXY, (0)
|
||||||
|
|
||||||
|
|
||||||
def has_IM():
|
def get_image_magick_version():
|
||||||
"""Return Image Magick version or None if it is unavailable
|
"""Return Image Magick version or None if it is unavailable
|
||||||
Try invoking ImageMagick's "convert"."""
|
Try invoking ImageMagick's "convert"."""
|
||||||
try:
|
try:
|
||||||
|
|
@ -248,7 +248,7 @@ def has_IM():
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def has_PIL():
|
def get_pil_version():
|
||||||
"""Return Image Magick version or None if it is unavailable
|
"""Return Image Magick version or None if it is unavailable
|
||||||
Try importing PIL."""
|
Try importing PIL."""
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,9 @@ from itertools import tee, izip
|
||||||
from beets import plugins, ui
|
from beets import plugins, ui
|
||||||
|
|
||||||
|
|
||||||
|
ASCII_DIGITS = string.digits + string.ascii_lowercase
|
||||||
|
|
||||||
|
|
||||||
class BucketError(Exception):
|
class BucketError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
@ -155,23 +158,23 @@ def build_alpha_spans(alpha_spans_str, alpha_regexs):
|
||||||
[from...to]
|
[from...to]
|
||||||
"""
|
"""
|
||||||
spans = []
|
spans = []
|
||||||
ASCII_DIGITS = string.digits + string.ascii_lowercase
|
|
||||||
for elem in alpha_spans_str:
|
for elem in alpha_spans_str:
|
||||||
if elem in alpha_regexs:
|
if elem in alpha_regexs:
|
||||||
spans.append(re.compile(alpha_regexs[elem]))
|
spans.append(re.compile(alpha_regexs[elem]))
|
||||||
else:
|
else:
|
||||||
bucket = sorted([x for x in elem.lower() if x.isalnum()])
|
bucket = sorted([x for x in elem.lower() if x.isalnum()])
|
||||||
if bucket:
|
if bucket:
|
||||||
beginIdx = ASCII_DIGITS.index(bucket[0])
|
begin_index = ASCII_DIGITS.index(bucket[0])
|
||||||
endIdx = ASCII_DIGITS.index(bucket[-1])
|
end_index = ASCII_DIGITS.index(bucket[-1])
|
||||||
else:
|
else:
|
||||||
raise ui.UserError(u"invalid range defined for alpha bucket "
|
raise ui.UserError(u"invalid range defined for alpha bucket "
|
||||||
u"'%s': no alphanumeric character found" %
|
u"'%s': no alphanumeric character found" %
|
||||||
elem)
|
elem)
|
||||||
spans.append(
|
spans.append(
|
||||||
re.compile(
|
re.compile(
|
||||||
"^[" + ASCII_DIGITS[beginIdx:endIdx + 1] +
|
"^[" + ASCII_DIGITS[begin_index:end_index + 1] +
|
||||||
ASCII_DIGITS[beginIdx:endIdx + 1].upper() + "]"
|
ASCII_DIGITS[begin_index:end_index + 1].upper() + "]"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return spans
|
return spans
|
||||||
|
|
|
||||||
|
|
@ -119,7 +119,7 @@ class ExportFormat(object):
|
||||||
"""The output format type"""
|
"""The output format type"""
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def factory(self, type, **kwargs):
|
def factory(cls, type, **kwargs):
|
||||||
if type == "json":
|
if type == "json":
|
||||||
if kwargs['file_path']:
|
if kwargs['file_path']:
|
||||||
return JsonFileFormat(**kwargs)
|
return JsonFileFormat(**kwargs)
|
||||||
|
|
|
||||||
|
|
@ -26,13 +26,13 @@ import difflib
|
||||||
|
|
||||||
class FuzzyQuery(StringFieldQuery):
|
class FuzzyQuery(StringFieldQuery):
|
||||||
@classmethod
|
@classmethod
|
||||||
def string_match(self, pattern, val):
|
def string_match(cls, pattern, val):
|
||||||
# smartcase
|
# smartcase
|
||||||
if pattern.islower():
|
if pattern.islower():
|
||||||
val = val.lower()
|
val = val.lower()
|
||||||
queryMatcher = difflib.SequenceMatcher(None, pattern, val)
|
query_matcher = difflib.SequenceMatcher(None, pattern, val)
|
||||||
threshold = config['fuzzy']['threshold'].as_number()
|
threshold = config['fuzzy']['threshold'].as_number()
|
||||||
return queryMatcher.quick_ratio() >= threshold
|
return query_matcher.quick_ratio() >= threshold
|
||||||
|
|
||||||
|
|
||||||
class FuzzyPlugin(BeetsPlugin):
|
class FuzzyPlugin(BeetsPlugin):
|
||||||
|
|
|
||||||
|
|
@ -167,11 +167,11 @@ class TestCase(unittest.TestCase):
|
||||||
beets.config.clear()
|
beets.config.clear()
|
||||||
beets.config._materialized = False
|
beets.config._materialized = False
|
||||||
|
|
||||||
def assertExists(self, path):
|
def assertExists(self, path): # noqa
|
||||||
self.assertTrue(os.path.exists(path),
|
self.assertTrue(os.path.exists(path),
|
||||||
u'file does not exist: {!r}'.format(path))
|
u'file does not exist: {!r}'.format(path))
|
||||||
|
|
||||||
def assertNotExists(self, path):
|
def assertNotExists(self, path): # noqa
|
||||||
self.assertFalse(os.path.exists(path),
|
self.assertFalse(os.path.exists(path),
|
||||||
u'file exists: {!r}'.format((path)))
|
u'file exists: {!r}'.format((path)))
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -518,7 +518,7 @@ class ArtForAlbumTest(UseThePlugin):
|
||||||
fetchart.FileSystem.get = self.old_fs_source_get
|
fetchart.FileSystem.get = self.old_fs_source_get
|
||||||
super(ArtForAlbumTest, self).tearDown()
|
super(ArtForAlbumTest, self).tearDown()
|
||||||
|
|
||||||
def _assertImageIsValidArt(self, image_file, should_exist):
|
def _assertImageIsValidArt(self, image_file, should_exist): # noqa
|
||||||
self.assertExists(image_file)
|
self.assertExists(image_file)
|
||||||
self.image_file = image_file
|
self.image_file = image_file
|
||||||
|
|
||||||
|
|
@ -531,7 +531,7 @@ class ArtForAlbumTest(UseThePlugin):
|
||||||
else:
|
else:
|
||||||
self.assertIsNone(candidate)
|
self.assertIsNone(candidate)
|
||||||
|
|
||||||
def _assertImageResized(self, image_file, should_resize):
|
def _assertImageResized(self, image_file, should_resize): # noqa
|
||||||
self.image_file = image_file
|
self.image_file = image_file
|
||||||
with patch.object(ArtResizer.shared, 'resize') as mock_resize:
|
with patch.object(ArtResizer.shared, 'resize') as mock_resize:
|
||||||
self.plugin.art_for_album(self.album, [''], True)
|
self.plugin.art_for_album(self.album, [''], True)
|
||||||
|
|
|
||||||
|
|
@ -940,13 +940,13 @@ class EnumTest(_common.TestCase):
|
||||||
Test Enum Subclasses defined in beets.util.enumeration
|
Test Enum Subclasses defined in beets.util.enumeration
|
||||||
"""
|
"""
|
||||||
def test_ordered_enum(self):
|
def test_ordered_enum(self):
|
||||||
OrderedEnumTest = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c'])
|
ordered_enum = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c'])
|
||||||
self.assertLess(OrderedEnumTest.a, OrderedEnumTest.b)
|
self.assertLess(ordered_enum.a, ordered_enum.b)
|
||||||
self.assertLess(OrderedEnumTest.a, OrderedEnumTest.c)
|
self.assertLess(ordered_enum.a, ordered_enum.c)
|
||||||
self.assertLess(OrderedEnumTest.b, OrderedEnumTest.c)
|
self.assertLess(ordered_enum.b, ordered_enum.c)
|
||||||
self.assertGreater(OrderedEnumTest.b, OrderedEnumTest.a)
|
self.assertGreater(ordered_enum.b, ordered_enum.a)
|
||||||
self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.a)
|
self.assertGreater(ordered_enum.c, ordered_enum.a)
|
||||||
self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.b)
|
self.assertGreater(ordered_enum.c, ordered_enum.b)
|
||||||
|
|
||||||
|
|
||||||
def suite():
|
def suite():
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ class TestHelper(helper.TestHelper):
|
||||||
return u'sh -c "cp \'$source\' \'$dest\'; ' \
|
return u'sh -c "cp \'$source\' \'$dest\'; ' \
|
||||||
u'printf {0} >> \'$dest\'"'.format(tag)
|
u'printf {0} >> \'$dest\'"'.format(tag)
|
||||||
|
|
||||||
def assertFileTag(self, path, tag):
|
def assertFileTag(self, path, tag): # noqa
|
||||||
"""Assert that the path is a file and the files content ends with `tag`.
|
"""Assert that the path is a file and the files content ends with `tag`.
|
||||||
"""
|
"""
|
||||||
self.assertTrue(os.path.isfile(path),
|
self.assertTrue(os.path.isfile(path),
|
||||||
|
|
@ -50,7 +50,7 @@ class TestHelper(helper.TestHelper):
|
||||||
self.assertEqual(f.read(), tag,
|
self.assertEqual(f.read(), tag,
|
||||||
u'{0} is not tagged with {1}'.format(path, tag))
|
u'{0} is not tagged with {1}'.format(path, tag))
|
||||||
|
|
||||||
def assertNoFileTag(self, path, tag):
|
def assertNoFileTag(self, path, tag): # noqa
|
||||||
"""Assert that the path is a file and the files content does not
|
"""Assert that the path is a file and the files content does not
|
||||||
end with `tag`.
|
end with `tag`.
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
|
|
@ -62,14 +62,14 @@ class DateIntervalTest(unittest.TestCase):
|
||||||
self.assertContains('..', date=datetime.min)
|
self.assertContains('..', date=datetime.min)
|
||||||
self.assertContains('..', '1000-01-01T00:00:00')
|
self.assertContains('..', '1000-01-01T00:00:00')
|
||||||
|
|
||||||
def assertContains(self, interval_pattern, date_pattern=None, date=None):
|
def assertContains(self, interval_pattern, date_pattern=None, date=None): # noqa
|
||||||
if date is None:
|
if date is None:
|
||||||
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))
|
self.assertTrue(interval.contains(date))
|
||||||
|
|
||||||
def assertExcludes(self, interval_pattern, date_pattern):
|
def assertExcludes(self, interval_pattern, date_pattern): # noqa
|
||||||
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)
|
||||||
|
|
|
||||||
|
|
@ -71,7 +71,7 @@ class ModifyFileMocker(object):
|
||||||
|
|
||||||
class EditMixin(object):
|
class EditMixin(object):
|
||||||
"""Helper containing some common functionality used for the Edit tests."""
|
"""Helper containing some common functionality used for the Edit tests."""
|
||||||
def assertItemFieldsModified(self, library_items, items, fields=[],
|
def assertItemFieldsModified(self, library_items, items, fields=[], # noqa
|
||||||
allowed=['path']):
|
allowed=['path']):
|
||||||
"""Assert that items in the library (`lib_items`) have different values
|
"""Assert that items in the library (`lib_items`) have different values
|
||||||
on the specified `fields` (and *only* on those fields), compared to
|
on the specified `fields` (and *only* on those fields), compared to
|
||||||
|
|
@ -133,7 +133,7 @@ class EditCommandTest(unittest.TestCase, TestHelper, EditMixin):
|
||||||
self.teardown_beets()
|
self.teardown_beets()
|
||||||
self.unload_plugins()
|
self.unload_plugins()
|
||||||
|
|
||||||
def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT,
|
def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, # noqa
|
||||||
write_call_count=TRACK_COUNT, title_starts_with=''):
|
write_call_count=TRACK_COUNT, title_starts_with=''):
|
||||||
"""Several common assertions on Album, Track and call counts."""
|
"""Several common assertions on Album, Track and call counts."""
|
||||||
self.assertEqual(len(self.lib.albums()), album_count)
|
self.assertEqual(len(self.lib.albums()), album_count)
|
||||||
|
|
|
||||||
|
|
@ -67,7 +67,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
|
||||||
self.teardown_beets()
|
self.teardown_beets()
|
||||||
self.matcher.restore()
|
self.matcher.restore()
|
||||||
|
|
||||||
def findMediaFile(self, item):
|
def find_media_file(self, item):
|
||||||
"""Find the pre-import MediaFile for an Item"""
|
"""Find the pre-import MediaFile for an Item"""
|
||||||
for m in self.media_files:
|
for m in self.media_files:
|
||||||
if m.title.replace('Tag', 'Applied') == item.title:
|
if m.title.replace('Tag', 'Applied') == item.title:
|
||||||
|
|
@ -75,11 +75,11 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
|
||||||
raise AssertionError(u"No MediaFile found for Item " +
|
raise AssertionError(u"No MediaFile found for Item " +
|
||||||
util.displayable_path(item.path))
|
util.displayable_path(item.path))
|
||||||
|
|
||||||
def assertEqualTimes(self, first, second, msg=None):
|
def assertEqualTimes(self, first, second, msg=None): # noqa
|
||||||
"""For comparing file modification times at a sufficient precision"""
|
"""For comparing file modification times at a sufficient precision"""
|
||||||
self.assertAlmostEqual(first, second, places=4, msg=msg)
|
self.assertAlmostEqual(first, second, places=4, msg=msg)
|
||||||
|
|
||||||
def assertAlbumImport(self):
|
def assertAlbumImport(self): # noqa
|
||||||
self.importer.run()
|
self.importer.run()
|
||||||
album = self.lib.albums().get()
|
album = self.lib.albums().get()
|
||||||
self.assertEqual(album.added, self.min_mtime)
|
self.assertEqual(album.added, self.min_mtime)
|
||||||
|
|
@ -102,7 +102,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
|
||||||
self.assertEqual(album.added, self.min_mtime)
|
self.assertEqual(album.added, self.min_mtime)
|
||||||
for item in album.items():
|
for item in album.items():
|
||||||
self.assertEqualTimes(item.added, self.min_mtime)
|
self.assertEqualTimes(item.added, self.min_mtime)
|
||||||
mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path)
|
mediafile_mtime = os.path.getmtime(self.find_media_file(item).path)
|
||||||
self.assertEqualTimes(item.mtime, mediafile_mtime)
|
self.assertEqualTimes(item.mtime, mediafile_mtime)
|
||||||
self.assertEqualTimes(os.path.getmtime(item.path),
|
self.assertEqualTimes(os.path.getmtime(item.path),
|
||||||
mediafile_mtime)
|
mediafile_mtime)
|
||||||
|
|
@ -133,7 +133,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
|
||||||
self.config['import']['singletons'] = True
|
self.config['import']['singletons'] = True
|
||||||
self.importer.run()
|
self.importer.run()
|
||||||
for item in self.lib.items():
|
for item in self.lib.items():
|
||||||
mfile = self.findMediaFile(item)
|
mfile = self.find_media_file(item)
|
||||||
self.assertEqualTimes(item.added, os.path.getmtime(mfile.path))
|
self.assertEqualTimes(item.added, os.path.getmtime(mfile.path))
|
||||||
|
|
||||||
def test_import_singletons_with_preserved_mtimes(self):
|
def test_import_singletons_with_preserved_mtimes(self):
|
||||||
|
|
@ -141,7 +141,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
|
||||||
self.config['importadded']['preserve_mtimes'] = True
|
self.config['importadded']['preserve_mtimes'] = True
|
||||||
self.importer.run()
|
self.importer.run()
|
||||||
for item in self.lib.items():
|
for item in self.lib.items():
|
||||||
mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path)
|
mediafile_mtime = os.path.getmtime(self.find_media_file(item).path)
|
||||||
self.assertEqualTimes(item.added, mediafile_mtime)
|
self.assertEqualTimes(item.added, mediafile_mtime)
|
||||||
self.assertEqualTimes(item.mtime, mediafile_mtime)
|
self.assertEqualTimes(item.mtime, mediafile_mtime)
|
||||||
self.assertEqualTimes(os.path.getmtime(item.path),
|
self.assertEqualTimes(os.path.getmtime(item.path),
|
||||||
|
|
|
||||||
|
|
@ -125,14 +125,14 @@ class AutotagStub(object):
|
||||||
artist = artist.replace('Tag', 'Applied') + id
|
artist = artist.replace('Tag', 'Applied') + id
|
||||||
album = album.replace('Tag', 'Applied') + id
|
album = album.replace('Tag', 'Applied') + id
|
||||||
|
|
||||||
trackInfos = []
|
track_infos = []
|
||||||
for i in range(tracks - missing):
|
for i in range(tracks - missing):
|
||||||
trackInfos.append(self._make_track_match(artist, album, i + 1))
|
track_infos.append(self._make_track_match(artist, album, i + 1))
|
||||||
|
|
||||||
return AlbumInfo(
|
return AlbumInfo(
|
||||||
artist=artist,
|
artist=artist,
|
||||||
album=album,
|
album=album,
|
||||||
tracks=trackInfos,
|
tracks=track_infos,
|
||||||
va=False,
|
va=False,
|
||||||
album_id=u'albumid' + id,
|
album_id=u'albumid' + id,
|
||||||
artist_id=u'artistid' + id,
|
artist_id=u'artistid' + id,
|
||||||
|
|
|
||||||
|
|
@ -167,16 +167,16 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper):
|
||||||
self.assertEqual(res, [u'pop'])
|
self.assertEqual(res, [u'pop'])
|
||||||
|
|
||||||
def test_get_genre(self):
|
def test_get_genre(self):
|
||||||
MOCK_GENRES = {'track': u'1', 'album': u'2', 'artist': u'3'}
|
mock_genres = {'track': u'1', 'album': u'2', 'artist': u'3'}
|
||||||
|
|
||||||
def mock_fetch_track_genre(self, obj=None):
|
def mock_fetch_track_genre(self, obj=None):
|
||||||
return MOCK_GENRES['track']
|
return mock_genres['track']
|
||||||
|
|
||||||
def mock_fetch_album_genre(self, obj):
|
def mock_fetch_album_genre(self, obj):
|
||||||
return MOCK_GENRES['album']
|
return mock_genres['album']
|
||||||
|
|
||||||
def mock_fetch_artist_genre(self, obj):
|
def mock_fetch_artist_genre(self, obj):
|
||||||
return MOCK_GENRES['artist']
|
return mock_genres['artist']
|
||||||
|
|
||||||
lastgenre.LastGenrePlugin.fetch_track_genre = mock_fetch_track_genre
|
lastgenre.LastGenrePlugin.fetch_track_genre = mock_fetch_track_genre
|
||||||
lastgenre.LastGenrePlugin.fetch_album_genre = mock_fetch_album_genre
|
lastgenre.LastGenrePlugin.fetch_album_genre = mock_fetch_album_genre
|
||||||
|
|
@ -184,7 +184,7 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper):
|
||||||
|
|
||||||
self._setup_config(whitelist=False)
|
self._setup_config(whitelist=False)
|
||||||
item = _common.item()
|
item = _common.item()
|
||||||
item.genre = MOCK_GENRES['track']
|
item.genre = mock_genres['track']
|
||||||
|
|
||||||
config['lastgenre'] = {'force': False}
|
config['lastgenre'] = {'force': False}
|
||||||
res = self.plugin._get_genre(item)
|
res = self.plugin._get_genre(item)
|
||||||
|
|
@ -192,17 +192,17 @@ class LastGenrePluginTest(unittest.TestCase, TestHelper):
|
||||||
|
|
||||||
config['lastgenre'] = {'force': True, 'source': u'track'}
|
config['lastgenre'] = {'force': True, 'source': u'track'}
|
||||||
res = self.plugin._get_genre(item)
|
res = self.plugin._get_genre(item)
|
||||||
self.assertEqual(res, (MOCK_GENRES['track'], u'track'))
|
self.assertEqual(res, (mock_genres['track'], u'track'))
|
||||||
|
|
||||||
config['lastgenre'] = {'source': u'album'}
|
config['lastgenre'] = {'source': u'album'}
|
||||||
res = self.plugin._get_genre(item)
|
res = self.plugin._get_genre(item)
|
||||||
self.assertEqual(res, (MOCK_GENRES['album'], u'album'))
|
self.assertEqual(res, (mock_genres['album'], u'album'))
|
||||||
|
|
||||||
config['lastgenre'] = {'source': u'artist'}
|
config['lastgenre'] = {'source': u'artist'}
|
||||||
res = self.plugin._get_genre(item)
|
res = self.plugin._get_genre(item)
|
||||||
self.assertEqual(res, (MOCK_GENRES['artist'], u'artist'))
|
self.assertEqual(res, (mock_genres['artist'], u'artist'))
|
||||||
|
|
||||||
MOCK_GENRES['artist'] = None
|
mock_genres['artist'] = None
|
||||||
res = self.plugin._get_genre(item)
|
res = self.plugin._get_genre(item)
|
||||||
self.assertEqual(res, (item.genre, u'original'))
|
self.assertEqual(res, (item.genre, u'original'))
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -365,14 +365,14 @@ class LyricsGooglePluginTest(unittest.TestCase):
|
||||||
not present in the title."""
|
not present in the title."""
|
||||||
s = self.source
|
s = self.source
|
||||||
url = s['url'] + s['path']
|
url = s['url'] + s['path']
|
||||||
urlTitle = u'example.com | Beats song by John doe'
|
url_title = u'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.assertEqual(google.is_page_candidate(url, urlTitle, s['title'],
|
self.assertEqual(google.is_page_candidate(url, url_title, s['title'],
|
||||||
s['artist']), True, url)
|
s['artist']), True, url)
|
||||||
# reject different title
|
# reject different title
|
||||||
urlTitle = u'example.com | seets bong lyrics by John doe'
|
url_title = u'example.com | seets bong lyrics by John doe'
|
||||||
self.assertEqual(google.is_page_candidate(url, urlTitle, s['title'],
|
self.assertEqual(google.is_page_candidate(url, url_title, s['title'],
|
||||||
s['artist']), False, url)
|
s['artist']), False, url)
|
||||||
|
|
||||||
def test_is_page_candidate_special_chars(self):
|
def test_is_page_candidate_special_chars(self):
|
||||||
|
|
|
||||||
|
|
@ -168,7 +168,7 @@ class ImageStructureTestMixin(ArtTestMixin):
|
||||||
self.assertEqual(cover.desc, u'album cover')
|
self.assertEqual(cover.desc, u'album cover')
|
||||||
self.assertEqual(mediafile.art, cover.data)
|
self.assertEqual(mediafile.art, cover.data)
|
||||||
|
|
||||||
def assertExtendedImageAttributes(self, image, **kwargs):
|
def assertExtendedImageAttributes(self, image, **kwargs): # noqa
|
||||||
"""Ignore extended image attributes in the base tests.
|
"""Ignore extended image attributes in the base tests.
|
||||||
"""
|
"""
|
||||||
pass
|
pass
|
||||||
|
|
@ -177,7 +177,7 @@ class ImageStructureTestMixin(ArtTestMixin):
|
||||||
class ExtendedImageStructureTestMixin(ImageStructureTestMixin):
|
class ExtendedImageStructureTestMixin(ImageStructureTestMixin):
|
||||||
"""Checks for additional attributes in the image structure."""
|
"""Checks for additional attributes in the image structure."""
|
||||||
|
|
||||||
def assertExtendedImageAttributes(self, image, desc=None, type=None):
|
def assertExtendedImageAttributes(self, image, desc=None, type=None): # noqa
|
||||||
self.assertEqual(image.desc, desc)
|
self.assertEqual(image.desc, desc)
|
||||||
self.assertEqual(image.type, type)
|
self.assertEqual(image.type, type)
|
||||||
|
|
||||||
|
|
@ -660,7 +660,7 @@ class ReadWriteTestBase(ArtTestMixin, GenreListTestMixin,
|
||||||
self.assertIsNone(mediafile.date)
|
self.assertIsNone(mediafile.date)
|
||||||
self.assertIsNone(mediafile.year)
|
self.assertIsNone(mediafile.year)
|
||||||
|
|
||||||
def assertTags(self, mediafile, tags):
|
def assertTags(self, mediafile, tags): # noqa
|
||||||
errors = []
|
errors = []
|
||||||
for key, value in tags.items():
|
for key, value in tags.items():
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -43,14 +43,14 @@ class MPDStatsTest(unittest.TestCase, TestHelper):
|
||||||
self.assertFalse(mpdstats.update_rating(None, True))
|
self.assertFalse(mpdstats.update_rating(None, True))
|
||||||
|
|
||||||
def test_get_item(self):
|
def test_get_item(self):
|
||||||
ITEM_PATH = '/foo/bar.flac'
|
item_path = '/foo/bar.flac'
|
||||||
item = Item(title=u'title', path=ITEM_PATH, id=1)
|
item = Item(title=u'title', path=item_path, id=1)
|
||||||
item.add(self.lib)
|
item.add(self.lib)
|
||||||
|
|
||||||
log = Mock()
|
log = Mock()
|
||||||
mpdstats = MPDStats(self.lib, log)
|
mpdstats = MPDStats(self.lib, log)
|
||||||
|
|
||||||
self.assertEqual(str(mpdstats.get_item(ITEM_PATH)), str(item))
|
self.assertEqual(str(mpdstats.get_item(item_path)), str(item))
|
||||||
self.assertIsNone(mpdstats.get_item('/some/non-existing/path'))
|
self.assertIsNone(mpdstats.get_item('/some/non-existing/path'))
|
||||||
self.assertIn(u'item not found:', log.info.call_args[0][0])
|
self.assertIn(u'item not found:', log.info.call_args[0][0])
|
||||||
|
|
||||||
|
|
@ -60,13 +60,13 @@ class MPDStatsTest(unittest.TestCase, TestHelper):
|
||||||
{'state': u'play', 'songid': 1, 'time': u'0:1'},
|
{'state': u'play', 'songid': 1, 'time': u'0:1'},
|
||||||
{'state': u'stop'}]
|
{'state': u'stop'}]
|
||||||
EVENTS = [["player"]] * (len(STATUSES) - 1) + [KeyboardInterrupt]
|
EVENTS = [["player"]] * (len(STATUSES) - 1) + [KeyboardInterrupt]
|
||||||
ITEM_PATH = '/foo/bar.flac'
|
item_path = '/foo/bar.flac'
|
||||||
|
|
||||||
@patch("beetsplug.mpdstats.MPDClientWrapper", return_value=Mock(**{
|
@patch("beetsplug.mpdstats.MPDClientWrapper", return_value=Mock(**{
|
||||||
"events.side_effect": EVENTS, "status.side_effect": STATUSES,
|
"events.side_effect": EVENTS, "status.side_effect": STATUSES,
|
||||||
"playlist.return_value": {1: ITEM_PATH}}))
|
"playlist.return_value": {1: item_path}}))
|
||||||
def test_run_MPDStats(self, mpd_mock):
|
def test_run_mpdstats(self, mpd_mock):
|
||||||
item = Item(title=u'title', path=self.ITEM_PATH, id=1)
|
item = Item(title=u'title', path=self.item_path, id=1)
|
||||||
item.add(self.lib)
|
item.add(self.lib)
|
||||||
|
|
||||||
log = Mock()
|
log = Mock()
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,7 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper):
|
||||||
def test_failing_to_set_permissions(self):
|
def test_failing_to_set_permissions(self):
|
||||||
self.do_thing(False)
|
self.do_thing(False)
|
||||||
|
|
||||||
def do_thing(self, expectSuccess):
|
def do_thing(self, expect_success):
|
||||||
def get_stat(v):
|
def get_stat(v):
|
||||||
return os.stat(
|
return os.stat(
|
||||||
os.path.join(self.temp_dir, 'import', *v)).st_mode & 0o777
|
os.path.join(self.temp_dir, 'import', *v)).st_mode & 0o777
|
||||||
|
|
@ -53,14 +53,14 @@ class PermissionsPluginTest(unittest.TestCase, TestHelper):
|
||||||
self.importer.run()
|
self.importer.run()
|
||||||
item = self.lib.items().get()
|
item = self.lib.items().get()
|
||||||
|
|
||||||
self.assertPerms(item.path, 'file', expectSuccess)
|
self.assertPerms(item.path, 'file', expect_success)
|
||||||
|
|
||||||
for path in dirs_in_library(self.lib.directory, item.path):
|
for path in dirs_in_library(self.lib.directory, item.path):
|
||||||
self.assertPerms(path, 'dir', expectSuccess)
|
self.assertPerms(path, 'dir', expect_success)
|
||||||
|
|
||||||
def assertPerms(self, path, typ, expectSuccess):
|
def assertPerms(self, path, typ, expect_success): # noqa
|
||||||
for x in [(True, self.exp_perms[expectSuccess][typ], '!='),
|
for x in [(True, self.exp_perms[expect_success][typ], '!='),
|
||||||
(False, self.exp_perms[not expectSuccess][typ], '==')]:
|
(False, self.exp_perms[not expect_success][typ], '==')]:
|
||||||
self.assertEqual(x[0], check_permissions(path, x[1]),
|
self.assertEqual(x[0], check_permissions(path, x[1]),
|
||||||
msg=u'{} : {} {} {}'.format(
|
msg=u'{} : {} {} {}'.format(
|
||||||
path, oct(os.stat(path).st_mode), x[2], oct(x[1])))
|
path, oct(os.stat(path).st_mode), x[2], oct(x[1])))
|
||||||
|
|
|
||||||
|
|
@ -35,11 +35,11 @@ from beets.library import Library, Item
|
||||||
|
|
||||||
class TestHelper(helper.TestHelper):
|
class TestHelper(helper.TestHelper):
|
||||||
|
|
||||||
def assertInResult(self, item, results):
|
def assertInResult(self, item, results): # noqa
|
||||||
result_ids = map(lambda i: i.id, results)
|
result_ids = map(lambda i: i.id, results)
|
||||||
self.assertIn(item.id, result_ids)
|
self.assertIn(item.id, result_ids)
|
||||||
|
|
||||||
def assertNotInResult(self, item, results):
|
def assertNotInResult(self, item, results): # noqa
|
||||||
result_ids = map(lambda i: i.id, results)
|
result_ids = map(lambda i: i.id, results)
|
||||||
self.assertNotIn(item.id, result_ids)
|
self.assertNotIn(item.id, result_ids)
|
||||||
|
|
||||||
|
|
@ -805,7 +805,7 @@ class NotQueryTest(DummyDataTestCase):
|
||||||
- `test_type_xxx`: tests for the negation of a particular XxxQuery class.
|
- `test_type_xxx`: tests for the negation of a particular XxxQuery class.
|
||||||
- `test_get_yyy`: tests on query strings (similar to `GetTest`)
|
- `test_get_yyy`: tests on query strings (similar to `GetTest`)
|
||||||
"""
|
"""
|
||||||
def assertNegationProperties(self, q):
|
def assertNegationProperties(self, q): # noqa
|
||||||
"""Given a Query `q`, assert that:
|
"""Given a Query `q`, assert that:
|
||||||
- q OR not(q) == all items
|
- q OR not(q) == all items
|
||||||
- q AND not(q) == 0
|
- q AND not(q) == 0
|
||||||
|
|
|
||||||
|
|
@ -88,15 +88,15 @@ class SmartPlaylistTest(unittest.TestCase):
|
||||||
for name, (_, sort), _ in spl._unmatched_playlists)
|
for name, (_, sort), _ in spl._unmatched_playlists)
|
||||||
|
|
||||||
asseq = self.assertEqual # less cluttered code
|
asseq = self.assertEqual # less cluttered code
|
||||||
S = FixedFieldSort # short cut since we're only dealing with this
|
sort = FixedFieldSort # short cut since we're only dealing with this
|
||||||
asseq(sorts["no_sort"], NullSort())
|
asseq(sorts["no_sort"], NullSort())
|
||||||
asseq(sorts["one_sort"], S(u'year'))
|
asseq(sorts["one_sort"], sort(u'year'))
|
||||||
asseq(sorts["only_empty_sorts"], None)
|
asseq(sorts["only_empty_sorts"], None)
|
||||||
asseq(sorts["one_non_empty_sort"], S(u'year'))
|
asseq(sorts["one_non_empty_sort"], sort(u'year'))
|
||||||
asseq(sorts["multiple_sorts"],
|
asseq(sorts["multiple_sorts"],
|
||||||
MultipleSort([S('year'), S(u'genre', False)]))
|
MultipleSort([sort('year'), sort(u'genre', False)]))
|
||||||
asseq(sorts["mixed"],
|
asseq(sorts["mixed"],
|
||||||
MultipleSort([S('year'), S(u'genre'), S(u'id', False)]))
|
MultipleSort([sort('year'), sort(u'genre'), sort(u'id', False)]))
|
||||||
|
|
||||||
def test_matches(self):
|
def test_matches(self):
|
||||||
spl = SmartPlaylistPlugin()
|
spl = SmartPlaylistPlugin()
|
||||||
|
|
|
||||||
|
|
@ -233,18 +233,18 @@ class ModifyTest(unittest.TestCase, TestHelper):
|
||||||
def test_selective_modify(self):
|
def test_selective_modify(self):
|
||||||
title = u"Tracktitle"
|
title = u"Tracktitle"
|
||||||
album = u"album"
|
album = u"album"
|
||||||
origArtist = u"composer"
|
original_artist = u"composer"
|
||||||
newArtist = u"coverArtist"
|
new_artist = u"coverArtist"
|
||||||
for i in range(0, 10):
|
for i in range(0, 10):
|
||||||
self.add_item_fixture(title=u"{0}{1}".format(title, i),
|
self.add_item_fixture(title=u"{0}{1}".format(title, i),
|
||||||
artist=origArtist,
|
artist=original_artist,
|
||||||
album=album)
|
album=album)
|
||||||
self.modify_inp('s\ny\ny\ny\nn\nn\ny\ny\ny\ny\nn',
|
self.modify_inp('s\ny\ny\ny\nn\nn\ny\ny\ny\ny\nn',
|
||||||
title, u"artist={0}".format(newArtist))
|
title, u"artist={0}".format(new_artist))
|
||||||
origItems = self.lib.items(u"artist:{0}".format(origArtist))
|
original_items = self.lib.items(u"artist:{0}".format(original_artist))
|
||||||
newItems = self.lib.items(u"artist:{0}".format(newArtist))
|
new_items = self.lib.items(u"artist:{0}".format(new_artist))
|
||||||
self.assertEqual(len(list(origItems)), 3)
|
self.assertEqual(len(list(original_items)), 3)
|
||||||
self.assertEqual(len(list(newItems)), 7)
|
self.assertEqual(len(list(new_items)), 7)
|
||||||
|
|
||||||
# Album Tests
|
# Album Tests
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue