autopep8: Add space after class signature/docstring

This commit is contained in:
Stein Magnus Jodal 2015-04-03 00:05:26 +02:00
parent 83c3d0013f
commit c4940cbea2
99 changed files with 252 additions and 0 deletions

View File

@ -15,6 +15,7 @@ sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + '/../'))
class Mock(object): class Mock(object):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
pass pass

View File

@ -55,7 +55,9 @@ PLAYBIN_FLAGS = (1 << 1) | (1 << 4)
class _Signals(object): class _Signals(object):
"""Helper for tracking gobject signal registrations""" """Helper for tracking gobject signal registrations"""
def __init__(self): def __init__(self):
self._ids = {} self._ids = {}
@ -84,7 +86,9 @@ class _Signals(object):
# TODO: expose this as a property on audio? # TODO: expose this as a property on audio?
class _Appsrc(object): class _Appsrc(object):
"""Helper class for dealing with appsrc based playback.""" """Helper class for dealing with appsrc based playback."""
def __init__(self): def __init__(self):
self._signals = _Signals() self._signals = _Signals()
self.reset() self.reset()
@ -151,6 +155,7 @@ class _Appsrc(object):
# TODO: expose this as a property on audio when #790 gets further along. # TODO: expose this as a property on audio when #790 gets further along.
class _Outputs(gst.Bin): class _Outputs(gst.Bin):
def __init__(self): def __init__(self):
gst.Bin.__init__(self) gst.Bin.__init__(self)
@ -250,6 +255,7 @@ class SoftwareMixer(object):
class _Handler(object): class _Handler(object):
def __init__(self, audio): def __init__(self, audio):
self._audio = audio self._audio = audio
self._element = None self._element = None
@ -418,6 +424,7 @@ class _Handler(object):
# TODO: create a player class which replaces the actors internals # TODO: create a player class which replaces the actors internals
class Audio(pykka.ThreadingActor): class Audio(pykka.ThreadingActor):
""" """
Audio output through `GStreamer <http://gstreamer.freedesktop.org/>`_. Audio output through `GStreamer <http://gstreamer.freedesktop.org/>`_.
""" """

View File

@ -2,6 +2,7 @@ from __future__ import absolute_import, unicode_literals
class PlaybackState(object): class PlaybackState(object):
""" """
Enum of playback states. Enum of playback states.
""" """

View File

@ -4,6 +4,7 @@ from mopidy import listener
class AudioListener(listener.Listener): class AudioListener(listener.Listener):
""" """
Marker interface for recipients of events sent by the audio actor. Marker interface for recipients of events sent by the audio actor.

View File

@ -136,6 +136,7 @@ def register_typefinders():
class BasePlaylistElement(gst.Bin): class BasePlaylistElement(gst.Bin):
"""Base class for creating GStreamer elements for playlist support. """Base class for creating GStreamer elements for playlist support.
This element performs the following steps: This element performs the following steps:

View File

@ -21,6 +21,7 @@ _RAW_AUDIO = gst.Caps(b'audio/x-raw-int; audio/x-raw-float')
# TODO: replace with a scan(uri, timeout=1000, proxy_config=None)? # TODO: replace with a scan(uri, timeout=1000, proxy_config=None)?
class Scanner(object): class Scanner(object):
""" """
Helper to get tags and other relevant info from URIs. Helper to get tags and other relevant info from URIs.

View File

@ -4,6 +4,7 @@ from mopidy import listener, models
class Backend(object): class Backend(object):
"""Backend API """Backend API
If the backend has problems during initialization it should raise If the backend has problems during initialization it should raise
@ -59,6 +60,7 @@ class Backend(object):
class LibraryProvider(object): class LibraryProvider(object):
""" """
:param backend: backend the controller is a part of :param backend: backend the controller is a part of
:type backend: :class:`mopidy.backend.Backend` :type backend: :class:`mopidy.backend.Backend`
@ -148,6 +150,7 @@ class LibraryProvider(object):
class PlaybackProvider(object): class PlaybackProvider(object):
""" """
:param audio: the audio actor :param audio: the audio actor
:type audio: actor proxy to an instance of :class:`mopidy.audio.Audio` :type audio: actor proxy to an instance of :class:`mopidy.audio.Audio`
@ -280,6 +283,7 @@ class PlaybackProvider(object):
class PlaylistsProvider(object): class PlaylistsProvider(object):
""" """
A playlist provider exposes a collection of playlists, methods to A playlist provider exposes a collection of playlists, methods to
create/change/delete playlists in this collection, and lookup of any create/change/delete playlists in this collection, and lookup of any
@ -391,6 +395,7 @@ class PlaylistsProvider(object):
class BackendListener(listener.Listener): class BackendListener(listener.Listener):
""" """
Marker interface for recipients of events sent by the backend actors. Marker interface for recipients of events sent by the backend actors.

View File

@ -38,6 +38,7 @@ def config_override_type(value):
class _ParserError(Exception): class _ParserError(Exception):
def __init__(self, message): def __init__(self, message):
self.message = message self.message = message
@ -47,11 +48,13 @@ class _HelpError(Exception):
class _ArgumentParser(argparse.ArgumentParser): class _ArgumentParser(argparse.ArgumentParser):
def error(self, message): def error(self, message):
raise _ParserError(message) raise _ParserError(message)
class _HelpAction(argparse.Action): class _HelpAction(argparse.Action):
def __init__(self, option_strings, dest=None, help=None): def __init__(self, option_strings, dest=None, help=None):
super(_HelpAction, self).__init__( super(_HelpAction, self).__init__(
option_strings=option_strings, option_strings=option_strings,
@ -65,6 +68,7 @@ class _HelpAction(argparse.Action):
class Command(object): class Command(object):
"""Command parser and runner for building trees of commands. """Command parser and runner for building trees of commands.
This class provides a wraper around :class:`argparse.ArgumentParser` This class provides a wraper around :class:`argparse.ArgumentParser`
@ -227,6 +231,7 @@ class Command(object):
class RootCommand(Command): class RootCommand(Command):
def __init__(self): def __init__(self):
super(RootCommand, self).__init__() super(RootCommand, self).__init__()
self.set(base_verbosity_level=0) self.set(base_verbosity_level=0)

View File

@ -264,6 +264,7 @@ def _postprocess(config_string):
class Proxy(collections.Mapping): class Proxy(collections.Mapping):
def __init__(self, data): def __init__(self, data):
self._data = data self._data = data

View File

@ -38,6 +38,7 @@ def _levenshtein(a, b):
class ConfigSchema(collections.OrderedDict): class ConfigSchema(collections.OrderedDict):
"""Logical group of config values that correspond to a config section. """Logical group of config values that correspond to a config section.
Schemas are set up by assigning config keys with config values to Schemas are set up by assigning config keys with config values to
@ -47,6 +48,7 @@ class ConfigSchema(collections.OrderedDict):
:meth:`serialize` for converting the values to a form suitable for :meth:`serialize` for converting the values to a form suitable for
persistence. persistence.
""" """
def __init__(self, name): def __init__(self, name):
super(ConfigSchema, self).__init__() super(ConfigSchema, self).__init__()
self.name = name self.name = name
@ -95,6 +97,7 @@ class ConfigSchema(collections.OrderedDict):
class MapConfigSchema(object): class MapConfigSchema(object):
"""Schema for handling multiple unknown keys with the same type. """Schema for handling multiple unknown keys with the same type.
Does not sub-class :class:`ConfigSchema`, but implements the same Does not sub-class :class:`ConfigSchema`, but implements the same

View File

@ -25,6 +25,7 @@ def encode(value):
class ExpandedPath(bytes): class ExpandedPath(bytes):
def __new__(cls, original, expanded): def __new__(cls, original, expanded):
return super(ExpandedPath, cls).__new__(cls, expanded) return super(ExpandedPath, cls).__new__(cls, expanded)
@ -37,6 +38,7 @@ class DeprecatedValue(object):
class ConfigValue(object): class ConfigValue(object):
"""Represents a config key's value and how to handle it. """Represents a config key's value and how to handle it.
Normally you will only be interacting with sub-classes for config values Normally you will only be interacting with sub-classes for config values
@ -65,6 +67,7 @@ class ConfigValue(object):
class Deprecated(ConfigValue): class Deprecated(ConfigValue):
"""Deprecated value """Deprecated value
Used for ignoring old config values that are no longer in use, but should Used for ignoring old config values that are no longer in use, but should
@ -79,10 +82,12 @@ class Deprecated(ConfigValue):
class String(ConfigValue): class String(ConfigValue):
"""String value. """String value.
Is decoded as utf-8 and \\n \\t escapes should work and be preserved. Is decoded as utf-8 and \\n \\t escapes should work and be preserved.
""" """
def __init__(self, optional=False, choices=None): def __init__(self, optional=False, choices=None):
self._required = not optional self._required = not optional
self._choices = choices self._choices = choices
@ -102,6 +107,7 @@ class String(ConfigValue):
class Secret(String): class Secret(String):
"""Secret string value. """Secret string value.
Is decoded as utf-8 and \\n \\t escapes should work and be preserved. Is decoded as utf-8 and \\n \\t escapes should work and be preserved.
@ -109,6 +115,7 @@ class Secret(String):
Should be used for passwords, auth tokens etc. Will mask value when being Should be used for passwords, auth tokens etc. Will mask value when being
displayed. displayed.
""" """
def __init__(self, optional=False, choices=None): def __init__(self, optional=False, choices=None):
self._required = not optional self._required = not optional
self._choices = None # Choices doesn't make sense for secrets self._choices = None # Choices doesn't make sense for secrets
@ -120,6 +127,7 @@ class Secret(String):
class Integer(ConfigValue): class Integer(ConfigValue):
"""Integer value.""" """Integer value."""
def __init__( def __init__(
@ -141,6 +149,7 @@ class Integer(ConfigValue):
class Boolean(ConfigValue): class Boolean(ConfigValue):
"""Boolean value. """Boolean value.
Accepts ``1``, ``yes``, ``true``, and ``on`` with any casing as Accepts ``1``, ``yes``, ``true``, and ``on`` with any casing as
@ -173,11 +182,13 @@ class Boolean(ConfigValue):
class List(ConfigValue): class List(ConfigValue):
"""List value. """List value.
Supports elements split by commas or newlines. Newlines take presedence and Supports elements split by commas or newlines. Newlines take presedence and
empty list items will be filtered out. empty list items will be filtered out.
""" """
def __init__(self, optional=False): def __init__(self, optional=False):
self._required = not optional self._required = not optional
@ -198,6 +209,7 @@ class List(ConfigValue):
class LogColor(ConfigValue): class LogColor(ConfigValue):
def deserialize(self, value): def deserialize(self, value):
validators.validate_choice(value.lower(), log.COLORS) validators.validate_choice(value.lower(), log.COLORS)
return value.lower() return value.lower()
@ -209,6 +221,7 @@ class LogColor(ConfigValue):
class LogLevel(ConfigValue): class LogLevel(ConfigValue):
"""Log level value. """Log level value.
Expects one of ``critical``, ``error``, ``warning``, ``info``, ``debug``, Expects one of ``critical``, ``error``, ``warning``, ``info``, ``debug``,
@ -235,6 +248,7 @@ class LogLevel(ConfigValue):
class Hostname(ConfigValue): class Hostname(ConfigValue):
"""Network hostname value.""" """Network hostname value."""
def __init__(self, optional=False): def __init__(self, optional=False):
@ -252,18 +266,21 @@ class Hostname(ConfigValue):
class Port(Integer): class Port(Integer):
"""Network port value. """Network port value.
Expects integer in the range 0-65535, zero tells the kernel to simply Expects integer in the range 0-65535, zero tells the kernel to simply
allocate a port for us. allocate a port for us.
""" """
# TODO: consider probing if port is free or not? # TODO: consider probing if port is free or not?
def __init__(self, choices=None, optional=False): def __init__(self, choices=None, optional=False):
super(Port, self).__init__( super(Port, self).__init__(
minimum=0, maximum=2 ** 16 - 1, choices=choices, optional=optional) minimum=0, maximum=2 ** 16 - 1, choices=choices, optional=optional)
class Path(ConfigValue): class Path(ConfigValue):
"""File system path """File system path
The following expansions of the path will be done: The following expansions of the path will be done:
@ -278,6 +295,7 @@ class Path(ConfigValue):
- ``$XDG_MUSIC_DIR`` according to the XDG spec - ``$XDG_MUSIC_DIR`` according to the XDG spec
""" """
def __init__(self, optional=False): def __init__(self, optional=False):
self._required = not optional self._required = not optional

View File

@ -134,6 +134,7 @@ class Core(
class Backends(list): class Backends(list):
def __init__(self, backends): def __init__(self, backends):
super(Backends, self).__init__(backends) super(Backends, self).__init__(backends)

View File

@ -4,6 +4,7 @@ from mopidy import listener
class CoreListener(listener.Listener): class CoreListener(listener.Listener):
""" """
Marker interface for recipients of events sent by the core actor. Marker interface for recipients of events sent by the core actor.

View File

@ -2,6 +2,7 @@ from __future__ import absolute_import, unicode_literals
class MopidyException(Exception): class MopidyException(Exception):
def __init__(self, message, *args, **kwargs): def __init__(self, message, *args, **kwargs):
super(MopidyException, self).__init__(message, *args, **kwargs) super(MopidyException, self).__init__(message, *args, **kwargs)
self._message = message self._message = message
@ -25,6 +26,7 @@ class ExtensionError(MopidyException):
class FindError(MopidyException): class FindError(MopidyException):
def __init__(self, message, errno=None): def __init__(self, message, errno=None):
super(FindError, self).__init__(message, errno) super(FindError, self).__init__(message, errno)
self.errno = errno self.errno = errno

View File

@ -12,6 +12,7 @@ logger = logging.getLogger(__name__)
class Extension(object): class Extension(object):
"""Base class for Mopidy extensions""" """Base class for Mopidy extensions"""
dist_name = None dist_name = None
@ -104,6 +105,7 @@ class Extension(object):
class Registry(collections.Mapping): class Registry(collections.Mapping):
"""Registry of components provided by Mopidy extensions. """Registry of components provided by Mopidy extensions.
Passed to the :meth:`~Extension.setup` method of all extensions. The Passed to the :meth:`~Extension.setup` method of all extensions. The

View File

@ -142,6 +142,7 @@ def set_mopidy_headers(request_handler):
class JsonRpcHandler(tornado.web.RequestHandler): class JsonRpcHandler(tornado.web.RequestHandler):
def initialize(self, core): def initialize(self, core):
self.jsonrpc = make_jsonrpc_wrapper(core) self.jsonrpc = make_jsonrpc_wrapper(core)
@ -176,6 +177,7 @@ class JsonRpcHandler(tornado.web.RequestHandler):
class ClientListHandler(tornado.web.RequestHandler): class ClientListHandler(tornado.web.RequestHandler):
def initialize(self, apps, statics): def initialize(self, apps, statics):
self.apps = apps self.apps = apps
self.statics = statics self.statics = statics
@ -197,6 +199,7 @@ class ClientListHandler(tornado.web.RequestHandler):
class StaticFileHandler(tornado.web.StaticFileHandler): class StaticFileHandler(tornado.web.StaticFileHandler):
def set_extra_headers(self, path): def set_extra_headers(self, path):
set_mopidy_headers(self) set_mopidy_headers(self)

View File

@ -35,6 +35,7 @@ def send(cls, event, **kwargs):
class Listener(object): class Listener(object):
def on_event(self, event, **kwargs): def on_event(self, event, **kwargs):
""" """
Called on all events. Called on all events.

View File

@ -48,6 +48,7 @@ class Extension(ext.Extension):
class Library(object): class Library(object):
""" """
Local library interface. Local library interface.

View File

@ -29,6 +29,7 @@ def _get_library(args, config):
class LocalCommand(commands.Command): class LocalCommand(commands.Command):
def __init__(self): def __init__(self):
super(LocalCommand, self).__init__() super(LocalCommand, self).__init__()
self.add_child('scan', ScanCommand()) self.add_child('scan', ScanCommand())
@ -162,6 +163,7 @@ class ScanCommand(commands.Command):
class _Progress(object): class _Progress(object):
def __init__(self, batch_size, total): def __init__(self, batch_size, total):
self.count = 0 self.count = 0
self.batch_size = batch_size self.batch_size = batch_size

View File

@ -8,6 +8,7 @@ logger = logging.getLogger(__name__)
class LocalLibraryProvider(backend.LibraryProvider): class LocalLibraryProvider(backend.LibraryProvider):
"""Proxy library that delegates work to our active local library.""" """Proxy library that delegates work to our active local library."""
root_directory = models.Ref.directory( root_directory = models.Ref.directory(

View File

@ -5,6 +5,7 @@ from mopidy.local import translator
class LocalPlaybackProvider(backend.PlaybackProvider): class LocalPlaybackProvider(backend.PlaybackProvider):
def translate_uri(self, uri): def translate_uri(self, uri):
return translator.local_track_uri_to_file_uri( return translator.local_track_uri_to_file_uri(
uri, self.backend.config['local']['media_dir']) uri, self.backend.config['local']['media_dir'])

View File

@ -8,6 +8,7 @@ logger = logging.getLogger(__name__)
class M3ULibraryProvider(backend.LibraryProvider): class M3ULibraryProvider(backend.LibraryProvider):
"""Library for looking up M3U playlists.""" """Library for looking up M3U playlists."""
def __init__(self, backend): def __init__(self, backend):

View File

@ -9,6 +9,7 @@ logger = logging.getLogger(__name__)
class Mixer(object): class Mixer(object):
""" """
Audio mixer API Audio mixer API
@ -111,6 +112,7 @@ class Mixer(object):
class MixerListener(listener.Listener): class MixerListener(listener.Listener):
""" """
Marker interface for recipients of events sent by the mixer actor. Marker interface for recipients of events sent by the mixer actor.

View File

@ -4,6 +4,7 @@ import json
class ImmutableObject(object): class ImmutableObject(object):
""" """
Superclass for immutable objects whose fields can only be modified via the Superclass for immutable objects whose fields can only be modified via the
constructor. constructor.
@ -102,6 +103,7 @@ class ImmutableObject(object):
class ModelJSONEncoder(json.JSONEncoder): class ModelJSONEncoder(json.JSONEncoder):
""" """
Automatically serialize Mopidy models to JSON. Automatically serialize Mopidy models to JSON.
@ -112,6 +114,7 @@ class ModelJSONEncoder(json.JSONEncoder):
'{"a_track": {"__model__": "Track", "name": "name"}}' '{"a_track": {"__model__": "Track", "name": "name"}}'
""" """
def default(self, obj): def default(self, obj):
if isinstance(obj, ImmutableObject): if isinstance(obj, ImmutableObject):
return obj.serialize() return obj.serialize()
@ -143,6 +146,7 @@ def model_json_decoder(dct):
class Ref(ImmutableObject): class Ref(ImmutableObject):
""" """
Model to represent URI references with a human friendly name and type Model to represent URI references with a human friendly name and type
attached. This is intended for use a lightweight object "free" of metadata attached. This is intended for use a lightweight object "free" of metadata
@ -213,6 +217,7 @@ class Ref(ImmutableObject):
class Image(ImmutableObject): class Image(ImmutableObject):
""" """
:param string uri: URI of the image :param string uri: URI of the image
:param int width: Optional width of image or :class:`None` :param int width: Optional width of image or :class:`None`
@ -230,6 +235,7 @@ class Image(ImmutableObject):
class Artist(ImmutableObject): class Artist(ImmutableObject):
""" """
:param uri: artist URI :param uri: artist URI
:type uri: string :type uri: string
@ -250,6 +256,7 @@ class Artist(ImmutableObject):
class Album(ImmutableObject): class Album(ImmutableObject):
""" """
:param uri: album URI :param uri: album URI
:type uri: string :type uri: string
@ -303,6 +310,7 @@ class Album(ImmutableObject):
class Track(ImmutableObject): class Track(ImmutableObject):
""" """
:param uri: track URI :param uri: track URI
:type uri: string :type uri: string
@ -395,6 +403,7 @@ class Track(ImmutableObject):
class TlTrack(ImmutableObject): class TlTrack(ImmutableObject):
""" """
A tracklist track. Wraps a regular track and it's tracklist ID. A tracklist track. Wraps a regular track and it's tracklist ID.
@ -433,6 +442,7 @@ class TlTrack(ImmutableObject):
class Playlist(ImmutableObject): class Playlist(ImmutableObject):
""" """
:param uri: playlist URI :param uri: playlist URI
:type uri: string :type uri: string
@ -473,6 +483,7 @@ class Playlist(ImmutableObject):
class SearchResult(ImmutableObject): class SearchResult(ImmutableObject):
""" """
:param uri: search result URI :param uri: search result URI
:type uri: string :type uri: string

View File

@ -13,6 +13,7 @@ logger = logging.getLogger(__name__)
class MpdFrontend(pykka.ThreadingActor, CoreListener): class MpdFrontend(pykka.ThreadingActor, CoreListener):
def __init__(self, config, core): def __init__(self, config, core):
super(MpdFrontend, self).__init__() super(MpdFrontend, self).__init__()

View File

@ -13,6 +13,7 @@ protocol.load_protocol_modules()
class MpdDispatcher(object): class MpdDispatcher(object):
""" """
The MPD session feeds the MPD dispatcher with requests. The dispatcher The MPD session feeds the MPD dispatcher with requests. The dispatcher
finds the correct handler, processes the request and sends the response finds the correct handler, processes the request and sends the response
@ -209,6 +210,7 @@ class MpdDispatcher(object):
class MpdContext(object): class MpdContext(object):
""" """
This object is passed as the first argument to all MPD command handlers to This object is passed as the first argument to all MPD command handlers to
give the command handlers access to important parts of Mopidy. give the command handlers access to important parts of Mopidy.

View File

@ -4,6 +4,7 @@ from mopidy.exceptions import MopidyException
class MpdAckError(MopidyException): class MpdAckError(MopidyException):
"""See fields on this class for available MPD error codes""" """See fields on this class for available MPD error codes"""
ACK_ERROR_NOT_LIST = 1 ACK_ERROR_NOT_LIST = 1
@ -59,6 +60,7 @@ class MpdUnknownError(MpdAckError):
class MpdUnknownCommand(MpdUnknownError): class MpdUnknownCommand(MpdUnknownError):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(MpdUnknownCommand, self).__init__(*args, **kwargs) super(MpdUnknownCommand, self).__init__(*args, **kwargs)
assert self.command is not None, 'command must be given explicitly' assert self.command is not None, 'command must be given explicitly'
@ -67,6 +69,7 @@ class MpdUnknownCommand(MpdUnknownError):
class MpdNoCommand(MpdUnknownCommand): class MpdNoCommand(MpdUnknownCommand):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
kwargs['command'] = '' kwargs['command'] = ''
super(MpdNoCommand, self).__init__(*args, **kwargs) super(MpdNoCommand, self).__init__(*args, **kwargs)

View File

@ -83,6 +83,7 @@ def RANGE(value): # noqa: N802
class Commands(object): class Commands(object):
"""Collection of MPD commands to expose to users. """Collection of MPD commands to expose to users.
Normally used through the global instance which command handlers have been Normally used through the global instance which command handlers have been

View File

@ -9,6 +9,7 @@ logger = logging.getLogger(__name__)
class MpdSession(network.LineProtocol): class MpdSession(network.LineProtocol):
""" """
The MPD client session. Keeps track of a single client session. Any The MPD client session. Keeps track of a single client session. Any
requests from the client is passed on to the MPD request dispatcher. requests from the client is passed on to the MPD request dispatcher.

View File

@ -4,6 +4,7 @@ import re
class MpdUriMapper(object): class MpdUriMapper(object):
""" """
Maintains the mappings between uniquified MPD names and URIs. Maintains the mappings between uniquified MPD names and URIs.
""" """

View File

@ -15,6 +15,7 @@ logger = logging.getLogger(__name__)
class StreamBackend(pykka.ThreadingActor, backend.Backend): class StreamBackend(pykka.ThreadingActor, backend.Backend):
def __init__(self, config, audio): def __init__(self, config, audio):
super(StreamBackend, self).__init__() super(StreamBackend, self).__init__()
@ -30,6 +31,7 @@ class StreamBackend(pykka.ThreadingActor, backend.Backend):
class StreamLibraryProvider(backend.LibraryProvider): class StreamLibraryProvider(backend.LibraryProvider):
def __init__(self, backend, timeout, blacklist, proxy): def __init__(self, backend, timeout, blacklist, proxy):
super(StreamLibraryProvider, self).__init__(backend) super(StreamLibraryProvider, self).__init__(backend)
self._scanner = scan.Scanner(timeout=timeout, proxy_config=proxy) self._scanner = scan.Scanner(timeout=timeout, proxy_config=proxy)

View File

@ -10,6 +10,7 @@ from mopidy import compat
class JsonRpcWrapper(object): class JsonRpcWrapper(object):
""" """
Wrap objects and make them accessible through JSON-RPC 2.0 messaging. Wrap objects and make them accessible through JSON-RPC 2.0 messaging.
@ -278,6 +279,7 @@ def get_combined_json_decoder(decoders):
def get_combined_json_encoder(encoders): def get_combined_json_encoder(encoders):
class JsonRpcEncoder(json.JSONEncoder): class JsonRpcEncoder(json.JSONEncoder):
def default(self, obj): def default(self, obj):
for encoder in encoders: for encoder in encoders:
try: try:
@ -289,6 +291,7 @@ def get_combined_json_encoder(encoders):
class JsonRpcInspector(object): class JsonRpcInspector(object):
""" """
Inspects a group of classes and functions to create a description of what Inspects a group of classes and functions to create a description of what
methods they can expose over JSON-RPC 2.0. methods they can expose over JSON-RPC 2.0.

View File

@ -21,6 +21,7 @@ logging.addLevelName(TRACE_LOG_LEVEL, 'TRACE')
class DelayedHandler(logging.Handler): class DelayedHandler(logging.Handler):
def __init__(self): def __init__(self):
logging.Handler.__init__(self) logging.Handler.__init__(self)
self._released = False self._released = False
@ -101,6 +102,7 @@ def setup_debug_logging_to_file(config):
class VerbosityFilter(logging.Filter): class VerbosityFilter(logging.Filter):
def __init__(self, verbosity_level, loglevels): def __init__(self, verbosity_level, loglevels):
self.verbosity_level = verbosity_level self.verbosity_level = verbosity_level
self.loglevels = loglevels self.loglevels = loglevels
@ -123,6 +125,7 @@ COLORS = [b'black', b'red', b'green', b'yellow', b'blue', b'magenta', b'cyan',
class ColorizingStreamHandler(logging.StreamHandler): class ColorizingStreamHandler(logging.StreamHandler):
""" """
Stream handler which colorizes the log using ANSI escape sequences. Stream handler which colorizes the log using ANSI escape sequences.

View File

@ -18,6 +18,7 @@ logger = logging.getLogger(__name__)
class ShouldRetrySocketCall(Exception): class ShouldRetrySocketCall(Exception):
"""Indicate that attempted socket call should be retried""" """Indicate that attempted socket call should be retried"""
@ -65,6 +66,7 @@ def format_hostname(hostname):
class Server(object): class Server(object):
"""Setup listener and register it with gobject's event loop.""" """Setup listener and register it with gobject's event loop."""
def __init__(self, host, port, protocol, protocol_kwargs=None, def __init__(self, host, port, protocol, protocol_kwargs=None,
@ -305,6 +307,7 @@ class Connection(object):
class LineProtocol(pykka.ThreadingActor): class LineProtocol(pykka.ThreadingActor):
""" """
Base class for handling line based protocols. Base class for handling line based protocols.

View File

@ -227,6 +227,7 @@ def check_file_path_is_inside_base_dir(file_path, base_path):
# FIXME replace with mock usage in tests. # FIXME replace with mock usage in tests.
class Mtime(object): class Mtime(object):
def __init__(self): def __init__(self):
self.fake = None self.fake = None

View File

@ -53,6 +53,7 @@ def stop_remaining_actors():
class BaseThread(threading.Thread): class BaseThread(threading.Thread):
def __init__(self): def __init__(self):
super(BaseThread, self).__init__() super(BaseThread, self).__init__()
# No thread should block process from exiting # No thread should block process from exiting

View File

@ -31,6 +31,7 @@ def _convert_text_list_to_dbus_format(text_list):
class Zeroconf(object): class Zeroconf(object):
"""Publish a network service with Zeroconf. """Publish a network service with Zeroconf.
Currently, this only works on Linux using Avahi via D-Bus. Currently, this only works on Linux using Avahi via D-Bus.

View File

@ -15,6 +15,7 @@ def path_to_data_dir(name):
class IsA(object): class IsA(object):
def __init__(self, klass): def __init__(self, klass):
self.klass = klass self.klass = klass

View File

@ -79,6 +79,7 @@ class DummyMixin(object):
class AudioTest(BaseTest): class AudioTest(BaseTest):
def test_start_playback_existing_file(self): def test_start_playback_existing_file(self):
self.audio.prepare_change() self.audio.prepare_change()
self.audio.set_uri(self.uris[0]) self.audio.set_uri(self.uris[0])
@ -134,6 +135,7 @@ class AudioDummyTest(DummyMixin, AudioTest):
@mock.patch.object(audio.AudioListener, 'send') @mock.patch.object(audio.AudioListener, 'send')
class AudioEventTest(BaseTest): class AudioEventTest(BaseTest):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
super(AudioEventTest, self).setUp() super(AudioEventTest, self).setUp()
self.audio.enable_sync_handler().get() self.audio.enable_sync_handler().get()
@ -435,11 +437,13 @@ class AudioEventTest(BaseTest):
class AudioDummyEventTest(DummyMixin, AudioEventTest): class AudioDummyEventTest(DummyMixin, AudioEventTest):
"""Exercise the AudioEventTest against our mock audio classes.""" """Exercise the AudioEventTest against our mock audio classes."""
# TODO: move to mixer tests... # TODO: move to mixer tests...
class MixerTest(BaseTest): class MixerTest(BaseTest):
@unittest.SkipTest @unittest.SkipTest
def test_set_mute(self): def test_set_mute(self):
for value in (True, False): for value in (True, False):
@ -460,6 +464,7 @@ class MixerTest(BaseTest):
class AudioStateTest(unittest.TestCase): class AudioStateTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.audio = audio.Audio(config=None, mixer=None) self.audio = audio.Audio(config=None, mixer=None)
@ -505,6 +510,7 @@ class AudioStateTest(unittest.TestCase):
class AudioBufferingTest(unittest.TestCase): class AudioBufferingTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.audio = audio.Audio(config=None, mixer=None) self.audio = audio.Audio(config=None, mixer=None)
self.audio._playbin = mock.Mock(spec=['set_state']) self.audio._playbin = mock.Mock(spec=['set_state'])

View File

@ -8,6 +8,7 @@ from mopidy import audio
class AudioListenerTest(unittest.TestCase): class AudioListenerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.listener = audio.AudioListener() self.listener = audio.AudioListener()

View File

@ -78,6 +78,7 @@ XSPF = b"""<?xml version="1.0" encoding="UTF-8"?>
class TypeFind(object): class TypeFind(object):
def __init__(self, data): def __init__(self, data):
self.data = data self.data = data

View File

@ -14,6 +14,7 @@ from tests import path_to_data_dir
class ScannerTest(unittest.TestCase): class ScannerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.errors = {} self.errors = {}
self.tags = {} self.tags = {}

View File

@ -11,6 +11,7 @@ from mopidy.models import Album, Artist, Track
# TODO: current test is trying to test everything at once with a complete tags # TODO: current test is trying to test everything at once with a complete tags
# set, instead we might want to try with a minimal one making testing easier. # set, instead we might want to try with a minimal one making testing easier.
class TagsToTrackTest(unittest.TestCase): class TagsToTrackTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.tags = { self.tags = {
'album': ['album'], 'album': ['album'],

View File

@ -8,6 +8,7 @@ from mopidy import backend
class BackendListenerTest(unittest.TestCase): class BackendListenerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.listener = backend.BackendListener() self.listener = backend.BackendListener()

View File

@ -12,6 +12,7 @@ from tests import path_to_data_dir
class LoadConfigTest(unittest.TestCase): class LoadConfigTest(unittest.TestCase):
def test_load_nothing(self): def test_load_nothing(self):
self.assertEqual({}, config._load([], [], [])) self.assertEqual({}, config._load([], [], []))
@ -96,6 +97,7 @@ class LoadConfigTest(unittest.TestCase):
class ValidateTest(unittest.TestCase): class ValidateTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.schema = config.ConfigSchema('foo') self.schema = config.ConfigSchema('foo')
self.schema['bar'] = config.ConfigValue() self.schema['bar'] = config.ConfigValue()

View File

@ -11,6 +11,7 @@ from tests import any_unicode
class ConfigSchemaTest(unittest.TestCase): class ConfigSchemaTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.schema = schemas.ConfigSchema('test') self.schema = schemas.ConfigSchema('test')
self.schema['foo'] = mock.Mock() self.schema['foo'] = mock.Mock()
@ -87,6 +88,7 @@ class ConfigSchemaTest(unittest.TestCase):
class MapConfigSchemaTest(unittest.TestCase): class MapConfigSchemaTest(unittest.TestCase):
def test_conversion(self): def test_conversion(self):
schema = schemas.MapConfigSchema('test', types.LogLevel()) schema = schemas.MapConfigSchema('test', types.LogLevel())
result, errors = schema.deserialize( result, errors = schema.deserialize(
@ -97,6 +99,7 @@ class MapConfigSchemaTest(unittest.TestCase):
class DidYouMeanTest(unittest.TestCase): class DidYouMeanTest(unittest.TestCase):
def test_suggestions(self): def test_suggestions(self):
choices = ('enabled', 'username', 'password', 'bitrate', 'timeout') choices = ('enabled', 'username', 'password', 'bitrate', 'timeout')

View File

@ -15,6 +15,7 @@ from mopidy.config import types
class ConfigValueTest(unittest.TestCase): class ConfigValueTest(unittest.TestCase):
def test_deserialize_passes_through(self): def test_deserialize_passes_through(self):
value = types.ConfigValue() value = types.ConfigValue()
sentinel = object() sentinel = object()
@ -36,6 +37,7 @@ class ConfigValueTest(unittest.TestCase):
class DeprecatedTest(unittest.TestCase): class DeprecatedTest(unittest.TestCase):
def test_deserialize_returns_deprecated_value(self): def test_deserialize_returns_deprecated_value(self):
self.assertIsInstance(types.Deprecated().deserialize(b'foobar'), self.assertIsInstance(types.Deprecated().deserialize(b'foobar'),
types.DeprecatedValue) types.DeprecatedValue)
@ -46,6 +48,7 @@ class DeprecatedTest(unittest.TestCase):
class StringTest(unittest.TestCase): class StringTest(unittest.TestCase):
def test_deserialize_conversion_success(self): def test_deserialize_conversion_success(self):
value = types.String() value = types.String()
self.assertEqual('foo', value.deserialize(b' foo ')) self.assertEqual('foo', value.deserialize(b' foo '))
@ -117,6 +120,7 @@ class StringTest(unittest.TestCase):
class SecretTest(unittest.TestCase): class SecretTest(unittest.TestCase):
def test_deserialize_decodes_utf8(self): def test_deserialize_decodes_utf8(self):
value = types.Secret() value = types.Secret()
result = value.deserialize('æøå'.encode('utf-8')) result = value.deserialize('æøå'.encode('utf-8'))
@ -152,6 +156,7 @@ class SecretTest(unittest.TestCase):
class IntegerTest(unittest.TestCase): class IntegerTest(unittest.TestCase):
def test_deserialize_conversion_success(self): def test_deserialize_conversion_success(self):
value = types.Integer() value = types.Integer()
self.assertEqual(123, value.deserialize('123')) self.assertEqual(123, value.deserialize('123'))
@ -186,6 +191,7 @@ class IntegerTest(unittest.TestCase):
class BooleanTest(unittest.TestCase): class BooleanTest(unittest.TestCase):
def test_deserialize_conversion_success(self): def test_deserialize_conversion_success(self):
value = types.Boolean() value = types.Boolean()
for true in ('1', 'yes', 'true', 'on'): for true in ('1', 'yes', 'true', 'on'):
@ -312,6 +318,7 @@ class LogLevelTest(unittest.TestCase):
class HostnameTest(unittest.TestCase): class HostnameTest(unittest.TestCase):
@mock.patch('socket.getaddrinfo') @mock.patch('socket.getaddrinfo')
def test_deserialize_conversion_success(self, getaddrinfo_mock): def test_deserialize_conversion_success(self, getaddrinfo_mock):
value = types.Hostname() value = types.Hostname()
@ -339,6 +346,7 @@ class HostnameTest(unittest.TestCase):
class PortTest(unittest.TestCase): class PortTest(unittest.TestCase):
def test_valid_ports(self): def test_valid_ports(self):
value = types.Port() value = types.Port()
self.assertEqual(0, value.deserialize('0')) self.assertEqual(0, value.deserialize('0'))
@ -356,6 +364,7 @@ class PortTest(unittest.TestCase):
class ExpandedPathTest(unittest.TestCase): class ExpandedPathTest(unittest.TestCase):
def test_is_bytes(self): def test_is_bytes(self):
self.assertIsInstance(types.ExpandedPath(b'/tmp', b'foo'), bytes) self.assertIsInstance(types.ExpandedPath(b'/tmp', b'foo'), bytes)
@ -373,6 +382,7 @@ class ExpandedPathTest(unittest.TestCase):
class PathTest(unittest.TestCase): class PathTest(unittest.TestCase):
def test_deserialize_conversion_success(self): def test_deserialize_conversion_success(self):
result = types.Path().deserialize(b'/foo') result = types.Path().deserialize(b'/foo')
self.assertEqual('/foo', result) self.assertEqual('/foo', result)

View File

@ -6,6 +6,7 @@ from mopidy.config import validators
class ValidateChoiceTest(unittest.TestCase): class ValidateChoiceTest(unittest.TestCase):
def test_no_choices_passes(self): def test_no_choices_passes(self):
validators.validate_choice('foo', None) validators.validate_choice('foo', None)
@ -25,6 +26,7 @@ class ValidateChoiceTest(unittest.TestCase):
class ValidateMinimumTest(unittest.TestCase): class ValidateMinimumTest(unittest.TestCase):
def test_no_minimum_passes(self): def test_no_minimum_passes(self):
validators.validate_minimum(10, None) validators.validate_minimum(10, None)
@ -39,6 +41,7 @@ class ValidateMinimumTest(unittest.TestCase):
class ValidateMaximumTest(unittest.TestCase): class ValidateMaximumTest(unittest.TestCase):
def test_no_maximum_passes(self): def test_no_maximum_passes(self):
validators.validate_maximum(5, None) validators.validate_maximum(5, None)
@ -53,6 +56,7 @@ class ValidateMaximumTest(unittest.TestCase):
class ValidateRequiredTest(unittest.TestCase): class ValidateRequiredTest(unittest.TestCase):
def test_passes_when_false(self): def test_passes_when_false(self):
validators.validate_required('foo', False) validators.validate_required('foo', False)
validators.validate_required('', False) validators.validate_required('', False)

View File

@ -11,6 +11,7 @@ from mopidy.utils import versioning
class CoreActorTest(unittest.TestCase): class CoreActorTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.backend1 = mock.Mock() self.backend1 = mock.Mock()
self.backend1.uri_schemes.get.return_value = ['dummy1'] self.backend1.uri_schemes.get.return_value = ['dummy1']

View File

@ -15,6 +15,7 @@ from tests import dummy_backend
@mock.patch.object(core.CoreListener, 'send') @mock.patch.object(core.CoreListener, 'send')
class BackendEventsTest(unittest.TestCase): class BackendEventsTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.backend = dummy_backend.create_proxy() self.backend = dummy_backend.create_proxy()
self.backend.library.dummy_library = [ self.backend.library.dummy_library = [

View File

@ -10,6 +10,7 @@ from mopidy.utils import deprecation
class BaseCoreLibraryTest(unittest.TestCase): class BaseCoreLibraryTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
dummy1_root = Ref.directory(uri='dummy1:directory', name='dummy1') dummy1_root = Ref.directory(uri='dummy1:directory', name='dummy1')
self.backend1 = mock.Mock() self.backend1 = mock.Mock()
@ -41,6 +42,7 @@ class BaseCoreLibraryTest(unittest.TestCase):
# TODO: split by method # TODO: split by method
class CoreLibraryTest(BaseCoreLibraryTest): class CoreLibraryTest(BaseCoreLibraryTest):
def test_get_images_returns_empty_dict_for_no_uris(self): def test_get_images_returns_empty_dict_for_no_uris(self):
self.assertEqual({}, self.core.library.get_images([])) self.assertEqual({}, self.core.library.get_images([]))
@ -273,6 +275,7 @@ class CoreLibraryTest(BaseCoreLibraryTest):
class DeprecatedFindExactCoreLibraryTest(BaseCoreLibraryTest): class DeprecatedFindExactCoreLibraryTest(BaseCoreLibraryTest):
def run(self, result=None): def run(self, result=None):
with deprecation.ignore('core.library.find_exact'): with deprecation.ignore('core.library.find_exact'):
return super(DeprecatedFindExactCoreLibraryTest, self).run(result) return super(DeprecatedFindExactCoreLibraryTest, self).run(result)
@ -354,6 +357,7 @@ class DeprecatedFindExactCoreLibraryTest(BaseCoreLibraryTest):
class DeprecatedLookupCoreLibraryTest(BaseCoreLibraryTest): class DeprecatedLookupCoreLibraryTest(BaseCoreLibraryTest):
def run(self, result=None): def run(self, result=None):
with deprecation.ignore('core.library.lookup:uri_arg'): with deprecation.ignore('core.library.lookup:uri_arg'):
return super(DeprecatedLookupCoreLibraryTest, self).run(result) return super(DeprecatedLookupCoreLibraryTest, self).run(result)
@ -379,6 +383,7 @@ class DeprecatedLookupCoreLibraryTest(BaseCoreLibraryTest):
class LegacyFindExactToSearchLibraryTest(unittest.TestCase): class LegacyFindExactToSearchLibraryTest(unittest.TestCase):
def run(self, result=None): def run(self, result=None):
with deprecation.ignore('core.library.find_exact'): with deprecation.ignore('core.library.find_exact'):
return super(LegacyFindExactToSearchLibraryTest, self).run(result) return super(LegacyFindExactToSearchLibraryTest, self).run(result)

View File

@ -9,6 +9,7 @@ from mopidy.models import Playlist, TlTrack
class CoreListenerTest(unittest.TestCase): class CoreListenerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.listener = CoreListener() self.listener = CoreListener()

View File

@ -11,6 +11,7 @@ from tests import dummy_mixer
class CoreMixerTest(unittest.TestCase): class CoreMixerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.mixer = mock.Mock(spec=mixer.Mixer) self.mixer = mock.Mock(spec=mixer.Mixer)
self.core = core.Core(mixer=self.mixer, backends=[]) self.core = core.Core(mixer=self.mixer, backends=[])
@ -39,6 +40,7 @@ class CoreMixerTest(unittest.TestCase):
class CoreNoneMixerTest(unittest.TestCase): class CoreNoneMixerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.core = core.Core(mixer=None, backends=[]) self.core = core.Core(mixer=None, backends=[])
@ -57,6 +59,7 @@ class CoreNoneMixerTest(unittest.TestCase):
@mock.patch.object(mixer.MixerListener, 'send') @mock.patch.object(mixer.MixerListener, 'send')
class CoreMixerListenerTest(unittest.TestCase): class CoreMixerListenerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.mixer = dummy_mixer.create_proxy() self.mixer = dummy_mixer.create_proxy()
self.core = core.Core(mixer=self.mixer, backends=[]) self.core = core.Core(mixer=self.mixer, backends=[])
@ -78,6 +81,7 @@ class CoreMixerListenerTest(unittest.TestCase):
@mock.patch.object(mixer.MixerListener, 'send') @mock.patch.object(mixer.MixerListener, 'send')
class CoreNoneMixerListenerTest(unittest.TestCase): class CoreNoneMixerListenerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.core = core.Core(mixer=None, backends=[]) self.core = core.Core(mixer=None, backends=[])

View File

@ -15,6 +15,7 @@ from tests import dummy_audio as audio
# TODO: split into smaller easier to follow tests. setup is way to complex. # TODO: split into smaller easier to follow tests. setup is way to complex.
# TODO: just mock tracklist? # TODO: just mock tracklist?
class CorePlaybackTest(unittest.TestCase): class CorePlaybackTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.backend1 = mock.Mock() self.backend1 = mock.Mock()
self.backend1.uri_schemes.get.return_value = ['dummy1'] self.backend1.uri_schemes.get.return_value = ['dummy1']
@ -601,6 +602,7 @@ class TestBackend(pykka.ThreadingActor, backend.Backend):
class TestStream(unittest.TestCase): class TestStream(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.audio = audio.DummyAudio.start().proxy() self.audio = audio.DummyAudio.start().proxy()
self.backend = TestBackend.start(config={}, audio=self.audio).proxy() self.backend = TestBackend.start(config={}, audio=self.audio).proxy()
@ -684,6 +686,7 @@ class TestStream(unittest.TestCase):
class CorePlaybackWithOldBackendTest(unittest.TestCase): class CorePlaybackWithOldBackendTest(unittest.TestCase):
def test_type_error_from_old_backend_does_not_crash_core(self): def test_type_error_from_old_backend_does_not_crash_core(self):
b = mock.Mock() b = mock.Mock()
b.uri_schemes.get.return_value = ['dummy1'] b.uri_schemes.get.return_value = ['dummy1']

View File

@ -10,6 +10,7 @@ from mopidy.utils import deprecation
class BasePlaylistsTest(unittest.TestCase): class BasePlaylistsTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.plr1a = Ref.playlist(name='A', uri='dummy1:pl:a') self.plr1a = Ref.playlist(name='A', uri='dummy1:pl:a')
self.plr1b = Ref.playlist(name='B', uri='dummy1:pl:b') self.plr1b = Ref.playlist(name='B', uri='dummy1:pl:b')
@ -52,6 +53,7 @@ class BasePlaylistsTest(unittest.TestCase):
class PlaylistTest(BasePlaylistsTest): class PlaylistTest(BasePlaylistsTest):
def test_as_list_combines_result_from_backends(self): def test_as_list_combines_result_from_backends(self):
result = self.core.playlists.as_list() result = self.core.playlists.as_list()
@ -231,6 +233,7 @@ class PlaylistTest(BasePlaylistsTest):
class DeprecatedFilterPlaylistsTest(BasePlaylistsTest): class DeprecatedFilterPlaylistsTest(BasePlaylistsTest):
def run(self, result=None): def run(self, result=None):
with deprecation.ignore(ids=['core.playlists.filter', with deprecation.ignore(ids=['core.playlists.filter',
'core.playlists.get_playlists']): 'core.playlists.get_playlists']):
@ -248,6 +251,7 @@ class DeprecatedFilterPlaylistsTest(BasePlaylistsTest):
class DeprecatedGetPlaylistsTest(BasePlaylistsTest): class DeprecatedGetPlaylistsTest(BasePlaylistsTest):
def run(self, result=None): def run(self, result=None):
with deprecation.ignore('core.playlists.get_playlists'): with deprecation.ignore('core.playlists.get_playlists'):
return super(DeprecatedGetPlaylistsTest, self).run(result) return super(DeprecatedGetPlaylistsTest, self).run(result)

View File

@ -10,6 +10,7 @@ from mopidy.utils import deprecation
class TracklistTest(unittest.TestCase): class TracklistTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.tracks = [ self.tracks = [
Track(uri='dummy1:a', name='foo'), Track(uri='dummy1:a', name='foo'),

View File

@ -16,6 +16,7 @@ def create_proxy(config=None, mixer=None):
class DummyAudio(pykka.ThreadingActor): class DummyAudio(pykka.ThreadingActor):
def __init__(self, config=None, mixer=None): def __init__(self, config=None, mixer=None):
super(DummyAudio, self).__init__() super(DummyAudio, self).__init__()
self.state = audio.PlaybackState.STOPPED self.state = audio.PlaybackState.STOPPED

View File

@ -17,6 +17,7 @@ def create_proxy(config=None, audio=None):
class DummyBackend(pykka.ThreadingActor, backend.Backend): class DummyBackend(pykka.ThreadingActor, backend.Backend):
def __init__(self, config, audio): def __init__(self, config, audio):
super(DummyBackend, self).__init__() super(DummyBackend, self).__init__()
@ -57,6 +58,7 @@ class DummyLibraryProvider(backend.LibraryProvider):
class DummyPlaybackProvider(backend.PlaybackProvider): class DummyPlaybackProvider(backend.PlaybackProvider):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(DummyPlaybackProvider, self).__init__(*args, **kwargs) super(DummyPlaybackProvider, self).__init__(*args, **kwargs)
self._uri = None self._uri = None
@ -93,6 +95,7 @@ class DummyPlaybackProvider(backend.PlaybackProvider):
class DummyPlaylistsProvider(backend.PlaylistsProvider): class DummyPlaylistsProvider(backend.PlaylistsProvider):
def __init__(self, backend): def __init__(self, backend):
super(DummyPlaylistsProvider, self).__init__(backend) super(DummyPlaylistsProvider, self).__init__(backend)
self._playlists = [] self._playlists = []

View File

@ -13,6 +13,7 @@ from mopidy.http import handlers
class StaticFileHandlerTest(tornado.testing.AsyncHTTPTestCase): class StaticFileHandlerTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self): def get_app(self):
return tornado.web.Application([ return tornado.web.Application([
(r'/(.*)', handlers.StaticFileHandler, { (r'/(.*)', handlers.StaticFileHandler, {
@ -43,6 +44,7 @@ class StaticFileHandlerTest(tornado.testing.AsyncHTTPTestCase):
# We aren't bothering with skipIf as then we would need to "backport" gen_test # We aren't bothering with skipIf as then we would need to "backport" gen_test
if hasattr(tornado.websocket, 'websocket_connect'): if hasattr(tornado.websocket, 'websocket_connect'):
class WebSocketHandlerTest(tornado.testing.AsyncHTTPTestCase): class WebSocketHandlerTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self): def get_app(self):
self.core = mock.Mock() self.core = mock.Mock()
return tornado.web.Application([ return tornado.web.Application([

View File

@ -12,6 +12,7 @@ from mopidy.http import actor, handlers
class HttpServerTest(tornado.testing.AsyncHTTPTestCase): class HttpServerTest(tornado.testing.AsyncHTTPTestCase):
def get_config(self): def get_config(self):
return { return {
'http': { 'http': {
@ -43,6 +44,7 @@ class HttpServerTest(tornado.testing.AsyncHTTPTestCase):
class RootRedirectTest(HttpServerTest): class RootRedirectTest(HttpServerTest):
def test_should_redirect_to_mopidy_app(self): def test_should_redirect_to_mopidy_app(self):
response = self.fetch('/', method='GET', follow_redirects=False) response = self.fetch('/', method='GET', follow_redirects=False)
@ -51,6 +53,7 @@ class RootRedirectTest(HttpServerTest):
class LegacyStaticDirAppTest(HttpServerTest): class LegacyStaticDirAppTest(HttpServerTest):
def get_config(self): def get_config(self):
config = super(LegacyStaticDirAppTest, self).get_config() config = super(LegacyStaticDirAppTest, self).get_config()
config['http']['static_dir'] = os.path.dirname(__file__) config['http']['static_dir'] = os.path.dirname(__file__)
@ -73,6 +76,7 @@ class LegacyStaticDirAppTest(HttpServerTest):
class MopidyAppTest(HttpServerTest): class MopidyAppTest(HttpServerTest):
def test_should_return_index(self): def test_should_return_index(self):
response = self.fetch('/mopidy/', method='GET') response = self.fetch('/mopidy/', method='GET')
body = tornado.escape.to_unicode(response.body) body = tornado.escape.to_unicode(response.body)
@ -103,6 +107,7 @@ class MopidyAppTest(HttpServerTest):
class MopidyWebSocketHandlerTest(HttpServerTest): class MopidyWebSocketHandlerTest(HttpServerTest):
def test_should_return_ws(self): def test_should_return_ws(self):
response = self.fetch('/mopidy/ws', method='GET') response = self.fetch('/mopidy/ws', method='GET')
@ -119,6 +124,7 @@ class MopidyWebSocketHandlerTest(HttpServerTest):
class MopidyRPCHandlerTest(HttpServerTest): class MopidyRPCHandlerTest(HttpServerTest):
def test_should_return_rpc_error(self): def test_should_return_rpc_error(self):
cmd = tornado.escape.json_encode({'action': 'get_version'}) cmd = tornado.escape.json_encode({'action': 'get_version'})
@ -164,6 +170,7 @@ class MopidyRPCHandlerTest(HttpServerTest):
class HttpServerWithStaticFilesTest(tornado.testing.AsyncHTTPTestCase): class HttpServerWithStaticFilesTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self): def get_app(self):
config = { config = {
'http': { 'http': {
@ -214,6 +221,7 @@ def wsgi_app_factory(config, core):
class HttpServerWithWsgiAppTest(tornado.testing.AsyncHTTPTestCase): class HttpServerWithWsgiAppTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self): def get_app(self):
config = { config = {
'http': { 'http': {

View File

@ -7,6 +7,7 @@ from mopidy.models import Album, Track
class LocalLibrarySearchTest(unittest.TestCase): class LocalLibrarySearchTest(unittest.TestCase):
def test_find_exact_with_album_query(self): def test_find_exact_with_album_query(self):
expected_tracks = [Track(album=Album(name='foo'))] expected_tracks = [Track(album=Album(name='foo'))]
tracks = [Track(), Track(album=Album(name='bar'))] + expected_tracks tracks = [Track(), Track(album=Album(name='bar'))] + expected_tracks

View File

@ -272,6 +272,7 @@ class M3UPlaylistsProviderTest(unittest.TestCase):
class DeprecatedM3UPlaylistsProviderTest(M3UPlaylistsProviderTest): class DeprecatedM3UPlaylistsProviderTest(M3UPlaylistsProviderTest):
def run(self, result=None): def run(self, result=None):
with deprecation.ignore(ids=['core.playlists.filter', with deprecation.ignore(ids=['core.playlists.filter',
'core.playlists.get_playlists']): 'core.playlists.get_playlists']):

View File

@ -30,6 +30,7 @@ encoded_ext_track = encoded_track.copy(name='æøå')
# FIXME use mock instead of tempfile.NamedTemporaryFile # FIXME use mock instead of tempfile.NamedTemporaryFile
class M3UToUriTest(unittest.TestCase): class M3UToUriTest(unittest.TestCase):
def parse(self, name): def parse(self, name):
return translator.parse_m3u(name, data_dir) return translator.parse_m3u(name, data_dir)

View File

@ -14,6 +14,7 @@ from tests import dummy_backend, dummy_mixer
class MockConnection(mock.Mock): class MockConnection(mock.Mock):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(MockConnection, self).__init__(*args, **kwargs) super(MockConnection, self).__init__(*args, **kwargs)
self.host = mock.sentinel.host self.host = mock.sentinel.host

View File

@ -4,6 +4,7 @@ from tests.mpd import protocol
class AuthenticationActiveTest(protocol.BaseTestCase): class AuthenticationActiveTest(protocol.BaseTestCase):
def get_config(self): def get_config(self):
config = super(AuthenticationActiveTest, self).get_config() config = super(AuthenticationActiveTest, self).get_config()
config['mpd']['password'] = 'topsecret' config['mpd']['password'] = 'topsecret'
@ -52,6 +53,7 @@ class AuthenticationActiveTest(protocol.BaseTestCase):
class AuthenticationInactiveTest(protocol.BaseTestCase): class AuthenticationInactiveTest(protocol.BaseTestCase):
def test_authentication_with_anything_when_password_check_turned_off(self): def test_authentication_with_anything_when_password_check_turned_off(self):
self.send_request('any request at all') self.send_request('any request at all')
self.assertTrue(self.dispatcher.authenticated) self.assertTrue(self.dispatcher.authenticated)

View File

@ -4,6 +4,7 @@ from tests.mpd import protocol
class ChannelsHandlerTest(protocol.BaseTestCase): class ChannelsHandlerTest(protocol.BaseTestCase):
def test_subscribe(self): def test_subscribe(self):
self.send_request('subscribe "topic"') self.send_request('subscribe "topic"')
self.assertEqualResponse('ACK [0@0] {subscribe} Not implemented') self.assertEqualResponse('ACK [0@0] {subscribe} Not implemented')

View File

@ -4,6 +4,7 @@ from tests.mpd import protocol
class CommandListsTest(protocol.BaseTestCase): class CommandListsTest(protocol.BaseTestCase):
def test_command_list_begin(self): def test_command_list_begin(self):
response = self.send_request('command_list_begin') response = self.send_request('command_list_begin')
self.assertEqual([], response) self.assertEqual([], response)

View File

@ -6,6 +6,7 @@ from tests.mpd import protocol
class ConnectionHandlerTest(protocol.BaseTestCase): class ConnectionHandlerTest(protocol.BaseTestCase):
def test_close_closes_the_client_connection(self): def test_close_closes_the_client_connection(self):
with patch.object(self.session, 'close') as close_mock: with patch.object(self.session, 'close') as close_mock:
self.send_request('close') self.send_request('close')

View File

@ -7,6 +7,7 @@ from tests.mpd import protocol
class AddCommandsTest(protocol.BaseTestCase): class AddCommandsTest(protocol.BaseTestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
super(AddCommandsTest, self).setUp() super(AddCommandsTest, self).setUp()
@ -92,6 +93,7 @@ class AddCommandsTest(protocol.BaseTestCase):
class BasePopulatedTracklistTestCase(protocol.BaseTestCase): class BasePopulatedTracklistTestCase(protocol.BaseTestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
super(BasePopulatedTracklistTestCase, self).setUp() super(BasePopulatedTracklistTestCase, self).setUp()
tracks = [Track(uri='dummy:/%s' % x, name=x) for x in 'abcdef'] tracks = [Track(uri='dummy:/%s' % x, name=x) for x in 'abcdef']
@ -100,6 +102,7 @@ class BasePopulatedTracklistTestCase(protocol.BaseTestCase):
class DeleteCommandsTest(BasePopulatedTracklistTestCase): class DeleteCommandsTest(BasePopulatedTracklistTestCase):
def test_clear(self): def test_clear(self):
self.send_request('clear') self.send_request('clear')
self.assertEqual(len(self.core.tracklist.tracks.get()), 0) self.assertEqual(len(self.core.tracklist.tracks.get()), 0)
@ -155,6 +158,7 @@ class DeleteCommandsTest(BasePopulatedTracklistTestCase):
class MoveCommandsTest(BasePopulatedTracklistTestCase): class MoveCommandsTest(BasePopulatedTracklistTestCase):
def test_move_songpos(self): def test_move_songpos(self):
self.send_request('move "1" "0"') self.send_request('move "1" "0"')
result = [t.name for t in self.core.tracklist.tracks.get()] result = [t.name for t in self.core.tracklist.tracks.get()]
@ -186,6 +190,7 @@ class MoveCommandsTest(BasePopulatedTracklistTestCase):
class PlaylistFindCommandTest(protocol.BaseTestCase): class PlaylistFindCommandTest(protocol.BaseTestCase):
def test_playlistfind(self): def test_playlistfind(self):
self.send_request('playlistfind "tag" "needle"') self.send_request('playlistfind "tag" "needle"')
self.assertEqualResponse('ACK [0@0] {playlistfind} Not implemented') self.assertEqualResponse('ACK [0@0] {playlistfind} Not implemented')
@ -211,6 +216,7 @@ class PlaylistFindCommandTest(protocol.BaseTestCase):
class PlaylistIdCommandTest(BasePopulatedTracklistTestCase): class PlaylistIdCommandTest(BasePopulatedTracklistTestCase):
def test_playlistid_without_songid(self): def test_playlistid_without_songid(self):
self.send_request('playlistid') self.send_request('playlistid')
self.assertInResponse('Title: a') self.assertInResponse('Title: a')
@ -231,6 +237,7 @@ class PlaylistIdCommandTest(BasePopulatedTracklistTestCase):
class PlaylistInfoCommandTest(BasePopulatedTracklistTestCase): class PlaylistInfoCommandTest(BasePopulatedTracklistTestCase):
def test_playlist_returns_same_as_playlistinfo(self): def test_playlist_returns_same_as_playlistinfo(self):
with deprecation.ignore('mpd.protocol.current_playlist.playlist'): with deprecation.ignore('mpd.protocol.current_playlist.playlist'):
playlist_response = self.send_request('playlist') playlist_response = self.send_request('playlist')
@ -318,6 +325,7 @@ class PlaylistInfoCommandTest(BasePopulatedTracklistTestCase):
class PlaylistSearchCommandTest(protocol.BaseTestCase): class PlaylistSearchCommandTest(protocol.BaseTestCase):
def test_playlistsearch(self): def test_playlistsearch(self):
self.send_request('playlistsearch "any" "needle"') self.send_request('playlistsearch "any" "needle"')
self.assertEqualResponse('ACK [0@0] {playlistsearch} Not implemented') self.assertEqualResponse('ACK [0@0] {playlistsearch} Not implemented')
@ -328,6 +336,7 @@ class PlaylistSearchCommandTest(protocol.BaseTestCase):
class PlChangeCommandTest(BasePopulatedTracklistTestCase): class PlChangeCommandTest(BasePopulatedTracklistTestCase):
def test_plchanges_with_lower_version_returns_changes(self): def test_plchanges_with_lower_version_returns_changes(self):
self.send_request('plchanges "0"') self.send_request('plchanges "0"')
self.assertInResponse('Title: a') self.assertInResponse('Title: a')
@ -379,6 +388,7 @@ class PlChangeCommandTest(BasePopulatedTracklistTestCase):
# TODO: we only seem to be testing that don't touch the non shuffled region :/ # TODO: we only seem to be testing that don't touch the non shuffled region :/
class ShuffleCommandTest(BasePopulatedTracklistTestCase): class ShuffleCommandTest(BasePopulatedTracklistTestCase):
def test_shuffle_without_range(self): def test_shuffle_without_range(self):
version = self.core.tracklist.version.get() version = self.core.tracklist.version.get()
@ -409,6 +419,7 @@ class ShuffleCommandTest(BasePopulatedTracklistTestCase):
class SwapCommandTest(BasePopulatedTracklistTestCase): class SwapCommandTest(BasePopulatedTracklistTestCase):
def test_swap(self): def test_swap(self):
self.send_request('swap "1" "4"') self.send_request('swap "1" "4"')
result = [t.name for t in self.core.tracklist.tracks.get()] result = [t.name for t in self.core.tracklist.tracks.get()]

View File

@ -8,6 +8,7 @@ from tests.mpd import protocol
class IdleHandlerTest(protocol.BaseTestCase): class IdleHandlerTest(protocol.BaseTestCase):
def idle_event(self, subsystem): def idle_event(self, subsystem):
self.session.on_idle(subsystem) self.session.on_idle(subsystem)

View File

@ -11,6 +11,7 @@ from tests.mpd import protocol
class QueryFromMpdSearchFormatTest(unittest.TestCase): class QueryFromMpdSearchFormatTest(unittest.TestCase):
def test_dates_are_extracted(self): def test_dates_are_extracted(self):
result = music_db._query_from_mpd_search_parameters( result = music_db._query_from_mpd_search_parameters(
['Date', '1974-01-02', 'Date', '1975'], music_db._SEARCH_MAPPING) ['Date', '1974-01-02', 'Date', '1975'], music_db._SEARCH_MAPPING)
@ -37,6 +38,7 @@ class QueryFromMpdListFormatTest(unittest.TestCase):
# TODO: why isn't core.playlists.filter getting deprecation warnings? # TODO: why isn't core.playlists.filter getting deprecation warnings?
class MusicDatabaseHandlerTest(protocol.BaseTestCase): class MusicDatabaseHandlerTest(protocol.BaseTestCase):
def test_count(self): def test_count(self):
self.send_request('count "artist" "needle"') self.send_request('count "artist" "needle"')
self.assertInResponse('songs: 0') self.assertInResponse('songs: 0')
@ -430,6 +432,7 @@ class MusicDatabaseHandlerTest(protocol.BaseTestCase):
class MusicDatabaseFindTest(protocol.BaseTestCase): class MusicDatabaseFindTest(protocol.BaseTestCase):
def test_find_includes_fake_artist_and_album_tracks(self): def test_find_includes_fake_artist_and_album_tracks(self):
self.backend.library.dummy_find_exact_result = SearchResult( self.backend.library.dummy_find_exact_result = SearchResult(
albums=[Album(uri='dummy:album:a', name='A', date='2001')], albums=[Album(uri='dummy:album:a', name='A', date='2001')],
@ -620,6 +623,7 @@ class MusicDatabaseFindTest(protocol.BaseTestCase):
class MusicDatabaseListTest(protocol.BaseTestCase): class MusicDatabaseListTest(protocol.BaseTestCase):
def test_list(self): def test_list(self):
self.backend.library.dummy_get_distinct_result = { self.backend.library.dummy_get_distinct_result = {
'artist': set(['A Artist'])} 'artist': set(['A Artist'])}
@ -1061,6 +1065,7 @@ class MusicDatabaseListTest(protocol.BaseTestCase):
class MusicDatabaseSearchTest(protocol.BaseTestCase): class MusicDatabaseSearchTest(protocol.BaseTestCase):
def test_search(self): def test_search(self):
self.backend.library.dummy_search_result = SearchResult( self.backend.library.dummy_search_result = SearchResult(
albums=[Album(uri='dummy:album:a', name='A')], albums=[Album(uri='dummy:album:a', name='A')],

View File

@ -15,6 +15,7 @@ STOPPED = PlaybackState.STOPPED
class PlaybackOptionsHandlerTest(protocol.BaseTestCase): class PlaybackOptionsHandlerTest(protocol.BaseTestCase):
def test_consume_off(self): def test_consume_off(self):
self.send_request('consume "0"') self.send_request('consume "0"')
self.assertFalse(self.core.tracklist.consume.get()) self.assertFalse(self.core.tracklist.consume.get())
@ -173,6 +174,7 @@ class PlaybackOptionsHandlerTest(protocol.BaseTestCase):
class PlaybackControlHandlerTest(protocol.BaseTestCase): class PlaybackControlHandlerTest(protocol.BaseTestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
super(PlaybackControlHandlerTest, self).setUp() super(PlaybackControlHandlerTest, self).setUp()
self.tracks = [Track(uri='dummy:a', length=40000), self.tracks = [Track(uri='dummy:a', length=40000),

View File

@ -4,6 +4,7 @@ from tests.mpd import protocol
class ReflectionHandlerTest(protocol.BaseTestCase): class ReflectionHandlerTest(protocol.BaseTestCase):
def test_config_is_not_allowed_across_the_network(self): def test_config_is_not_allowed_across_the_network(self):
self.send_request('config') self.send_request('config')
self.assertEqualResponse( self.assertEqualResponse(
@ -49,6 +50,7 @@ class ReflectionHandlerTest(protocol.BaseTestCase):
class ReflectionWhenNotAuthedTest(protocol.BaseTestCase): class ReflectionWhenNotAuthedTest(protocol.BaseTestCase):
def get_config(self): def get_config(self):
config = super(ReflectionWhenNotAuthedTest, self).get_config() config = super(ReflectionWhenNotAuthedTest, self).get_config()
config['mpd']['password'] = 'topsecret' config['mpd']['password'] = 'topsecret'

View File

@ -8,6 +8,7 @@ from tests.mpd import protocol
class IssueGH17RegressionTest(protocol.BaseTestCase): class IssueGH17RegressionTest(protocol.BaseTestCase):
""" """
The issue: http://github.com/mopidy/mopidy/issues/17 The issue: http://github.com/mopidy/mopidy/issues/17
@ -17,6 +18,7 @@ class IssueGH17RegressionTest(protocol.BaseTestCase):
- Turn on random mode - Turn on random mode
- Press next until you get to the unplayable track - Press next until you get to the unplayable track
""" """
def test(self): def test(self):
tracks = [ tracks = [
Track(uri='dummy:a'), Track(uri='dummy:a'),
@ -51,6 +53,7 @@ class IssueGH17RegressionTest(protocol.BaseTestCase):
class IssueGH18RegressionTest(protocol.BaseTestCase): class IssueGH18RegressionTest(protocol.BaseTestCase):
""" """
The issue: http://github.com/mopidy/mopidy/issues/18 The issue: http://github.com/mopidy/mopidy/issues/18
@ -89,6 +92,7 @@ class IssueGH18RegressionTest(protocol.BaseTestCase):
class IssueGH22RegressionTest(protocol.BaseTestCase): class IssueGH22RegressionTest(protocol.BaseTestCase):
""" """
The issue: http://github.com/mopidy/mopidy/issues/22 The issue: http://github.com/mopidy/mopidy/issues/22
@ -123,6 +127,7 @@ class IssueGH22RegressionTest(protocol.BaseTestCase):
class IssueGH69RegressionTest(protocol.BaseTestCase): class IssueGH69RegressionTest(protocol.BaseTestCase):
""" """
The issue: https://github.com/mopidy/mopidy/issues/69 The issue: https://github.com/mopidy/mopidy/issues/69
@ -151,6 +156,7 @@ class IssueGH69RegressionTest(protocol.BaseTestCase):
class IssueGH113RegressionTest(protocol.BaseTestCase): class IssueGH113RegressionTest(protocol.BaseTestCase):
""" """
The issue: https://github.com/mopidy/mopidy/issues/113 The issue: https://github.com/mopidy/mopidy/issues/113
@ -176,6 +182,7 @@ class IssueGH113RegressionTest(protocol.BaseTestCase):
class IssueGH137RegressionTest(protocol.BaseTestCase): class IssueGH137RegressionTest(protocol.BaseTestCase):
""" """
The issue: https://github.com/mopidy/mopidy/issues/137 The issue: https://github.com/mopidy/mopidy/issues/137

View File

@ -6,6 +6,7 @@ from tests.mpd import protocol
class StatusHandlerTest(protocol.BaseTestCase): class StatusHandlerTest(protocol.BaseTestCase):
def test_clearerror(self): def test_clearerror(self):
self.send_request('clearerror') self.send_request('clearerror')
self.assertEqualResponse('ACK [0@0] {clearerror} Not implemented') self.assertEqualResponse('ACK [0@0] {clearerror} Not implemented')

View File

@ -4,6 +4,7 @@ from tests.mpd import protocol
class StickersHandlerTest(protocol.BaseTestCase): class StickersHandlerTest(protocol.BaseTestCase):
def test_sticker_get(self): def test_sticker_get(self):
self.send_request( self.send_request(
'sticker get "song" "file:///dev/urandom" "a_name"') 'sticker get "song" "file:///dev/urandom" "a_name"')

View File

@ -6,6 +6,7 @@ from tests.mpd import protocol
class PlaylistsHandlerTest(protocol.BaseTestCase): class PlaylistsHandlerTest(protocol.BaseTestCase):
def test_listplaylist(self): def test_listplaylist(self):
self.backend.playlists.set_dummy_playlists([ self.backend.playlists.set_dummy_playlists([
Playlist( Playlist(

View File

@ -8,6 +8,7 @@ from mopidy.mpd import exceptions, protocol
class TestConverts(unittest.TestCase): class TestConverts(unittest.TestCase):
def test_integer(self): def test_integer(self):
self.assertEqual(123, protocol.INT('123')) self.assertEqual(123, protocol.INT('123'))
self.assertEqual(-123, protocol.INT('-123')) self.assertEqual(-123, protocol.INT('-123'))
@ -55,6 +56,7 @@ class TestConverts(unittest.TestCase):
class TestCommands(unittest.TestCase): class TestCommands(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.commands = protocol.Commands() self.commands = protocol.Commands()

View File

@ -13,6 +13,7 @@ from tests import dummy_backend
class MpdDispatcherTest(unittest.TestCase): class MpdDispatcherTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
config = { config = {
'mpd': { 'mpd': {

View File

@ -8,6 +8,7 @@ from mopidy.mpd.exceptions import (
class MpdExceptionsTest(unittest.TestCase): class MpdExceptionsTest(unittest.TestCase):
def test_mpd_not_implemented_is_a_mpd_ack_error(self): def test_mpd_not_implemented_is_a_mpd_ack_error(self):
try: try:
raise MpdNotImplemented raise MpdNotImplemented

View File

@ -23,6 +23,7 @@ STOPPED = PlaybackState.STOPPED
class StatusHandlerTest(unittest.TestCase): class StatusHandlerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.mixer = dummy_mixer.create_proxy() self.mixer = dummy_mixer.create_proxy()
self.backend = dummy_backend.create_proxy() self.backend = dummy_backend.create_proxy()

View File

@ -8,6 +8,7 @@ from mopidy.mpd import exceptions, tokenize
class TestTokenizer(unittest.TestCase): class TestTokenizer(unittest.TestCase):
def assertTokenizeEquals(self, expected, line): # noqa: N802 def assertTokenizeEquals(self, expected, line): # noqa: N802
self.assertEqual(expected, tokenize.split(line)) self.assertEqual(expected, tokenize.split(line))

View File

@ -116,6 +116,7 @@ class TrackMpdFormatTest(unittest.TestCase):
class PlaylistMpdFormatTest(unittest.TestCase): class PlaylistMpdFormatTest(unittest.TestCase):
def test_mpd_format(self): def test_mpd_format(self):
playlist = Playlist(tracks=[ playlist = Playlist(tracks=[
Track(track_no=1), Track(track_no=2), Track(track_no=3)]) Track(track_no=1), Track(track_no=2), Track(track_no=3)])

View File

@ -19,6 +19,7 @@ from tests import path_to_data_dir
class LibraryProviderTest(unittest.TestCase): class LibraryProviderTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.backend = mock.Mock() self.backend = mock.Mock()
self.backend.uri_schemes = ['file'] self.backend.uri_schemes = ['file']

View File

@ -9,6 +9,7 @@ from mopidy import commands
class ConfigOverrideTypeTest(unittest.TestCase): class ConfigOverrideTypeTest(unittest.TestCase):
def test_valid_override(self): def test_valid_override(self):
expected = (b'section', b'key', b'value') expected = (b'section', b'key', b'value')
self.assertEqual( self.assertEqual(
@ -44,6 +45,7 @@ class ConfigOverrideTypeTest(unittest.TestCase):
class CommandParsingTest(unittest.TestCase): class CommandParsingTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.exit_patcher = mock.patch.object(commands.Command, 'exit') self.exit_patcher = mock.patch.object(commands.Command, 'exit')
self.exit_mock = self.exit_patcher.start() self.exit_mock = self.exit_patcher.start()
@ -258,6 +260,7 @@ class CommandParsingTest(unittest.TestCase):
class UsageTest(unittest.TestCase): class UsageTest(unittest.TestCase):
@mock.patch('sys.argv') @mock.patch('sys.argv')
def test_prog_name_default_and_override(self, argv_mock): def test_prog_name_default_and_override(self, argv_mock):
argv_mock.__getitem__.return_value = '/usr/bin/foo' argv_mock.__getitem__.return_value = '/usr/bin/foo'
@ -294,6 +297,7 @@ class UsageTest(unittest.TestCase):
class HelpTest(unittest.TestCase): class HelpTest(unittest.TestCase):
@mock.patch('sys.argv') @mock.patch('sys.argv')
def test_prog_name_default_and_override(self, argv_mock): def test_prog_name_default_and_override(self, argv_mock):
argv_mock.__getitem__.return_value = '/usr/bin/foo' argv_mock.__getitem__.return_value = '/usr/bin/foo'
@ -485,6 +489,7 @@ class HelpTest(unittest.TestCase):
class RunTest(unittest.TestCase): class RunTest(unittest.TestCase):
def test_default_implmentation_raises_error(self): def test_default_implmentation_raises_error(self):
with self.assertRaises(NotImplementedError): with self.assertRaises(NotImplementedError):
commands.Command().run() commands.Command().run()

View File

@ -6,6 +6,7 @@ from mopidy import exceptions
class ExceptionsTest(unittest.TestCase): class ExceptionsTest(unittest.TestCase):
def test_exception_can_include_message_string(self): def test_exception_can_include_message_string(self):
exc = exceptions.MopidyException('foo') exc = exceptions.MopidyException('foo')

View File

@ -6,6 +6,7 @@ from mopidy import config, ext
class ExtensionTest(unittest.TestCase): class ExtensionTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.ext = ext.Extension() self.ext = ext.Extension()

View File

@ -9,6 +9,7 @@ import mopidy
class HelpTest(unittest.TestCase): class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self): def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__) mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help'] args = [sys.executable, mopidy_dir, '--help']

View File

@ -8,6 +8,7 @@ from mopidy import mixer
class MixerListenerTest(unittest.TestCase): class MixerListenerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.listener = mixer.MixerListener() self.listener = mixer.MixerListener()

View File

@ -9,6 +9,7 @@ from mopidy.models import (
class GenericCopyTest(unittest.TestCase): class GenericCopyTest(unittest.TestCase):
def compare(self, orig, other): def compare(self, orig, other):
self.assertEqual(orig, other) self.assertEqual(orig, other)
self.assertNotEqual(id(orig), id(other)) self.assertNotEqual(id(orig), id(other))
@ -58,6 +59,7 @@ class GenericCopyTest(unittest.TestCase):
class RefTest(unittest.TestCase): class RefTest(unittest.TestCase):
def test_uri(self): def test_uri(self):
uri = 'an_uri' uri = 'an_uri'
ref = Ref(uri=uri) ref = Ref(uri=uri)
@ -131,6 +133,7 @@ class RefTest(unittest.TestCase):
class ImageTest(unittest.TestCase): class ImageTest(unittest.TestCase):
def test_uri(self): def test_uri(self):
uri = 'an_uri' uri = 'an_uri'
image = Image(uri=uri) image = Image(uri=uri)
@ -156,6 +159,7 @@ class ImageTest(unittest.TestCase):
class ArtistTest(unittest.TestCase): class ArtistTest(unittest.TestCase):
def test_uri(self): def test_uri(self):
uri = 'an_uri' uri = 'an_uri'
artist = Artist(uri=uri) artist = Artist(uri=uri)
@ -286,6 +290,7 @@ class ArtistTest(unittest.TestCase):
class AlbumTest(unittest.TestCase): class AlbumTest(unittest.TestCase):
def test_uri(self): def test_uri(self):
uri = 'an_uri' uri = 'an_uri'
album = Album(uri=uri) album = Album(uri=uri)
@ -498,6 +503,7 @@ class AlbumTest(unittest.TestCase):
class TrackTest(unittest.TestCase): class TrackTest(unittest.TestCase):
def test_uri(self): def test_uri(self):
uri = 'an_uri' uri = 'an_uri'
track = Track(uri=uri) track = Track(uri=uri)
@ -796,6 +802,7 @@ class TrackTest(unittest.TestCase):
class TlTrackTest(unittest.TestCase): class TlTrackTest(unittest.TestCase):
def test_tlid(self): def test_tlid(self):
tlid = 123 tlid = 123
tl_track = TlTrack(tlid=tlid) tl_track = TlTrack(tlid=tlid)
@ -874,6 +881,7 @@ class TlTrackTest(unittest.TestCase):
class PlaylistTest(unittest.TestCase): class PlaylistTest(unittest.TestCase):
def test_uri(self): def test_uri(self):
uri = 'an_uri' uri = 'an_uri'
playlist = Playlist(uri=uri) playlist = Playlist(uri=uri)
@ -1065,6 +1073,7 @@ class PlaylistTest(unittest.TestCase):
class SearchResultTest(unittest.TestCase): class SearchResultTest(unittest.TestCase):
def test_uri(self): def test_uri(self):
uri = 'an_uri' uri = 'an_uri'
result = SearchResult(uri=uri) result = SearchResult(uri=uri)

View File

@ -7,6 +7,7 @@ from mopidy import __version__
class VersionTest(unittest.TestCase): class VersionTest(unittest.TestCase):
def assertVersionLess(self, first, second): # noqa: N802 def assertVersionLess(self, first, second): # noqa: N802
self.assertLess(StrictVersion(first), StrictVersion(second)) self.assertLess(StrictVersion(first), StrictVersion(second))

View File

@ -17,6 +17,7 @@ from tests import any_int, any_unicode
class ConnectionTest(unittest.TestCase): class ConnectionTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.mock = Mock(spec=network.Connection) self.mock = Mock(spec=network.Connection)

View File

@ -14,6 +14,7 @@ from tests import any_unicode
class LineProtocolTest(unittest.TestCase): class LineProtocolTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.mock = Mock(spec=network.LineProtocol) self.mock = Mock(spec=network.LineProtocol)

View File

@ -14,6 +14,7 @@ from tests import any_int
class ServerTest(unittest.TestCase): class ServerTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.mock = Mock(spec=network.Server) self.mock = Mock(spec=network.Server)

View File

@ -9,6 +9,7 @@ from mopidy.utils import network
class FormatHostnameTest(unittest.TestCase): class FormatHostnameTest(unittest.TestCase):
@patch('mopidy.utils.network.has_ipv6', True) @patch('mopidy.utils.network.has_ipv6', True)
def test_format_hostname_prefixes_ipv4_addresses_when_ipv6_available(self): def test_format_hostname_prefixes_ipv4_addresses_when_ipv6_available(self):
network.has_ipv6 = True network.has_ipv6 = True
@ -22,6 +23,7 @@ class FormatHostnameTest(unittest.TestCase):
class TryIPv6SocketTest(unittest.TestCase): class TryIPv6SocketTest(unittest.TestCase):
@patch('socket.has_ipv6', False) @patch('socket.has_ipv6', False)
def test_system_that_claims_no_ipv6_support(self): def test_system_that_claims_no_ipv6_support(self):
self.assertFalse(network.try_ipv6_socket()) self.assertFalse(network.try_ipv6_socket())
@ -40,6 +42,7 @@ class TryIPv6SocketTest(unittest.TestCase):
class CreateSocketTest(unittest.TestCase): class CreateSocketTest(unittest.TestCase):
@patch('mopidy.utils.network.has_ipv6', False) @patch('mopidy.utils.network.has_ipv6', False)
@patch('socket.socket') @patch('socket.socket')
def test_ipv4_socket(self, socket_mock): def test_ipv4_socket(self, socket_mock):

View File

@ -16,6 +16,7 @@ from mopidy.utils import deps
class DepsTest(unittest.TestCase): class DepsTest(unittest.TestCase):
def test_format_dependency_list(self): def test_format_dependency_list(self):
adapters = [ adapters = [
lambda: dict(name='Python', version='FooPython 2.7.3'), lambda: dict(name='Python', version='FooPython 2.7.3'),

View File

@ -9,6 +9,7 @@ from mopidy.utils.encoding import locale_decode
@mock.patch('mopidy.utils.encoding.locale.getpreferredencoding') @mock.patch('mopidy.utils.encoding.locale.getpreferredencoding')
class LocaleDecodeTest(unittest.TestCase): class LocaleDecodeTest(unittest.TestCase):
def test_can_decode_utf8_strings_with_french_content(self, mock): def test_can_decode_utf8_strings_with_french_content(self, mock):
mock.return_value = 'UTF-8' mock.return_value = 'UTF-8'

View File

@ -14,6 +14,7 @@ from tests import dummy_backend
class Calculator(object): class Calculator(object):
def __init__(self): def __init__(self):
self._mem = None self._mem = None
@ -50,6 +51,7 @@ class Calculator(object):
class JsonRpcTestBase(unittest.TestCase): class JsonRpcTestBase(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.backend = dummy_backend.create_proxy() self.backend = dummy_backend.create_proxy()
self.calc = Calculator() self.calc = Calculator()
@ -74,12 +76,14 @@ class JsonRpcTestBase(unittest.TestCase):
class JsonRpcSetupTest(JsonRpcTestBase): class JsonRpcSetupTest(JsonRpcTestBase):
def test_empty_object_mounts_is_not_allowed(self): def test_empty_object_mounts_is_not_allowed(self):
with self.assertRaises(AttributeError): with self.assertRaises(AttributeError):
jsonrpc.JsonRpcWrapper(objects={'': Calculator()}) jsonrpc.JsonRpcWrapper(objects={'': Calculator()})
class JsonRpcSerializationTest(JsonRpcTestBase): class JsonRpcSerializationTest(JsonRpcTestBase):
def test_handle_json_converts_from_and_to_json(self): def test_handle_json_converts_from_and_to_json(self):
self.jrw.handle_data = mock.Mock() self.jrw.handle_data = mock.Mock()
self.jrw.handle_data.return_value = {'foo': 'response'} self.jrw.handle_data.return_value = {'foo': 'response'}
@ -145,6 +149,7 @@ class JsonRpcSerializationTest(JsonRpcTestBase):
class JsonRpcSingleCommandTest(JsonRpcTestBase): class JsonRpcSingleCommandTest(JsonRpcTestBase):
def test_call_method_on_root(self): def test_call_method_on_root(self):
request = { request = {
'jsonrpc': '2.0', 'jsonrpc': '2.0',
@ -249,6 +254,7 @@ class JsonRpcSingleCommandTest(JsonRpcTestBase):
class JsonRpcSingleNotificationTest(JsonRpcTestBase): class JsonRpcSingleNotificationTest(JsonRpcTestBase):
def test_notification_does_not_return_a_result(self): def test_notification_does_not_return_a_result(self):
request = { request = {
'jsonrpc': '2.0', 'jsonrpc': '2.0',
@ -283,6 +289,7 @@ class JsonRpcSingleNotificationTest(JsonRpcTestBase):
class JsonRpcBatchTest(JsonRpcTestBase): class JsonRpcBatchTest(JsonRpcTestBase):
def test_batch_of_only_commands_returns_all(self): def test_batch_of_only_commands_returns_all(self):
self.core.tracklist.set_random(True).get() self.core.tracklist.set_random(True).get()
@ -331,6 +338,7 @@ class JsonRpcBatchTest(JsonRpcTestBase):
class JsonRpcSingleCommandErrorTest(JsonRpcTestBase): class JsonRpcSingleCommandErrorTest(JsonRpcTestBase):
def test_application_error_response(self): def test_application_error_response(self):
request = { request = {
'jsonrpc': '2.0', 'jsonrpc': '2.0',
@ -500,6 +508,7 @@ class JsonRpcSingleCommandErrorTest(JsonRpcTestBase):
class JsonRpcBatchErrorTest(JsonRpcTestBase): class JsonRpcBatchErrorTest(JsonRpcTestBase):
def test_empty_batch_list_causes_invalid_request_error(self): def test_empty_batch_list_causes_invalid_request_error(self):
request = [] request = []
response = self.jrw.handle_data(request) response = self.jrw.handle_data(request)
@ -566,6 +575,7 @@ class JsonRpcBatchErrorTest(JsonRpcTestBase):
class JsonRpcInspectorTest(JsonRpcTestBase): class JsonRpcInspectorTest(JsonRpcTestBase):
def test_empty_object_mounts_is_not_allowed(self): def test_empty_object_mounts_is_not_allowed(self):
with self.assertRaises(AttributeError): with self.assertRaises(AttributeError):
jsonrpc.JsonRpcInspector(objects={'': Calculator}) jsonrpc.JsonRpcInspector(objects={'': Calculator})

View File

@ -16,6 +16,7 @@ import tests
class GetOrCreateDirTest(unittest.TestCase): class GetOrCreateDirTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.parent = tempfile.mkdtemp() self.parent = tempfile.mkdtemp()
@ -67,6 +68,7 @@ class GetOrCreateDirTest(unittest.TestCase):
class GetOrCreateFileTest(unittest.TestCase): class GetOrCreateFileTest(unittest.TestCase):
def setUp(self): # noqa: N802 def setUp(self): # noqa: N802
self.parent = tempfile.mkdtemp() self.parent = tempfile.mkdtemp()
@ -135,6 +137,7 @@ class GetOrCreateFileTest(unittest.TestCase):
class PathToFileURITest(unittest.TestCase): class PathToFileURITest(unittest.TestCase):
def test_simple_path(self): def test_simple_path(self):
result = path.path_to_uri('/etc/fstab') result = path.path_to_uri('/etc/fstab')
self.assertEqual(result, 'file:///etc/fstab') self.assertEqual(result, 'file:///etc/fstab')
@ -157,6 +160,7 @@ class PathToFileURITest(unittest.TestCase):
class UriToPathTest(unittest.TestCase): class UriToPathTest(unittest.TestCase):
def test_simple_uri(self): def test_simple_uri(self):
result = path.uri_to_path('file:///etc/fstab') result = path.uri_to_path('file:///etc/fstab')
self.assertEqual(result, '/etc/fstab'.encode('utf-8')) self.assertEqual(result, '/etc/fstab'.encode('utf-8'))
@ -175,6 +179,7 @@ class UriToPathTest(unittest.TestCase):
class SplitPathTest(unittest.TestCase): class SplitPathTest(unittest.TestCase):
def test_empty_path(self): def test_empty_path(self):
self.assertEqual([], path.split_path('')) self.assertEqual([], path.split_path(''))
@ -378,6 +383,7 @@ class FindMTimesTest(unittest.TestCase):
# TODO: kill this in favour of just os.path.getmtime + mocks # TODO: kill this in favour of just os.path.getmtime + mocks
class MtimeTest(unittest.TestCase): class MtimeTest(unittest.TestCase):
def tearDown(self): # noqa: N802 def tearDown(self): # noqa: N802
path.mtime.undo_fake() path.mtime.undo_fake()