Remove unused imports

Fix imports
Fix formatting
This commit is contained in:
Andrew Rogl 2021-08-26 20:59:48 +10:00
parent 0f48ccde78
commit ee4268dabb
63 changed files with 84 additions and 125 deletions

View file

@ -18,7 +18,6 @@
import musicbrainzngs import musicbrainzngs
import re import re
import traceback import traceback
from six.moves.urllib.parse import urljoin
from beets import logging from beets import logging
from beets import plugins from beets import plugins
@ -26,6 +25,7 @@ import beets.autotag.hooks
import beets import beets
from beets import util from beets import util
from beets import config from beets import config
from urllib.parse import urljoin
VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377' VARIOUS_ARTISTS_ID = '89ad4ac3-39f7-470e-963a-56509c546377'

View file

@ -29,7 +29,6 @@ import subprocess
import platform import platform
import shlex import shlex
from beets.util import hidden from beets.util import hidden
import six
from unidecode import unidecode from unidecode import unidecode
from enum import Enum from enum import Enum
@ -100,6 +99,7 @@ class FilesystemError(HumanReadableException):
via a function in this module. The `paths` field is a sequence of via a function in this module. The `paths` field is a sequence of
pathnames involved in the operation. pathnames involved in the operation.
""" """
def __init__(self, reason, verb, paths, tb=None): def __init__(self, reason, verb, paths, tb=None):
self.paths = paths self.paths = paths
super().__init__(reason, verb, tb) super().__init__(reason, verb, tb)
@ -599,6 +599,7 @@ def unique_path(path):
if not os.path.exists(new_path): if not os.path.exists(new_path):
return new_path return new_path
# Note: The Windows "reserved characters" are, of course, allowed on # Note: The Windows "reserved characters" are, of course, allowed on
# Unix. They are forbidden here because they cause problems on Samba # Unix. They are forbidden here because they cause problems on Samba
# shares, which are sufficiently common as to cause frequent problems. # shares, which are sufficiently common as to cause frequent problems.
@ -736,8 +737,6 @@ def py3_path(path):
if isinstance(path, str): if isinstance(path, str):
return path return path
assert isinstance(path, bytes) assert isinstance(path, bytes)
if six.PY2:
return path
return os.fsdecode(path) return os.fsdecode(path)
@ -801,7 +800,7 @@ def cpu_count():
'/usr/sbin/sysctl', '/usr/sbin/sysctl',
'-n', '-n',
'hw.ncpu', 'hw.ncpu',
]).stdout) ]).stdout)
except (ValueError, OSError, subprocess.CalledProcessError): except (ValueError, OSError, subprocess.CalledProcessError):
num = 0 num = 0
else: else:

View file

@ -20,7 +20,7 @@ import subprocess
import os import os
import re import re
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from six.moves.urllib.parse import urlencode from urllib.parse import urlencode
from beets import logging from beets import logging
from beets import util from beets import util

View file

@ -32,7 +32,7 @@ in place of any single coroutine.
""" """
from six.moves import queue import queue
from threading import Thread, Lock from threading import Thread, Lock
import sys import sys

View file

@ -287,8 +287,8 @@ class AcousticPlugin(plugins.BeetsPlugin):
# The recursive traversal. # The recursive traversal.
composites = defaultdict(list) composites = defaultdict(list)
yield from self._data_to_scheme_child(data, yield from self._data_to_scheme_child(data,
scheme, scheme,
composites) composites)
# When composites has been populated, yield the composite attributes # When composites has been populated, yield the composite attributes
# by joining their parts. # by joining their parts.
@ -309,8 +309,8 @@ class AcousticPlugin(plugins.BeetsPlugin):
if k in subdata: if k in subdata:
if type(v) == dict: if type(v) == dict:
yield from self._data_to_scheme_child(subdata[k], yield from self._data_to_scheme_child(subdata[k],
v, v,
composites) composites)
elif type(v) == tuple: elif type(v) == tuple:
composite_attribute, part_number = v composite_attribute, part_number = v
attribute_parts = composites[composite_attribute] attribute_parts = composites[composite_attribute]

View file

@ -22,7 +22,6 @@ import shlex
import os import os
import errno import errno
import sys import sys
import six
import confuse import confuse
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
from beets.ui import Subcommand from beets.ui import Subcommand

View file

@ -24,7 +24,6 @@ from beets.ui import print_, decargs
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
from beets.dbcore.query import StringFieldQuery from beets.dbcore.query import StringFieldQuery
from unidecode import unidecode from unidecode import unidecode
import six
class BareascQuery(StringFieldQuery): class BareascQuery(StringFieldQuery):
@ -75,9 +74,9 @@ class BareascPlugin(BeetsPlugin):
# Copied from commands.py - list_items # Copied from commands.py - list_items
if album: if album:
for album in lib.albums(query): for album in lib.albums(query):
bare = unidecode(six.ensure_text(str(album))) bare = unidecode(str(album))
print_(six.ensure_text(bare)) print_(bare)
else: else:
for item in lib.items(query): for item in lib.items(query):
bare = unidecode(six.ensure_text(str(item))) bare = unidecode(str(item))
print_(six.ensure_text(bare)) print_(bare)

View file

@ -17,7 +17,6 @@
import json import json
import re import re
import six
from datetime import datetime, timedelta from datetime import datetime, timedelta
from requests_oauthlib import OAuth1Session from requests_oauthlib import OAuth1Session

View file

@ -36,7 +36,6 @@ from beets.util import bluelet
from beets.library import Item from beets.library import Item
from beets import dbcore from beets import dbcore
from mediafile import MediaFile from mediafile import MediaFile
import six
PROTOCOL_VERSION = '0.16.0' PROTOCOL_VERSION = '0.16.0'
BUFSIZE = 1024 BUFSIZE = 1024

View file

@ -17,13 +17,12 @@ music player.
""" """
import six
import sys import sys
import time import time
from six.moves import _thread import _thread
import os import os
import copy import copy
from six.moves import urllib import urllib
from beets import ui from beets import ui
import gi import gi

View file

@ -126,9 +126,9 @@ def str2fmt(s):
res = {'fromnchars': len(m.group('fromyear')), res = {'fromnchars': len(m.group('fromyear')),
'tonchars': len(m.group('toyear'))} 'tonchars': len(m.group('toyear'))}
res['fmt'] = "{}%s{}{}{}".format(m.group('bef'), res['fmt'] = "{}%s{}{}{}".format(m.group('bef'),
m.group('sep'), m.group('sep'),
'%s' if res['tonchars'] else '', '%s' if res['tonchars'] else '',
m.group('after')) m.group('after'))
return res return res

View file

@ -119,7 +119,7 @@ class ConvertPlugin(BeetsPlugin):
'formats': { 'formats': {
'aac': { 'aac': {
'command': 'ffmpeg -i $source -y -vn -acodec aac ' 'command': 'ffmpeg -i $source -y -vn -acodec aac '
'-aq 1 $dest', '-aq 1 $dest',
'extension': 'm4a', 'extension': 'm4a',
}, },
'alac': { 'alac': {

View file

@ -17,7 +17,6 @@
import collections import collections
import six
import unidecode import unidecode
import requests import requests

View file

@ -24,7 +24,7 @@ import confuse
from discogs_client import Release, Master, Client from discogs_client import Release, Master, Client
from discogs_client.exceptions import DiscogsAPIError from discogs_client.exceptions import DiscogsAPIError
from requests.exceptions import ConnectionError from requests.exceptions import ConnectionError
from six.moves import http_client import http.client
import beets import beets
import re import re
import time import time
@ -40,7 +40,7 @@ API_KEY = 'rAzVUQYRaoFjeBjyWuWZ'
API_SECRET = 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy' API_SECRET = 'plxtUTqoCzwxZpqdPysCwGuBSmZNdZVy'
# Exceptions that discogs_client should really handle but does not. # Exceptions that discogs_client should really handle but does not.
CONNECTION_ERRORS = (ConnectionError, socket.error, http_client.HTTPException, CONNECTION_ERRORS = (ConnectionError, socket.error, http.client.HTTPException,
ValueError, # JSON decoding raises a ValueError. ValueError, # JSON decoding raises a ValueError.
DiscogsAPIError) DiscogsAPIError)
@ -505,7 +505,7 @@ class DiscogsPlugin(BeetsPlugin):
if self.config['index_tracks']: if self.config['index_tracks']:
for subtrack in subtracks: for subtrack in subtracks:
subtrack['title'] = '{}: {}'.format( subtrack['title'] = '{}: {}'.format(
index_track['title'], subtrack['title']) index_track['title'], subtrack['title'])
tracklist.extend(subtracks) tracklist.extend(subtracks)
else: else:
# Merge the subtracks, pick a title, and append the new track. # Merge the subtracks, pick a title, and append the new track.

View file

@ -16,7 +16,6 @@
""" """
import shlex import shlex
import six
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
from beets.ui import decargs, print_, Subcommand, UserError from beets.ui import decargs, print_, Subcommand, UserError

View file

@ -26,7 +26,6 @@ import subprocess
import yaml import yaml
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
import os import os
import six
import shlex import shlex

View file

@ -11,9 +11,7 @@
import hashlib import hashlib
import requests import requests
from six.moves.urllib.parse import urlencode from urllib.parse import urlencode, urljoin, parse_qs, urlsplit, urlunsplit
from six.moves.urllib.parse import urljoin, parse_qs, urlsplit, urlunsplit
from beets import config from beets import config
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin

View file

@ -33,7 +33,6 @@ from beets.util.artresizer import ArtResizer
from beets.util import sorted_walk from beets.util import sorted_walk
from beets.util import syspath, bytestring_path, py3_path from beets.util import syspath, bytestring_path, py3_path
import confuse import confuse
import six
CONTENT_TYPES = { CONTENT_TYPES = {
'image/jpeg': [b'jpg', b'jpeg'], 'image/jpeg': [b'jpg', b'jpeg'],

View file

@ -20,7 +20,6 @@ from beets import plugins
from beets.util import displayable_path from beets.util import displayable_path
import os import os
import re import re
import six
# Filename field extraction patterns. # Filename field extraction patterns.

View file

@ -48,7 +48,7 @@ class CodingFormatter(string.Formatter):
format_string = format_string.decode(self._coding) format_string = format_string.decode(self._coding)
return super().format(format_string, *args, return super().format(format_string, *args,
**kwargs) **kwargs)
def convert_field(self, value, conversion): def convert_field(self, value, conversion):
"""Converts the provided value given a conversion type. """Converts the provided value given a conversion type.
@ -58,7 +58,7 @@ class CodingFormatter(string.Formatter):
See string.Formatter.convert_field. See string.Formatter.convert_field.
""" """
converted = super().convert_field(value, converted = super().convert_field(value,
conversion) conversion)
if isinstance(converted, bytes): if isinstance(converted, bytes):
return converted.decode(self._coding) return converted.decode(self._coding)
@ -68,6 +68,7 @@ class CodingFormatter(string.Formatter):
class HookPlugin(BeetsPlugin): class HookPlugin(BeetsPlugin):
"""Allows custom commands to be run when an event is emitted by beets""" """Allows custom commands to be run when an event is emitted by beets"""
def __init__(self): def __init__(self):
super().__init__() super().__init__()

View file

@ -60,8 +60,8 @@ class ImportAddedPlugin(BeetsPlugin):
def record_reimported(self, task, session): def record_reimported(self, task, session):
self.reimported_item_ids = {item.id for item, replaced_items self.reimported_item_ids = {item.id for item, replaced_items
in task.replaced_items.items() in task.replaced_items.items()
if replaced_items} if replaced_items}
self.replaced_album_paths = set(task.replaced_albums.keys()) self.replaced_album_paths = set(task.replaced_albums.keys())
def write_file_mtime(self, path, mtime): def write_file_mtime(self, path, mtime):

View file

@ -20,7 +20,6 @@ import itertools
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
from beets import config from beets import config
import six
FUNC_NAME = '__INLINE_FUNC__' FUNC_NAME = '__INLINE_FUNC__'

View file

@ -26,7 +26,6 @@ Put something like the following in your config.yaml to configure:
import requests import requests
from beets import config from beets import config
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
import six
def update_kodi(host, port, user, password): def update_kodi(host, port, user, password):

View file

@ -13,8 +13,6 @@
# included in all copies or substantial portions of the Software. # included in all copies or substantial portions of the Software.
import six
"""Gets genres for imported music based on Last.fm tags. """Gets genres for imported music based on Last.fm tags.
Uses a provided whitelist file to determine which tags are valid genres. Uses a provided whitelist file to determine which tags are valid genres.
@ -266,7 +264,7 @@ class LastGenrePlugin(plugins.BeetsPlugin):
return None return None
key = '{}.{}'.format(entity, key = '{}.{}'.format(entity,
'-'.join(str(a) for a in args)) '-'.join(str(a) for a in args))
if key in self._genre_cache: if key in self._genre_cache:
return self._genre_cache[key] return self._genre_cache[key]
else: else:

View file

@ -27,8 +27,7 @@ import requests
import unicodedata import unicodedata
from unidecode import unidecode from unidecode import unidecode
import warnings import warnings
import six import urllib
from six.moves import urllib
try: try:
import bs4 import bs4
@ -47,7 +46,7 @@ try:
# PY3: HTMLParseError was removed in 3.5 as strict mode # PY3: HTMLParseError was removed in 3.5 as strict mode
# was deprecated in 3.3. # was deprecated in 3.3.
# https://docs.python.org/3.3/library/html.parser.html # https://docs.python.org/3.3/library/html.parser.html
from six.moves.html_parser import HTMLParseError from html.parser import HTMLParseError
except ImportError: except ImportError:
class HTMLParseError(Exception): class HTMLParseError(Exception):
pass pass
@ -864,8 +863,8 @@ class LyricsPlugin(plugins.BeetsPlugin):
title_str = ":index:`%s`" % item.title.strip() title_str = ":index:`%s`" % item.title.strip()
block = '| ' + item.lyrics.replace('\n', '\n| ') block = '| ' + item.lyrics.replace('\n', '\n| ')
self.rest += "{}\n{}\n\n{}\n\n".format(title_str, self.rest += "{}\n{}\n\n{}\n\n".format(title_str,
'~' * len(title_str), '~' * len(title_str),
block) block)
def writerest(self, directory): def writerest(self, directory):
"""Write self.rest to a ReST file """Write self.rest to a ReST file

View file

@ -22,7 +22,6 @@ implemented by MusicBrainz yet.
""" """
from beets.autotag import Recommendation from beets.autotag import Recommendation
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
from beets.ui.commands import PromptChoice from beets.ui.commands import PromptChoice

View file

@ -22,7 +22,6 @@ from importlib import import_module
from confuse import ConfigValueError from confuse import ConfigValueError
from beets import ui from beets import ui
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
import six
METASYNC_MODULE = 'beetsplug.metasync' METASYNC_MODULE = 'beetsplug.metasync'

View file

@ -22,7 +22,7 @@ import shutil
import tempfile import tempfile
import plistlib import plistlib
from six.moves.urllib.parse import urlparse, unquote from urllib.parse import urlparse, unquote
from time import mktime from time import mktime
from beets import util from beets import util
@ -61,12 +61,12 @@ def _norm_itunes_path(path):
class Itunes(MetaSource): class Itunes(MetaSource):
item_types = { item_types = {
'itunes_rating': types.INTEGER, # 0..100 scale 'itunes_rating': types.INTEGER, # 0..100 scale
'itunes_playcount': types.INTEGER, 'itunes_playcount': types.INTEGER,
'itunes_skipcount': types.INTEGER, 'itunes_skipcount': types.INTEGER,
'itunes_lastplayed': DateType(), 'itunes_lastplayed': DateType(),
'itunes_lastskipped': DateType(), 'itunes_lastskipped': DateType(),
'itunes_dateadded': DateType(), 'itunes_dateadded': DateType(),
} }
def __init__(self, config, log): def __init__(self, config, log):

View file

@ -14,9 +14,6 @@
import mpd import mpd
import socket
import select
import sys
import time import time
import os import os
@ -300,10 +297,10 @@ class MPDStats:
self._log.info('playing {0}', displayable_path(path)) self._log.info('playing {0}', displayable_path(path))
self.now_playing = { self.now_playing = {
'started': time.time(), 'started': time.time(),
'remaining': remaining, 'remaining': remaining,
'path': path, 'path': path,
'id': songid, 'id': songid,
'beets_item': self.get_item(path), 'beets_item': self.get_item(path),
} }
@ -331,22 +328,22 @@ class MPDStats:
class MPDStatsPlugin(plugins.BeetsPlugin): class MPDStatsPlugin(plugins.BeetsPlugin):
item_types = { item_types = {
'play_count': types.INTEGER, 'play_count': types.INTEGER,
'skip_count': types.INTEGER, 'skip_count': types.INTEGER,
'last_played': library.DateType(), 'last_played': library.DateType(),
'rating': types.FLOAT, 'rating': types.FLOAT,
} }
def __init__(self): def __init__(self):
super().__init__() super().__init__()
mpd_config.add({ mpd_config.add({
'music_directory': config['directory'].as_filename(), 'music_directory': config['directory'].as_filename(),
'strip_path': '', 'strip_path': '',
'rating': True, 'rating': True,
'rating_mix': 0.75, 'rating_mix': 0.75,
'host': os.environ.get('MPD_HOST', 'localhost'), 'host': os.environ.get('MPD_HOST', 'localhost'),
'port': int(os.environ.get('MPD_PORT', 6600)), 'port': int(os.environ.get('MPD_PORT', 6600)),
'password': '', 'password': '',
}) })
mpd_config['password'].redact = True mpd_config['password'].redact = True

View file

@ -25,7 +25,6 @@ from beets.plugins import BeetsPlugin
import os import os
import socket import socket
from beets import config from beets import config
import six
# No need to introduce a dependency on an MPD library for such a # No need to introduce a dependency on an MPD library for such a

View file

@ -9,7 +9,6 @@ import os
from beets import config, util from beets import config, util
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin
from beets.util import ancestry from beets.util import ancestry
import six
def convert_perm(perm): def convert_perm(perm):

View file

@ -10,7 +10,7 @@ Put something like the following in your config.yaml to configure:
import requests import requests
from xml.etree import ElementTree from xml.etree import ElementTree
from six.moves.urllib.parse import urljoin, urlencode from urllib.parse import urljoin, urlencode
from beets import config from beets import config
from beets.plugins import BeetsPlugin from beets.plugins import BeetsPlugin

View file

@ -18,7 +18,6 @@ import enum
import math import math
import os import os
import signal import signal
import six
import subprocess import subprocess
import sys import sys
import warnings import warnings

View file

@ -24,7 +24,6 @@ from beets.library import Item, Album, parse_query_string
from beets.dbcore import OrQuery from beets.dbcore import OrQuery
from beets.dbcore.query import MultipleSort, ParsingError from beets.dbcore.query import MultipleSort, ParsingError
import os import os
import six
try: try:
from urllib.request import pathname2url from urllib.request import pathname2url
@ -72,8 +71,8 @@ class SmartPlaylistPlugin(BeetsPlugin):
args.add(f"{a}.m3u") args.add(f"{a}.m3u")
playlists = {(name, q, a_q) playlists = {(name, q, a_q)
for name, q, a_q in self._unmatched_playlists for name, q, a_q in self._unmatched_playlists
if name in args} if name in args}
if not playlists: if not playlists:
raise ui.UserError( raise ui.UserError(
'No playlist matching any of {} found'.format( 'No playlist matching any of {} found'.format(

View file

@ -22,7 +22,6 @@ import base64
import webbrowser import webbrowser
import collections import collections
import six
import unidecode import unidecode
import requests import requests
import confuse import confuse

View file

@ -43,8 +43,8 @@ def filter_to_be_removed(items, keys):
def to_be_removed(item): def to_be_removed(item):
for artist, album, title in keys: for artist, album, title in keys:
if artist == item['artist'] and\ if artist == item['artist'] and\
album == item['album'] and\ album == item['album'] and\
title == item['title']: title == item['title']:
return False return False
return True return True

View file

@ -33,7 +33,6 @@ from beets.plugins import BeetsPlugin
from beets.ui import Subcommand, decargs from beets.ui import Subcommand, decargs
from beets import util from beets import util
from beets.util.artresizer import ArtResizer, get_im_version, get_pil_version from beets.util.artresizer import ArtResizer, get_im_version, get_pil_version
import six
BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails") BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails")

View file

@ -42,7 +42,7 @@ class Unimported(BeetsPlugin):
in self.config['ignore_extensions'].as_str_seq()] in self.config['ignore_extensions'].as_str_seq()]
in_folder = { in_folder = {
os.path.join(r, file) for r, d, f in os.walk(lib.directory) os.path.join(r, file) for r, d, f in os.walk(lib.directory)
for file in f if not any( for file in f if not any(
[file.endswith(extension) for extension in [file.endswith(extension) for extension in
ignore_exts])} ignore_exts])}
in_library = {x.path for x in lib.items()} in_library = {x.path for x in lib.items()}

View file

@ -14,7 +14,6 @@
""" Clears tag fields in media files.""" """ Clears tag fields in media files."""
import six
import re import re

View file

@ -85,7 +85,6 @@ setup(
}, },
install_requires=[ install_requires=[
'six>=1.9',
'unidecode', 'unidecode',
'musicbrainzngs>=0.4', 'musicbrainzngs>=0.4',
'pyyaml', 'pyyaml',

View file

@ -1,2 +1 @@
# Make python -m testall.py work. # Make python -m testall.py work.

View file

@ -30,7 +30,6 @@ information or mock the environment.
""" """
import sys import sys
import os import os
import os.path import os.path
@ -54,7 +53,6 @@ from beets.util import MoveOperation
# TODO Move AutotagMock here # TODO Move AutotagMock here
from test import _common from test import _common
import six
class LogCapture(logging.Handler): class LogCapture(logging.Handler):
@ -578,6 +576,7 @@ def generate_album_info(album_id, track_values):
return album return album
ALBUM_INFO_FIELDS = ['album', 'album_id', 'artist', 'artist_id', ALBUM_INFO_FIELDS = ['album', 'album_id', 'artist', 'artist_id',
'asin', 'albumtype', 'va', 'label', 'asin', 'albumtype', 'va', 'label',
'artist_sort', 'releasegroup_id', 'catalognum', 'artist_sort', 'releasegroup_id', 'catalognum',
@ -602,6 +601,7 @@ def generate_track_info(track_id='track info', values={}):
setattr(track, field, value) setattr(track, field, value)
return track return track
TRACK_INFO_FIELDS = ['artist', 'artist_id', 'artist_sort', TRACK_INFO_FIELDS = ['artist', 'artist_id', 'artist_sort',
'disctitle', 'artist_credit', 'data_source', 'disctitle', 'artist_credit', 'data_source',
'data_url'] 'data_url']

View file

@ -15,7 +15,6 @@
"""Tests for image resizing based on filesize.""" """Tests for image resizing based on filesize."""
import unittest import unittest
import os import os

View file

@ -18,7 +18,6 @@
import unittest import unittest
from test import _common from test import _common
from test.helper import TestHelper from test.helper import TestHelper
import six
from datetime import timedelta from datetime import timedelta
from beetsplug import beatport from beetsplug import beatport

View file

@ -10,7 +10,6 @@ from beets import config
from test.helper import TestHelper from test.helper import TestHelper
from beets.library import Library from beets.library import Library
import six
class ConfigCommandTest(unittest.TestCase, TestHelper): class ConfigCommandTest(unittest.TestCase, TestHelper):

View file

@ -49,7 +49,7 @@ class TestHelper(helper.TestHelper):
# A Python script that copies the file and appends a tag. # A Python script that copies the file and appends a tag.
stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8') stub = os.path.join(_common.RSRC, b'convert_stub.py').decode('utf-8')
return "{} {} $source $dest {}".format(shell_quote(sys.executable), return "{} {} $source $dest {}".format(shell_quote(sys.executable),
shell_quote(stub), tag) shell_quote(stub), tag)
def assertFileTag(self, path, tag): # noqa 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`.
@ -135,6 +135,7 @@ class ConvertCommand:
"""A mixin providing a utility method to run the `convert`command """A mixin providing a utility method to run the `convert`command
in tests. in tests.
""" """
def run_convert_path(self, path, *args): def run_convert_path(self, path, *args):
"""Run the `convert` command on a given path.""" """Run the `convert` command on a given path."""
# The path is currently a filesystem bytestring. Convert it to # The path is currently a filesystem bytestring. Convert it to

View file

@ -19,12 +19,10 @@ import os
import shutil import shutil
import sqlite3 import sqlite3
import unittest import unittest
from six import assertRaisesRegex
from test import _common from test import _common
from beets import dbcore from beets import dbcore
from tempfile import mkstemp from tempfile import mkstemp
import six
# Fixture: concrete database and model classes. For migration tests, we # Fixture: concrete database and model classes. For migration tests, we

View file

@ -112,7 +112,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
album = self.lib.albums().get() album = self.lib.albums().get()
album_added_before = album.added album_added_before = album.added
items_added_before = {item.path: item.added items_added_before = {item.path: item.added
for item in album.items()} for item in album.items()}
# Newer Item path mtimes as if Beets had modified them # Newer Item path mtimes as if Beets had modified them
modify_mtimes(items_added_before.keys(), offset=10000) modify_mtimes(items_added_before.keys(), offset=10000)
# Reimport # Reimport
@ -122,7 +122,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
album = self.lib.albums().get() album = self.lib.albums().get()
self.assertEqualTimes(album.added, album_added_before) self.assertEqualTimes(album.added, album_added_before)
items_added_after = {item.path: item.added items_added_after = {item.path: item.added
for item in album.items()} for item in album.items()}
for item_path, added_after in items_added_after.items(): for item_path, added_after in items_added_after.items():
self.assertEqualTimes(items_added_before[item_path], added_after, self.assertEqualTimes(items_added_before[item_path], added_after,
"reimport modified Item.added for " + "reimport modified Item.added for " +
@ -151,7 +151,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
# Import and record the original added dates # Import and record the original added dates
self.importer.run() self.importer.run()
items_added_before = {item.path: item.added items_added_before = {item.path: item.added
for item in self.lib.items()} for item in self.lib.items()}
# Newer Item path mtimes as if Beets had modified them # Newer Item path mtimes as if Beets had modified them
modify_mtimes(items_added_before.keys(), offset=10000) modify_mtimes(items_added_before.keys(), offset=10000)
# Reimport # Reimport
@ -160,7 +160,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
self.importer.run() self.importer.run()
# Verify the reimported items # Verify the reimported items
items_added_after = {item.path: item.added items_added_after = {item.path: item.added
for item in self.lib.items()} for item in self.lib.items()}
for item_path, added_after in items_added_after.items(): for item_path, added_after in items_added_after.items():
self.assertEqualTimes(items_added_before[item_path], added_after, self.assertEqualTimes(items_added_before[item_path], added_after,
"reimport modified Item.added for " + "reimport modified Item.added for " +
@ -170,5 +170,6 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
def suite(): def suite():
return unittest.TestLoader().loadTestsFromName(__name__) return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main(defaultTest='suite') unittest.main(defaultTest='suite')

View file

@ -52,7 +52,7 @@ class IPFSPluginTest(unittest.TestCase, TestHelper):
_fsencoding(), _fsencoding(),
) )
want_path = '/ipfs/{}/{}'.format(test_album.ipfs, want_path = '/ipfs/{}/{}'.format(test_album.ipfs,
ipfs_item) ipfs_item)
want_path = bytestring_path(want_path) want_path = bytestring_path(want_path)
self.assertEqual(check_item.path, want_path) self.assertEqual(check_item.path, want_path)
self.assertEqual(check_item.get('ipfs', with_album=False), self.assertEqual(check_item.get('ipfs', with_album=False),
@ -95,5 +95,6 @@ class IPFSPluginTest(unittest.TestCase, TestHelper):
def suite(): def suite():
return unittest.TestLoader().loadTestsFromName(__name__) return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main(defaultTest='suite') unittest.main(defaultTest='suite')

View file

@ -23,7 +23,6 @@ from beetsplug import lastgenre
from beets import config from beets import config
from test.helper import TestHelper from test.helper import TestHelper
import six
class LastGenrePluginTest(unittest.TestCase, TestHelper): class LastGenrePluginTest(unittest.TestCase, TestHelper):

View file

@ -35,7 +35,6 @@ from beets import config
from mediafile import MediaFile, UnreadableFileError from mediafile import MediaFile, UnreadableFileError
from beets.util import syspath, bytestring_path from beets.util import syspath, bytestring_path
from test.helper import TestHelper from test.helper import TestHelper
import six
# Shortcut to path normalization. # Shortcut to path normalization.
np = util.normpath np = util.normpath

View file

@ -12,7 +12,6 @@ import beetsplug
from test import _common from test import _common
from test._common import TestCase from test._common import TestCase
from test import helper from test import helper
import six
class LoggingTest(TestCase): class LoggingTest(TestCase):

View file

@ -18,7 +18,6 @@
import itertools import itertools
import os import os
import re import re
import six
import sys import sys
import unittest import unittest

View file

@ -12,13 +12,13 @@
# The above copyright notice and this permission notice shall be # The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software. # included in all copies or substantial portions of the Software.
from six.moves import shlex_quote
import os import os
import shutil import shutil
import tempfile import tempfile
import unittest import unittest
from shlex import quote
from test import _common from test import _common
from test import helper from test import helper
@ -88,7 +88,7 @@ class PlaylistQueryTestHelper(PlaylistTestHelper):
}) })
def test_path_query_with_absolute_paths_in_playlist(self): def test_path_query_with_absolute_paths_in_playlist(self):
q = 'playlist:{}'.format(shlex_quote(os.path.join( q = 'playlist:{}'.format(quote(os.path.join(
self.playlist_dir, self.playlist_dir,
'absolute.m3u', 'absolute.m3u',
))) )))
@ -107,7 +107,7 @@ class PlaylistQueryTestHelper(PlaylistTestHelper):
}) })
def test_path_query_with_relative_paths_in_playlist(self): def test_path_query_with_relative_paths_in_playlist(self):
q = 'playlist:{}'.format(shlex_quote(os.path.join( q = 'playlist:{}'.format(quote(os.path.join(
self.playlist_dir, self.playlist_dir,
'relative.m3u', 'relative.m3u',
))) )))
@ -123,7 +123,7 @@ class PlaylistQueryTestHelper(PlaylistTestHelper):
self.assertEqual(set(results), set()) self.assertEqual(set(results), set())
def test_path_query_with_nonexisting_playlist(self): def test_path_query_with_nonexisting_playlist(self):
q = 'playlist:{}'.format(shlex_quote(os.path.join( q = 'playlist:{}'.format(quote(os.path.join(
self.playlist_dir, self.playlist_dir,
self.playlist_dir, self.playlist_dir,
'nonexisting.m3u', 'nonexisting.m3u',
@ -218,7 +218,7 @@ class PlaylistUpdateTestHelper(PlaylistTestHelper):
class PlaylistTestItemMoved(PlaylistUpdateTestHelper, unittest.TestCase): class PlaylistTestItemMoved(PlaylistUpdateTestHelper, unittest.TestCase):
def test_item_moved(self): def test_item_moved(self):
# Emit item_moved event for an item that is in a playlist # Emit item_moved event for an item that is in a playlist
results = self.lib.items('path:{}'.format(shlex_quote( results = self.lib.items('path:{}'.format(quote(
os.path.join(self.music_dir, 'd', 'e', 'f.mp3')))) os.path.join(self.music_dir, 'd', 'e', 'f.mp3'))))
item = results[0] item = results[0]
beets.plugins.send( beets.plugins.send(
@ -227,7 +227,7 @@ class PlaylistTestItemMoved(PlaylistUpdateTestHelper, unittest.TestCase):
os.path.join(self.music_dir, 'g', 'h', 'i.mp3'))) os.path.join(self.music_dir, 'g', 'h', 'i.mp3')))
# Emit item_moved event for an item that is not in a playlist # Emit item_moved event for an item that is not in a playlist
results = self.lib.items('path:{}'.format(shlex_quote( results = self.lib.items('path:{}'.format(quote(
os.path.join(self.music_dir, 'x', 'y', 'z.mp3')))) os.path.join(self.music_dir, 'x', 'y', 'z.mp3'))))
item = results[0] item = results[0]
beets.plugins.send( beets.plugins.send(
@ -264,13 +264,13 @@ class PlaylistTestItemMoved(PlaylistUpdateTestHelper, unittest.TestCase):
class PlaylistTestItemRemoved(PlaylistUpdateTestHelper, unittest.TestCase): class PlaylistTestItemRemoved(PlaylistUpdateTestHelper, unittest.TestCase):
def test_item_removed(self): def test_item_removed(self):
# Emit item_removed event for an item that is in a playlist # Emit item_removed event for an item that is in a playlist
results = self.lib.items('path:{}'.format(shlex_quote( results = self.lib.items('path:{}'.format(quote(
os.path.join(self.music_dir, 'd', 'e', 'f.mp3')))) os.path.join(self.music_dir, 'd', 'e', 'f.mp3'))))
item = results[0] item = results[0]
beets.plugins.send('item_removed', item=item) beets.plugins.send('item_removed', item=item)
# Emit item_removed event for an item that is not in a playlist # Emit item_removed event for an item that is not in a playlist
results = self.lib.items('path:{}'.format(shlex_quote( results = self.lib.items('path:{}'.format(quote(
os.path.join(self.music_dir, 'x', 'y', 'z.mp3')))) os.path.join(self.music_dir, 'x', 'y', 'z.mp3'))))
item = results[0] item = results[0]
beets.plugins.send('item_removed', item=item) beets.plugins.send('item_removed', item=item)
@ -302,5 +302,6 @@ class PlaylistTestItemRemoved(PlaylistUpdateTestHelper, unittest.TestCase):
def suite(): def suite():
return unittest.TestLoader().loadTestsFromName(__name__) return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main(defaultTest='suite') unittest.main(defaultTest='suite')

View file

@ -16,7 +16,6 @@
""" """
import os import os
import six
import shutil import shutil
import unittest import unittest

View file

@ -32,7 +32,6 @@ from beets.dbcore.query import (NoneQuery, ParsingError,
from beets.library import Library, Item from beets.library import Library, Item
from beets import util from beets import util
import platform import platform
import six
class TestHelper(helper.TestHelper): class TestHelper(helper.TestHelper):

View file

@ -13,8 +13,6 @@
# included in all copies or substantial portions of the Software. # included in all copies or substantial portions of the Software.
import six
import unittest import unittest
from mediafile import MediaFile from mediafile import MediaFile
@ -214,5 +212,6 @@ class ReplayGainFfmpegTest(ReplayGainCliTestBase, unittest.TestCase):
def suite(): def suite():
return unittest.TestLoader().loadTestsFromName(__name__) return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main(defaultTest='suite') unittest.main(defaultTest='suite')

View file

@ -83,7 +83,7 @@ class SmartPlaylistTest(unittest.TestCase):
spl.build_queries() spl.build_queries()
sorts = {name: sort sorts = {name: sort
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
sort = FixedFieldSort # short cut since we're only dealing with this sort = FixedFieldSort # short cut since we're only dealing with this

View file

@ -8,11 +8,12 @@ from test import _common
from beets import config from beets import config
from beetsplug import subsonicupdate from beetsplug import subsonicupdate
from test.helper import TestHelper from test.helper import TestHelper
from six.moves.urllib.parse import parse_qs, urlparse from urllib.parse import parse_qs, urlparse
class ArgumentsMock: class ArgumentsMock:
"""Argument mocks for tests.""" """Argument mocks for tests."""
def __init__(self, mode, show_failures): def __init__(self, mode, show_failures):
"""Constructs ArgumentsMock.""" """Constructs ArgumentsMock."""
self.mode = mode self.mode = mode

View file

@ -16,7 +16,6 @@
""" """
import unittest import unittest
import six
from beets.util import functemplate from beets.util import functemplate

View file

@ -25,7 +25,6 @@ from test import test_importer
from beets.ui.commands import TerminalImportSession from beets.ui.commands import TerminalImportSession
from beets import importer from beets import importer
from beets import config from beets import config
import six
class TerminalImportSessionFixture(TerminalImportSession): class TerminalImportSessionFixture(TerminalImportSession):

View file

@ -24,7 +24,6 @@ from unittest.mock import patch, Mock
from test import _common from test import _common
from beets import util from beets import util
import six
class UtilTest(unittest.TestCase): class UtilTest(unittest.TestCase):

View file

@ -4,7 +4,6 @@
import json import json
import unittest import unittest
import os.path import os.path
from six import assertCountEqual
import shutil import shutil
from test import _common from test import _common
@ -672,5 +671,6 @@ class WebPluginTest(_common.LibTestCase):
def suite(): def suite():
return unittest.TestLoader().loadTestsFromName(__name__) return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main(defaultTest='suite') unittest.main(defaultTest='suite')