desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Keep only genres that are in the whitelist.'
| def test_whitelist_custom(self):
| self._setup_config(whitelist=set(['blues', 'rock', 'jazz']), count=2)
self.assertEqual(self.plugin._resolve_genres(['pop', 'blues']), u'Blues')
self._setup_config(canonical='', whitelist=set(['rock']))
self.assertEqual(self.plugin._resolve_genres(['delta blues']), u'')
|
'Keep the n first genres, as we expect them to be sorted from more to
less popular.'
| def test_count(self):
| self._setup_config(whitelist=set(['blues', 'rock', 'jazz']), count=2)
self.assertEqual(self.plugin._resolve_genres(['jazz', 'pop', 'rock', 'blues']), u'Jazz, Rock')
|
'Keep the n first genres, after having applied c14n when necessary'
| def test_count_c14n(self):
| self._setup_config(whitelist=set(['blues', 'rock', 'jazz']), canonical=True, count=2)
self.assertEqual(self.plugin._resolve_genres(['jazz', 'pop', 'country blues', 'rock']), u'Jazz, Blues')
|
'Genres first pass through c14n and are then filtered'
| def test_c14n_whitelist(self):
| self._setup_config(canonical=True, whitelist=set(['rock']))
self.assertEqual(self.plugin._resolve_genres(['delta blues']), u'')
|
'For backwards compatibility, setting the `canonical` option
to the empty string enables it using the default tree.'
| def test_empty_string_enables_canonical(self):
| self._setup_config(canonical='', count=99)
self.assertEqual(self.plugin._resolve_genres(['delta blues']), u'Blues')
|
'Again for backwards compatibility, setting the `whitelist`
option to the empty string enables the default set of genres.'
| def test_empty_string_enables_whitelist(self):
| self._setup_config(whitelist='')
self.assertEqual(self.plugin._resolve_genres(['iota blues']), u'')
|
'Remove duplicated genres.'
| def test_no_duplicate(self):
| self._setup_config(count=99)
self.assertEqual(self.plugin._resolve_genres(['blues', 'blues']), u'Blues')
|
'The default configuration should import everything.'
| def test_import_default(self):
| self.__run([('Album: %s' % displayable_path(self.artist_path)), (' %s' % displayable_path(self.artist_paths[0])), (' %s' % displayable_path(self.artist_paths[1])), ('Album: %s' % displayable_path(self.album_path)), (' %s' % displayable_path(self.album_paths[0])), (' %s' % displayab... |
'Find the pre-import MediaFile for an Item'
| def find_media_file(self, item):
| for m in self.media_files:
if (m.title.replace('Tag', 'Applied') == item.title):
return m
raise AssertionError((u'No MediaFile found for Item ' + util.displayable_path(item.path)))
|
'For comparing file modification times at a sufficient precision'
| def assertEqualTimes(self, first, second, msg=None):
| self.assertAlmostEqual(first, second, places=4, msg=msg)
|
'Root logger level should be shared between threads.'
| def test_root_logger_levels(self):
| self.config['threaded'] = True
blog.getLogger('beets').set_global_level(blog.WARNING)
with helper.capture_log() as logs:
importer = self.create_importer()
importer.run()
self.assertEqual(logs, [])
blog.getLogger('beets').set_global_level(blog.INFO)
with helper.capture_log() as lo... |
'Create a mock `Popen` object.'
| def _popen(self, status=0, stdout='', stderr=''):
| popen = MagicMock(returncode=status)
popen.communicate.return_value = (stdout, stderr)
return popen
|
'Assert that an object is a Symbol with the given identifier.'
| def _assert_symbol(self, obj, ident):
| self.assertTrue(isinstance(obj, functemplate.Symbol), (u'not a Symbol: %s' % repr(obj)))
self.assertEqual(obj.ident, ident, (u'wrong identifier: %s vs. %s' % (repr(obj.ident), repr(ident))))
|
'Assert that an object is a Call with the given identifier and
argument count.'
| def _assert_call(self, obj, ident, numargs):
| self.assertTrue(isinstance(obj, functemplate.Call), (u'not a Call: %s' % repr(obj)))
self.assertEqual(obj.ident, ident, (u'wrong identifier: %s vs. %s' % (repr(obj.ident), repr(ident))))
self.assertEqual(len(obj.args), numargs, (u'wrong argument count in %s: %i vs. ... |
'For compatibility with OS X/iTunes.
See https://github.com/beetbox/beets/issues/899#issuecomment-62437773'
| def test_image_encoding(self):
| for v23 in [True, False]:
mf = self._make_test(id3v23=v23)
try:
mf.images = [mediafile.Image('data', desc=u''), mediafile.Image('data', desc=u'foo'), mediafile.Image('data', desc=u'\u0185')]
mf.save()
apic_frames = mf.mgfile.tags.getall('APIC')
encodin... |
'Check that two paths are equal.'
| def assert_equal_path(self, a, b):
| self.assertEqual(util.normpath(a), util.normpath(b), u'paths are not equal: {!r} and {!r}'.format(a, b))
|
'Create a temporary directory and assign it into `self.temp_dir`.
Call `remove_temp_dir` later to delete it.'
| def create_temp_dir(self):
| path = tempfile.mkdtemp()
if (not isinstance(path, bytes)):
path = path.encode('utf8')
self.temp_dir = path
|
'Delete the temporary directory created by `create_temp_dir`.'
| def remove_temp_dir(self):
| if os.path.isdir(self.temp_dir):
shutil.rmtree(self.temp_dir)
|
'Execute the fetch_art coroutine for the task and return the
album\'s resulting artpath. ``should_exist`` specifies whether to
assert that art path was set (to the correct value) or or that
the path was not set.'
| def _fetch_art(self, should_exist):
| self.plugin.fetch_art(self.session, self.task)
self.plugin.assign_art(self.session, self.task)
artpath = self.lib.albums()[0].artpath
if should_exist:
self.assertEqual(artpath, os.path.join(os.path.dirname(self.i.path), 'cover.jpg'))
self.assertExists(artpath)
else:
self.asse... |
'Skip the test if the art resizer doesn\'t have ImageMagick or
PIL (so comparisons and measurements are unavailable).'
| def _require_backend(self):
| if (ArtResizer.shared.method[0] == WEBPROXY):
self.skipTest(u'ArtResizer has no local imaging backend available')
|
'Ignore extended image attributes in the base tests.'
| def assertExtendedImageAttributes(self, image, **kwargs):
| pass
|
'The `unparseable.*` fixture should not crash but should return None
for all parts of the release date.'
| def test_unparseable_date(self):
| mediafile = self._mediafile_fixture('unparseable')
self.assertIsNone(mediafile.date)
self.assertIsNone(mediafile.year)
self.assertIsNone(mediafile.month)
self.assertIsNone(mediafile.day)
|
'Return dictionary of tags, mapping tag names to values.'
| def _generate_tags(self, base=None):
| tags = {}
for key in self.tag_fields:
if key.startswith('rg_'):
tags[key] = 1.0
elif key.startswith('r128_'):
tags[key] = (-1)
else:
tags[key] = ('value\\u2010%s' % key)
for key in ['disc', 'disctotal', 'track', 'tracktotal', 'bpm']:
tags[k... |
'Set up configuration'
| def setUp(self):
| self.setup_beets()
self.load_plugins('ftintitle')
|
'Set up configuration'
| def setUp(self):
| ftintitle.FtInTitlePlugin()
|
'Test the presence of plugin choices on the prompt (album).'
| def test_plugin_choices_in_ui_input_options_album(self):
| class DummyPlugin(plugins.BeetsPlugin, ):
def __init__(self):
super(DummyPlugin, self).__init__()
self.register_listener('before_choose_candidate', self.return_choices)
def return_choices(self, session, task):
return [ui.commands.PromptChoice('f', u'Foo', None), u... |
'Test the presence of plugin choices on the prompt (singleton).'
| def test_plugin_choices_in_ui_input_options_singleton(self):
| class DummyPlugin(plugins.BeetsPlugin, ):
def __init__(self):
super(DummyPlugin, self).__init__()
self.register_listener('before_choose_candidate', self.return_choices)
def return_choices(self, session, task):
return [ui.commands.PromptChoice('f', u'Foo', None), u... |
'Test the short letter conflict solving.'
| def test_choices_conflicts(self):
| class DummyPlugin(plugins.BeetsPlugin, ):
def __init__(self):
super(DummyPlugin, self).__init__()
self.register_listener('before_choose_candidate', self.return_choices)
def return_choices(self, session, task):
return [ui.commands.PromptChoice('a', u'A foo', Non... |
'Test that plugin callbacks are being called upon user choice.'
| def test_plugin_callback(self):
| class DummyPlugin(plugins.BeetsPlugin, ):
def __init__(self):
super(DummyPlugin, self).__init__()
self.register_listener('before_choose_candidate', self.return_choices)
def return_choices(self, session, task):
return [ui.commands.PromptChoice('f', u'Foo', self.foo... |
'Test that plugin callbacks that return a value exit the loop.'
| def test_plugin_callback_return(self):
| class DummyPlugin(plugins.BeetsPlugin, ):
def __init__(self):
super(DummyPlugin, self).__init__()
self.register_listener('before_choose_candidate', self.return_choices)
def return_choices(self, session, task):
return [ui.commands.PromptChoice('f', u'Foo', self.foo... |
'Given a Query `q`, assert that:
- q OR not(q) == all items
- q AND not(q) == 0
- not(not(q)) == q'
| def assertNegationProperties(self, q):
| not_q = dbcore.query.NotQuery(q)
q_or = dbcore.query.OrQuery([q, not_q])
q_and = dbcore.query.AndQuery([q, not_q])
self.assert_items_matched_all(self.lib.items(q_or))
self.assert_items_matched(self.lib.items(q_and), [])
all_titles = set([i.title for i in self.lib.items()])
q_results = set([i... |
'Test both negation prefixes on a keyed query.'
| def test_get_prefixes_keyed(self):
| q0 = u'-title:qux'
q1 = u'^title:qux'
results0 = self.lib.items(q0)
results1 = self.lib.items(q1)
self.assert_items_matched(results0, [u'foo bar', u'beets 4 eva'])
self.assert_items_matched(results1, [u'foo bar', u'beets 4 eva'])
|
'Test both negation prefixes on an unkeyed query.'
| def test_get_prefixes_unkeyed(self):
| q0 = u'-qux'
q1 = u'^qux'
results0 = self.lib.items(q0)
results1 = self.lib.items(q1)
self.assert_items_matched(results0, [u'foo bar', u'beets 4 eva'])
self.assert_items_matched(results1, [u'foo bar', u'beets 4 eva'])
|
'Test that the results are the same regardless of the `fast` flag
for negated `FieldQuery`s.
TODO: investigate NoneQuery(fast=False), as it is raising
AttributeError: type object \'NoneQuery\' has no attribute \'field\'
at NoneQuery.match() (due to being @classmethod, and no self?)'
| def test_fast_vs_slow(self):
| classes = [(dbcore.query.DateQuery, [u'added', u'2001-01-01']), (dbcore.query.MatchQuery, [u'artist', u'one']), (dbcore.query.NumericQuery, [u'year', u'2002']), (dbcore.query.StringFieldQuery, [u'year', u'2001']), (dbcore.query.RegexpQuery, [u'album', u'^.a']), (dbcore.query.SubstringQuery, [u'title', u'x'])]
f... |
'Create response for mocking the get_music_section function.'
| def add_response_get_music_section(self, section_name='Music'):
| escaped_section_name = section_name.replace('"', '\\"')
body = (('<?xml version="1.0" encoding="UTF-8"?><MediaContainer size="3" allowSync="0" identifier="com.plexapp.plugins.library" mediaTagPrefix="/system/bundle/media/flags/" mediaTagVersion="1413367228" title1="Plex Library"><Dire... |
'Create response for mocking the update_plex function.'
| def add_response_update_plex(self):
| body = ''
status = 200
content_type = 'text/html'
responses.add(responses.GET, 'http://localhost:32400/library/sections/2/refresh', body=body, status=status, content_type=content_type)
|
'If a single year is given, range starts from this year and stops at
the year preceding the one of next bucket.'
| def test_year_single_year(self):
| self._setup_config(bucket_year=['1950s', '1970s'])
self.assertEqual(self.plugin._tmpl_bucket('1959'), '1950s')
self.assertEqual(self.plugin._tmpl_bucket('1969'), '1950s')
|
'If a single year is given for the last bucket, extend it to current
year.'
| def test_year_single_year_last_folder(self):
| self._setup_config(bucket_year=['1950', '1970'])
self.assertEqual(self.plugin._tmpl_bucket('2014'), '1970')
self.assertEqual(self.plugin._tmpl_bucket('2025'), '2025')
|
'Buckets can be named with the \'from-to\' syntax.'
| def test_year_two_years(self):
| self._setup_config(bucket_year=['1950-59', '1960-1969'])
self.assertEqual(self.plugin._tmpl_bucket('1959'), '1950-59')
self.assertEqual(self.plugin._tmpl_bucket('1969'), '1960-1969')
|
'Buckets can be named by listing all the years'
| def test_year_multiple_years(self):
| self._setup_config(bucket_year=['1950,51,52,53'])
self.assertEqual(self.plugin._tmpl_bucket('1953'), '1950,51,52,53')
self.assertEqual(self.plugin._tmpl_bucket('1974'), '1974')
|
'If no range match, return the year'
| def test_year_out_of_range(self):
| self._setup_config(bucket_year=['1950-59', '1960-69'])
self.assertEqual(self.plugin._tmpl_bucket('1974'), '1974')
self._setup_config(bucket_year=[])
self.assertEqual(self.plugin._tmpl_bucket('1974'), '1974')
|
'If no defined range match, extrapolate all ranges using the most
common syntax amongst existing buckets and return the matching one.'
| def test_year_out_of_range_extrapolate(self):
| self._setup_config(bucket_year=['1950-59', '1960-69'], extrapolate=True)
self.assertEqual(self.plugin._tmpl_bucket('1914'), '1910-19')
self._setup_config(bucket_year=['1962-81', '2002', '2012'], extrapolate=True)
self.assertEqual(self.plugin._tmpl_bucket('1983'), '1982')
self._setup_config(bucket_ye... |
'Alphabet buckets can be named by listing all their chars'
| def test_alpha_all_chars(self):
| self._setup_config(bucket_alpha=['ABCD', 'FGH', 'IJKL'])
self.assertEqual(self.plugin._tmpl_bucket('garry'), 'FGH')
|
'Alphabet buckets can be named by listing the \'from-to\' syntax'
| def test_alpha_first_last_chars(self):
| self._setup_config(bucket_alpha=['0->9', 'A->D', 'F-H', 'I->Z'])
self.assertEqual(self.plugin._tmpl_bucket('garry'), 'F-H')
self.assertEqual(self.plugin._tmpl_bucket('2pac'), '0->9')
|
'If no range match, return the initial'
| def test_alpha_out_of_range(self):
| self._setup_config(bucket_alpha=['ABCD', 'FGH', 'IJKL'])
self.assertEqual(self.plugin._tmpl_bucket('errol'), 'E')
self._setup_config(bucket_alpha=[])
self.assertEqual(self.plugin._tmpl_bucket('errol'), 'E')
|
'Check regex is used'
| def test_alpha_regex(self):
| self._setup_config(bucket_alpha=['foo', 'bar'], bucket_alpha_regex={'foo': '^[a-d]', 'bar': '^[e-z]'})
self.assertEqual(self.plugin._tmpl_bucket('alpha'), 'foo')
self.assertEqual(self.plugin._tmpl_bucket('delta'), 'foo')
self.assertEqual(self.plugin._tmpl_bucket('zeta'), 'bar')
self.assertEqual(self... |
'Check mixing regex and non-regex is possible'
| def test_alpha_regex_mix(self):
| self._setup_config(bucket_alpha=['A - D', 'E - L'], bucket_alpha_regex={'A - D': '^[0-9a-dA-D\xe2\x80\xa6\xc3\xa4\xc3\x84]'})
self.assertEqual(self.plugin._tmpl_bucket('alpha'), 'A - D')
self.assertEqual(self.plugin._tmpl_bucket('\xc3\x84rzte'), 'A - D')
self.assertEqual(se... |
'If bad alpha range definition, a UserError is raised.'
| def test_bad_alpha_range_def(self):
| with self.assertRaises(ui.UserError):
self._setup_config(bucket_alpha=['$%'])
|
'If bad year range definition, a UserError is raised.
Range origin must be expressed on 4 digits.'
| def test_bad_year_range_def_no4digits(self):
| with self.assertRaises(ui.UserError):
self._setup_config(bucket_year=['62-64'])
|
'If bad year range definition, a UserError is raised.
At least the range origin must be declared.'
| def test_bad_year_range_def_nodigits(self):
| with self.assertRaises(ui.UserError):
self._setup_config(bucket_year=['nodigits'])
|
'Return a conversion command that copies files and appends
`tag` to the copy.'
| def tagged_copy_cmd(self, tag):
| if re.search('[^a-zA-Z0-9]', tag):
raise ValueError(u"tag '{0}' must only contain letters and digits".format(tag))
stub = os.path.join(_common.RSRC, 'convert_stub.py').decode('utf-8')
return u'{} {} $source $dest {}'.format(shell_quote(sys.executable), shell_quote(st... |
'Assert that the path is a file and the files content ends with `tag`.'
| def assertFileTag(self, path, tag):
| display_tag = tag
tag = tag.encode('utf-8')
self.assertTrue(os.path.isfile(path), u'{0} is not a file'.format(util.displayable_path(path)))
with open(path, 'rb') as f:
f.seek((- len(display_tag)), os.SEEK_END)
self.assertEqual(f.read(), tag, u'{0} is not tagged wi... |
'Assert that the path is a file and the files content does not
end with `tag`.'
| def assertNoFileTag(self, path, tag):
| display_tag = tag
tag = tag.encode('utf-8')
self.assertTrue(os.path.isfile(path), u'{0} is not a file'.format(util.displayable_path(path)))
with open(path, 'rb') as f:
f.seek((- len(tag)), os.SEEK_END)
self.assertNotEqual(f.read(), tag, u'{0} is unexpectedly tagged ... |
'Run the `convert` command on a given path.'
| def run_convert_path(self, path, *args):
| path = path.decode(util._fsencoding()).encode(util.arg_encoding())
args = (args + (('path:' + path),))
return self.run_command('convert', *args)
|
'Run the `convert` command on `self.item`.'
| def run_convert(self, *args):
| return self.run_convert_path(self.item.path, *args)
|
'Setup pristine global configuration and library for testing.
Sets ``beets.config`` so we can safely use any functionality
that uses the global configuration. All paths used are
contained in a temporary directory
Sets the following properties on itself.
- ``temp_dir`` Path to a temporary directory containing all
files... | def setup_beets(self, disk=False):
| self.create_temp_dir()
os.environ['BEETSDIR'] = util.py3_path(self.temp_dir)
self.config = beets.config
self.config.clear()
self.config.read()
self.config['plugins'] = []
self.config['verbose'] = 1
self.config['ui']['color'] = False
self.config['threaded'] = False
self.libdir = o... |
'Load and initialize plugins by names.
Similar setting a list of plugins in the configuration. Make
sure you call ``unload_plugins()`` afterwards.'
| def load_plugins(self, *plugins):
| beets.config['plugins'] = plugins
beets.plugins.load_plugins(plugins)
beets.plugins.find_plugins()
Item._original_types = dict(Item._types)
Album._original_types = dict(Album._types)
Item._types.update(beets.plugins.types(Item))
Album._types.update(beets.plugins.types(Album))
|
'Unload all plugins and remove the from the configuration.'
| def unload_plugins(self):
| beets.config['plugins'] = []
beets.plugins._classes = set()
beets.plugins._instances = {}
Item._types = Item._original_types
Album._types = Album._original_types
|
'Create files to import and return corresponding session.
Copies the specified number of files to a subdirectory of
`self.temp_dir` and creates a `TestImportSession` for this path.'
| def create_importer(self, item_count=1, album_count=1):
| import_dir = os.path.join(self.temp_dir, 'import')
if (not os.path.isdir(import_dir)):
os.mkdir(import_dir)
album_no = 0
while album_count:
album = util.bytestring_path(u'album {0}'.format(album_no))
album_dir = os.path.join(import_dir, album)
if os.path.exists(album_d... |
'Return an `Item` instance with sensible default values.
The item receives its attributes from `**values` paratmeter. The
`title`, `artist`, `album`, `track`, `format` and `path`
attributes have defaults if they are not given as parameters.
The `title` attribute is formated with a running item count to
prevent duplicat... | def create_item(self, **values):
| item_count = self._get_item_count()
values_ = {'title': u't\xeftle {0}', 'artist': u'the \xe4rtist', 'album': u'the \xe4lbum', 'track': item_count, 'format': 'MP3'}
values_.update(values)
values_['title'] = values_['title'].format(item_count)
values_['db'] = self.lib
item = Item(**value... |
'Add an item to the library and return it.
Creates the item by passing the parameters to `create_item()`.
If `path` is not set in `values` it is set to `item.destination()`.'
| def add_item(self, **values):
| if ('path' in values):
values['path'] = util.normpath(values['path'])
item = self.create_item(**values)
item.add(self.lib)
if ('path' not in values):
item['path'] = item.destination()
item.store()
return item
|
'Add an item with an actual audio file to the library.'
| def add_item_fixture(self, **values):
| item = self.create_item(**values)
extension = item['format'].lower()
item['path'] = os.path.join(_common.RSRC, util.bytestring_path(('min.' + extension)))
item.add(self.lib)
item.move(copy=True)
item.store()
return item
|
'Add a number of items with files to the database.'
| def add_item_fixtures(self, ext='mp3', count=1):
| items = []
path = os.path.join(_common.RSRC, util.bytestring_path(('full.' + ext)))
for i in range(count):
item = Item.from_path(path)
item.album = u'\xe4lbum {0}'.format(i)
item.title = u't\xeftle {0}'.format(i)
item.add(self.lib)
item.move(copy=True)
i... |
'Add an album with files to the database.'
| def add_album_fixture(self, track_count=1, ext='mp3'):
| items = []
path = os.path.join(_common.RSRC, util.bytestring_path(('full.' + ext)))
for i in range(track_count):
item = Item.from_path(path)
item.album = u'\xe4lbum'
item.title = u't\xeftle {0}'.format(i)
item.add(self.lib)
item.move(copy=True)
item.store()... |
'Copies a fixture mediafile with the extension to a temporary
location and returns the path.
It keeps track of the created locations and will delete the with
`remove_mediafile_fixtures()`
`images` is a subset of \'png\', \'jpg\', and \'tiff\'. For each
specified extension a cover art image is added to the media
file.'
| def create_mediafile_fixture(self, ext='mp3', images=[]):
| src = os.path.join(_common.RSRC, util.bytestring_path(('full.' + ext)))
(handle, path) = mkstemp()
os.close(handle)
shutil.copyfile(src, path)
if images:
mediafile = MediaFile(path)
imgs = []
for img_ext in images:
file = util.bytestring_path('image-2x3.{0}'.forma... |
'Run a beets command with an arbitrary amount of arguments. The
Library` defaults to `self.lib`, but can be overridden with
the keyword argument `lib`.'
| def run_command(self, *args, **kwargs):
| sys.argv = ['beet']
lib = None
if hasattr(self, 'lib'):
lib = self.lib
lib = kwargs.get('lib', lib)
beets.ui._raw_main(_convert_args(list(args)), lib)
|
'Create a temporary directory and assign it into
`self.temp_dir`. Call `remove_temp_dir` later to delete it.'
| def create_temp_dir(self):
| temp_dir = mkdtemp()
self.temp_dir = util.bytestring_path(temp_dir)
|
'Delete the temporary directory created by `create_temp_dir`.'
| def remove_temp_dir(self):
| shutil.rmtree(self.temp_dir)
|
'Create a file at `path` with given content.
If `dir` is given, it is prepended to `path`. After that, if the
path is relative, it is resolved with respect to
`self.temp_dir`.'
| def touch(self, path, dir=None, content=''):
| if dir:
path = os.path.join(dir, path)
if (not os.path.isabs(path)):
path = os.path.join(self.temp_dir, path)
parent = os.path.dirname(path)
if (not os.path.isdir(parent)):
os.makedirs(util.syspath(parent))
with open(util.syspath(path), 'a+') as f:
f.write(content)
... |
'Returns a Bag that mimics a discogs_client.Release. The list
of elements on the returned Bag is incomplete, including just
those required for the tests on this class.'
| def _make_release(self, tracks=None):
| data = {'id': 'ALBUM ID', 'uri': 'ALBUM URI', 'title': 'ALBUM TITLE', 'year': '3001', 'artists': [{'name': 'ARTIST NAME', 'id': 'ARTIST ID', 'join': ','}], 'formats': [{'descriptions': ['FORMAT DESC 1', 'FORMAT DESC 2'], 'name': 'FORMAT', 'qty': 1}], 'labels': [{'name': 'LABEL NAME', '... |
'Return a Bag that mimics a discogs_client.Release with a
tracklist where tracks have the specified `positions`.'
| def _make_release_from_positions(self, positions):
| tracks = [self._make_track(('TITLE%s' % i), position) for (i, position) in enumerate(positions, start=1)]
return self._make_release(tracks)
|
'Test the conversion of discogs `position` to medium, medium_index
and subtrack_index.'
| def test_parse_position(self):
| positions = [('1', (None, '1', None)), ('A12', ('A', '12', None)), ('12-34', ('12-', '34', None)), ('CD1-1', ('CD1-', '1', None)), ('1.12', (None, '1', '12')), ('12.a', (None, '12', 'A')), ('12.34', (None, '12', '34')), ('1ab', (None, '1', 'AB')), ('IV', ('IV', None, None))]
d = DiscogsPlugin()
for (positio... |
'Test standard Discogs position 12.2.9#1: "without sides".'
| def test_parse_tracklist_without_sides(self):
| release = self._make_release_from_positions(['1', '2', '3'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 1)
self.assertEqual(len(d.tracks), 3)
|
'Test standard Discogs position 12.2.9#2: "with sides".'
| def test_parse_tracklist_with_sides(self):
| release = self._make_release_from_positions(['A1', 'A2', 'B1', 'B2'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 1)
self.assertEqual(len(d.tracks), 4)
|
'Test standard Discogs position 12.2.9#3: "multiple LP".'
| def test_parse_tracklist_multiple_lp(self):
| release = self._make_release_from_positions(['A1', 'A2', 'B1', 'C1'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 2)
self.assertEqual(len(d.tracks), 4)
|
'Test standard Discogs position 12.2.9#4: "multiple CDs".'
| def test_parse_tracklist_multiple_cd(self):
| release = self._make_release_from_positions(['1-1', '1-2', '2-1', '3-1'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 3)
self.assertEqual(len(d.tracks), 4)
|
'Test non standard Discogs position.'
| def test_parse_tracklist_non_standard(self):
| release = self._make_release_from_positions(['I', 'II', 'III', 'IV'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 1)
self.assertEqual(len(d.tracks), 4)
|
'Test standard Discogs position 12.2.9#5: "sub tracks, dots".'
| def test_parse_tracklist_subtracks_dot(self):
| release = self._make_release_from_positions(['1', '2.1', '2.2', '3'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 1)
self.assertEqual(len(d.tracks), 3)
release = self._make_release_from_positions(['A1', 'A2.1', 'A2.2', 'A3'])
d = DiscogsPlugin().get_album_info(release... |
'Test standard Discogs position 12.2.9#5: "sub tracks, letter".'
| def test_parse_tracklist_subtracks_letter(self):
| release = self._make_release_from_positions(['A1', 'A2a', 'A2b', 'A3'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 1)
self.assertEqual(len(d.tracks), 3)
release = self._make_release_from_positions(['A1', 'A2.a', 'A2.b', 'A3'])
d = DiscogsPlugin().get_album_info(relea... |
'Test standard Discogs position 12.2.9#6: "extra material".'
| def test_parse_tracklist_subtracks_extra_material(self):
| release = self._make_release_from_positions(['1', '2', 'Video 1'])
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 2)
self.assertEqual(len(d.tracks), 3)
|
'Test parsing of subtracks that include index tracks.'
| def test_parse_tracklist_subtracks_indices(self):
| release = self._make_release_from_positions(['', '', '1.1', '1.2'])
release.data['tracklist'][0]['title'] = 'MEDIUM TITLE'
release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE'
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 1)
self.assertEqual(d.tracks[0].... |
'Test parsing of subtracks defined inside a index track that are
logical subtracks (ie. should be grouped together into a single track).'
| def test_parse_tracklist_subtracks_nested_logical(self):
| release = self._make_release_from_positions(['1', '', '3'])
release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE'
release.data['tracklist'][1]['sub_tracks'] = [self._make_track('TITLE ONE', '2.1', '01:01'), self._make_track('TITLE TWO', '2.2', '02:02')]
d = DiscogsPlugin().get_album_in... |
'Test parsing of subtracks defined inside a index track that are
physical subtracks (ie. should not be grouped together).'
| def test_parse_tracklist_subtracks_nested_physical(self):
| release = self._make_release_from_positions(['1', '', '4'])
release.data['tracklist'][1]['title'] = 'TRACK GROUP TITLE'
release.data['tracklist'][1]['sub_tracks'] = [self._make_track('TITLE ONE', '2', '01:01'), self._make_track('TITLE TWO', '3', '02:02')]
d = DiscogsPlugin().get_album_info(r... |
'Test parsing of index tracks that act as disc titles.'
| def test_parse_tracklist_disctitles(self):
| release = self._make_release_from_positions(['', '1-1', '1-2', '', '2-1'])
release.data['tracklist'][0]['title'] = 'MEDIUM TITLE CD1'
release.data['tracklist'][3]['title'] = 'MEDIUM TITLE CD2'
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d.mediums, 2)
self.assertEqual... |
'Test parsing of a release with the minimal amount of information.'
| def test_parse_minimal_release(self):
| data = {'id': 123, 'tracklist': [self._make_track('A', '1', '01:01')], 'artists': [{'name': 'ARTIST NAME', 'id': 321, 'join': ''}], 'title': 'TITLE'}
release = Bag(data=data, title=data['title'], artists=[Bag(data=d) for d in data['artists']])
d = DiscogsPlugin().get_album_info(release)
self.assertEq... |
'Test parsing of a release that does not have the required fields.'
| def test_parse_release_without_required_fields(self):
| release = Bag(data={}, refresh=(lambda *args: None))
with capture_log() as logs:
d = DiscogsPlugin().get_album_info(release)
self.assertEqual(d, None)
self.assertIn('Release does not contain the required fields', logs[0])
|
'Set up configuration.'
| def setUp(self):
| lyrics.LyricsPlugin()
|
'Set up configuration.'
| def setUp(self):
| try:
__import__('bs4')
except ImportError:
self.skipTest('Beautiful Soup 4 not available')
if (sys.version_info[:3] < (2, 7, 3)):
self.skipTest("Python's built-in HTML parser is not good enough")
|
'Test default backends with songs known to exist in respective databases.'
| @unittest.skipUnless((os.environ.get('BEETS_TEST_LYRICS_SOURCES', '0') == '1'), 'lyrics sources testing not enabled')
def test_backend_sources_ok(self):
| errors = []
for s in self.DEFAULT_SOURCES:
res = s['backend'](self.plugin.config, self.plugin._log).fetch(s['artist'], s['title'])
if (not is_lyrics_content_ok(s['title'], res)):
errors.append(s['backend'].__name__)
self.assertFalse(errors)
|
'Test if lyrics present on websites registered in beets google custom
search engine are correctly scraped.'
| @unittest.skipUnless((os.environ.get('BEETS_TEST_LYRICS_SOURCES', '0') == '1'), 'lyrics sources testing not enabled')
def test_google_sources_ok(self):
| for s in self.GOOGLE_SOURCES:
url = (s['url'] + s['path'])
res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url))
self.assertTrue(google.is_lyrics(res), url)
self.assertTrue(is_lyrics_content_ok(s['title'], res), url)
|
'Set up configuration'
| def setUp(self):
| LyricsGoogleBaseTest.setUp(self)
self.plugin = lyrics.LyricsPlugin()
|
'Test that lyrics of the mocked page are correctly scraped'
| @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl())
def test_mocked_source_ok(self):
| url = (self.source['url'] + self.source['path'])
res = lyrics.scrape_lyrics_from_html(raw_backend.fetch_url(url))
self.assertTrue(google.is_lyrics(res), url)
self.assertTrue(is_lyrics_content_ok(self.source['title'], res), url)
|
'Test matching html page title with song infos -- when song infos are
present in the title.'
| @patch.object(lyrics.Backend, 'fetch_url', MockFetchUrl())
def test_is_page_candidate_exact_match(self):
| from bs4 import SoupStrainer, BeautifulSoup
s = self.source
url = six.text_type((s['url'] + s['path']))
html = raw_backend.fetch_url(url)
soup = BeautifulSoup(html, 'html.parser', parse_only=SoupStrainer('title'))
self.assertEqual(google.is_page_candidate(url, soup.title.string, s['title'], s['a... |
'Test matching html page title with song infos -- when song infos are
not present in the title.'
| def test_is_page_candidate_fuzzy_match(self):
| s = self.source
url = (s['url'] + s['path'])
url_title = u'example.com | Beats song by John doe'
self.assertEqual(google.is_page_candidate(url, url_title, s['title'], s['artist']), True, url)
url_title = u'example.com | seets bong lyrics by John doe'
self.a... |
'Ensure that `is_page_candidate` doesn\'t crash when the artist
and such contain special regular expression characters.'
| def test_is_page_candidate_special_chars(self):
| s = self.source
url = (s['url'] + s['path'])
url_title = u'foo'
google.is_page_candidate(url, url_title, s['title'], u'Sunn O)))')
|
'`self.contents` and `self.replacements` are initialized here, in
order to keep the rest of the functions of this class with the same
signature as `EditPlugin.get_editor()`, making mocking easier.
- `contents`: string with the contents of the file to be used for
`overwrite_contents()`
- `replacement`: dict with the in-... | def __init__(self, contents=None, replacements=None):
| self.contents = contents
self.replacements = replacements
self.action = self.overwrite_contents
if replacements:
self.action = self.replace_contents
|
'Modify `filename`, replacing its contents with `self.contents`. If
`self.contents` is empty, the file remains unchanged.'
| def overwrite_contents(self, filename, log):
| if self.contents:
with codecs.open(filename, 'w', encoding='utf-8') as f:
f.write(self.contents)
|
'Modify `filename`, reading its contents and replacing the strings
specified in `self.replacements`.'
| def replace_contents(self, filename, log):
| with codecs.open(filename, 'r', encoding='utf-8') as f:
contents = f.read()
for (old, new_) in self.replacements.items():
contents = contents.replace(old, new_)
with codecs.open(filename, 'w', encoding='utf-8') as f:
f.write(contents)
|
'Assert that items in the library (`lib_items`) have different values
on the specified `fields` (and *only* on those fields), compared to
`items`.
An empty `fields` list results in asserting that no modifications have
been performed. `allowed` is a list of field changes that are ignored
(they may or may not have change... | def assertItemFieldsModified(self, library_items, items, fields=[], allowed=['path']):
| for (lib_item, item) in zip(library_items, items):
diff_fields = [field for field in lib_item._fields if (lib_item[field] != item[field])]
self.assertEqual(set(diff_fields).difference(allowed), set(fields))
|
'Run the edit command during an import session, with mocked stdin and
yaml writing.'
| def run_mocked_interpreter(self, modify_file_args={}, stdin=[]):
| m = ModifyFileMocker(**modify_file_args)
with patch('beetsplug.edit.edit', side_effect=m.action):
with control_stdin('\n'.join(stdin)):
self.importer.run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.