Merge pull request #2179 from mandeep/new-style-classes

Refactored old style classes to new style classes
This commit is contained in:
Ronny Pfannschmidt 2017-01-10 16:08:24 +01:00 committed by GitHub
commit 6c011f43e9
18 changed files with 55 additions and 49 deletions

View File

@ -87,6 +87,7 @@ Lukas Bednar
Luke Murphy Luke Murphy
Maciek Fijalkowski Maciek Fijalkowski
Maho Maho
Mandeep Bhutani
Manuel Krebber Manuel Krebber
Marc Schlaich Marc Schlaich
Marcin Bachry Marcin Bachry

View File

@ -17,6 +17,9 @@ New Features
Changes Changes
------- -------
* Old-style classes have been changed to new-style classes in order to improve
compatability with Python 2. Thanks to `@mandeep`_ for the PR (`#2147`_).
* It is now possible to skip test classes from being collected by setting a * It is now possible to skip test classes from being collected by setting a
``__test__`` attribute to ``False`` in the class body (`#2007`_). Thanks ``__test__`` attribute to ``False`` in the class body (`#2007`_). Thanks
to `@syre`_ for the report and `@lwm`_ for the PR. to `@syre`_ for the report and `@lwm`_ for the PR.
@ -44,6 +47,7 @@ Changes
.. _@wheerd: https://github.com/wheerd .. _@wheerd: https://github.com/wheerd
.. _@fogo: https://github.com/fogo .. _@fogo: https://github.com/fogo
.. _@lesteve: https://github.com/lesteve .. _@lesteve: https://github.com/lesteve
.. _@mandeep: https://github.com/mandeep
.. _#1512: https://github.com/pytest-dev/pytest/issues/1512 .. _#1512: https://github.com/pytest-dev/pytest/issues/1512
.. _#1874: https://github.com/pytest-dev/pytest/pull/1874 .. _#1874: https://github.com/pytest-dev/pytest/pull/1874
@ -52,6 +56,7 @@ Changes
.. _#2013: https://github.com/pytest-dev/pytest/issues/2013 .. _#2013: https://github.com/pytest-dev/pytest/issues/2013
.. _#2101: https://github.com/pytest-dev/pytest/pull/2101 .. _#2101: https://github.com/pytest-dev/pytest/pull/2101
.. _#2166: https://github.com/pytest-dev/pytest/pull/2166 .. _#2166: https://github.com/pytest-dev/pytest/pull/2166
.. _#2147: https://github.com/pytest-dev/pytest/issues/2147
3.0.6.dev0 (unreleased) 3.0.6.dev0 (unreleased)
======================= =======================

View File

@ -62,7 +62,7 @@ import sys
import os import os
from glob import glob from glob import glob
class FastFilesCompleter: class FastFilesCompleter(object):
'Fast file completer class' 'Fast file completer class'
def __init__(self, directories=True): def __init__(self, directories=True):
self.directories = directories self.directories = directories

View File

@ -59,7 +59,7 @@ class DummyRewriteHook(object):
pass pass
class AssertionState: class AssertionState(object):
"""State for the assertion plugin.""" """State for the assertion plugin."""
def __init__(self, config, mode): def __init__(self, config, mode):

View File

@ -87,7 +87,7 @@ class Cache(object):
json.dump(value, f, indent=2, sort_keys=True) json.dump(value, f, indent=2, sort_keys=True)
class LFPlugin: class LFPlugin(object):
""" Plugin which implements the --lf (run last-failing) option """ """ Plugin which implements the --lf (run last-failing) option """
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config

View File

@ -57,7 +57,7 @@ def pytest_load_initial_conftests(early_config, parser, args):
sys.stderr.write(err) sys.stderr.write(err)
class CaptureManager: class CaptureManager(object):
def __init__(self, method): def __init__(self, method):
self._method = method self._method = method
@ -182,7 +182,7 @@ def capfd(request):
return c return c
class CaptureFixture: class CaptureFixture(object):
def __init__(self, captureclass, request): def __init__(self, captureclass, request):
self.captureclass = captureclass self.captureclass = captureclass
self.request = request self.request = request
@ -315,10 +315,10 @@ class MultiCapture(object):
return (self.out.snap() if self.out is not None else "", return (self.out.snap() if self.out is not None else "",
self.err.snap() if self.err is not None else "") self.err.snap() if self.err is not None else "")
class NoCapture: class NoCapture(object):
__init__ = start = done = suspend = resume = lambda *args: None __init__ = start = done = suspend = resume = lambda *args: None
class FDCapture: class FDCapture(object):
""" Capture IO to/from a given os-level filedescriptor. """ """ Capture IO to/from a given os-level filedescriptor. """
def __init__(self, targetfd, tmpfile=None): def __init__(self, targetfd, tmpfile=None):
@ -394,7 +394,7 @@ class FDCapture:
os.write(self.targetfd_save, data) os.write(self.targetfd_save, data)
class SysCapture: class SysCapture(object):
def __init__(self, fd, tmpfile=None): def __init__(self, fd, tmpfile=None):
name = patchsysdict[fd] name = patchsysdict[fd]
self._old = getattr(sys, name) self._old = getattr(sys, name)
@ -432,7 +432,7 @@ class SysCapture:
self._old.flush() self._old.flush()
class DontReadFromInput: class DontReadFromInput(object):
"""Temporary stub class. Ideally when stdin is accessed, the """Temporary stub class. Ideally when stdin is accessed, the
capturing should be turned off, with possibly all data captured capturing should be turned off, with possibly all data captured
so far sent to the screen. This should be configurable, though, so far sent to the screen. This should be configurable, though,

View File

@ -62,7 +62,7 @@ def main(args=None, plugins=None):
sys.stderr.write("ERROR: %s\n" %(msg,)) sys.stderr.write("ERROR: %s\n" %(msg,))
return 4 return 4
class cmdline: # compatibility namespace class cmdline(object): # compatibility namespace
main = staticmethod(main) main = staticmethod(main)
@ -447,7 +447,7 @@ class PytestPluginManager(PluginManager):
self.consider_module(mod) self.consider_module(mod)
class Parser: class Parser(object):
""" Parser for command line arguments and ini-file values. """ Parser for command line arguments and ini-file values.
:ivar extra_info: dict of generic param -> value to display in case :ivar extra_info: dict of generic param -> value to display in case
@ -582,7 +582,7 @@ class ArgumentError(Exception):
return self.msg return self.msg
class Argument: class Argument(object):
"""class that mimics the necessary behaviour of optparse.Option """class that mimics the necessary behaviour of optparse.Option
its currently a least effort implementation its currently a least effort implementation
@ -712,7 +712,7 @@ class Argument:
return 'Argument({0})'.format(', '.join(args)) return 'Argument({0})'.format(', '.join(args))
class OptionGroup: class OptionGroup(object):
def __init__(self, name, description="", parser=None): def __init__(self, name, description="", parser=None):
self.name = name self.name = name
self.description = description self.description = description
@ -838,7 +838,7 @@ class CmdOptions(object):
def copy(self): def copy(self):
return CmdOptions(self.__dict__) return CmdOptions(self.__dict__)
class Notset: class Notset(object):
def __repr__(self): def __repr__(self):
return "<NOTSET>" return "<NOTSET>"

View File

@ -43,7 +43,7 @@ def pytest_configure(config):
pytestPDB._pdb_cls = pdb_cls pytestPDB._pdb_cls = pdb_cls
config._cleanup.append(fin) config._cleanup.append(fin)
class pytestPDB: class pytestPDB(object):
""" Pseudo PDB that defers to the real pdb. """ """ Pseudo PDB that defers to the real pdb. """
_pluginmanager = None _pluginmanager = None
_config = None _config = None
@ -64,7 +64,7 @@ class pytestPDB:
self._pdb_cls().set_trace(frame) self._pdb_cls().set_trace(frame)
class PdbInvoke: class PdbInvoke(object):
def pytest_exception_interact(self, node, call, report): def pytest_exception_interact(self, node, call, report):
capman = node.config.pluginmanager.getplugin("capturemanager") capman = node.config.pluginmanager.getplugin("capturemanager")
if capman: if capman:

View File

@ -222,7 +222,7 @@ def slice_items(items, ignore, scoped_argkeys_cache):
class FuncargnamesCompatAttr: class FuncargnamesCompatAttr(object):
""" helper class so that Metafunc, Function and FixtureRequest """ helper class so that Metafunc, Function and FixtureRequest
don't need to each define the "funcargnames" compatibility attribute. don't need to each define the "funcargnames" compatibility attribute.
""" """
@ -258,7 +258,7 @@ def fillfixtures(function):
def get_direct_param_fixture_func(request): def get_direct_param_fixture_func(request):
return request.param return request.param
class FuncFixtureInfo: class FuncFixtureInfo(object):
def __init__(self, argnames, names_closure, name2fixturedefs): def __init__(self, argnames, names_closure, name2fixturedefs):
self.argnames = argnames self.argnames = argnames
self.names_closure = names_closure self.names_closure = names_closure
@ -456,7 +456,7 @@ class FixtureRequest(FuncargnamesCompatAttr):
fixturedef = self._getnextfixturedef(argname) fixturedef = self._getnextfixturedef(argname)
except FixtureLookupError: except FixtureLookupError:
if argname == "request": if argname == "request":
class PseudoFixtureDef: class PseudoFixtureDef(object):
cached_result = (self, [0], None) cached_result = (self, [0], None)
scope = "function" scope = "function"
return PseudoFixtureDef return PseudoFixtureDef
@ -723,7 +723,7 @@ def call_fixture_func(fixturefunc, request, kwargs):
return res return res
class FixtureDef: class FixtureDef(object):
""" A container for a factory definition. """ """ A container for a factory definition. """
def __init__(self, fixturemanager, baseid, argname, func, scope, params, def __init__(self, fixturemanager, baseid, argname, func, scope, params,
unittest=False, ids=None): unittest=False, ids=None):
@ -822,7 +822,7 @@ def pytest_fixture_setup(fixturedef, request):
return result return result
class FixtureFunctionMarker: class FixtureFunctionMarker(object):
def __init__(self, scope, params, autouse=False, ids=None, name=None): def __init__(self, scope, params, autouse=False, ids=None, name=None):
self.scope = scope self.scope = scope
self.params = params self.params = params
@ -909,7 +909,7 @@ def pytestconfig(request):
return request.config return request.config
class FixtureManager: class FixtureManager(object):
""" """
pytest fixtures definitions and information is stored and managed pytest fixtures definitions and information is stored and managed
from this class. from this class.

View File

@ -179,7 +179,7 @@ def pytest_ignore_collect(path, config):
return False return False
class FSHookProxy: class FSHookProxy(object):
def __init__(self, fspath, pm, remove_mods): def __init__(self, fspath, pm, remove_mods):
self.fspath = fspath self.fspath = fspath
self.pm = pm self.pm = pm

View File

@ -99,7 +99,7 @@ def pytest_collection_modifyitems(items, config):
items[:] = remaining items[:] = remaining
class MarkMapping: class MarkMapping(object):
"""Provides a local mapping for markers where item access """Provides a local mapping for markers where item access
resolves to True if the marker is present. """ resolves to True if the marker is present. """
def __init__(self, keywords): def __init__(self, keywords):
@ -113,7 +113,7 @@ class MarkMapping:
return name in self._mymarks return name in self._mymarks
class KeywordMapping: class KeywordMapping(object):
"""Provides a local mapping for keywords. """Provides a local mapping for keywords.
Given a list of names, map any substring of one of these names to True. Given a list of names, map any substring of one of these names to True.
""" """
@ -173,7 +173,7 @@ def pytest_configure(config):
pytest.mark._config = config pytest.mark._config = config
class MarkGenerator: class MarkGenerator(object):
""" Factory for :class:`MarkDecorator` objects - exposed as """ Factory for :class:`MarkDecorator` objects - exposed as
a ``pytest.mark`` singleton instance. Example:: a ``pytest.mark`` singleton instance. Example::
@ -210,7 +210,7 @@ def istestfunc(func):
return hasattr(func, "__call__") and \ return hasattr(func, "__call__") and \
getattr(func, "__name__", "<lambda>") != "<lambda>" getattr(func, "__name__", "<lambda>") != "<lambda>"
class MarkDecorator: class MarkDecorator(object):
""" A decorator for test functions and test classes. When applied """ A decorator for test functions and test classes. When applied
it will create :class:`MarkInfo` objects which may be it will create :class:`MarkInfo` objects which may be
:ref:`retrieved by hooks as item keywords <excontrolskip>`. :ref:`retrieved by hooks as item keywords <excontrolskip>`.

View File

@ -88,7 +88,7 @@ def derive_importpath(import_path, raising):
return attr, target return attr, target
class Notset: class Notset(object):
def __repr__(self): def __repr__(self):
return "<notset>" return "<notset>"
@ -96,7 +96,7 @@ class Notset:
notset = Notset() notset = Notset()
class MonkeyPatch: class MonkeyPatch(object):
""" Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes. """ Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes.
""" """

View File

@ -165,7 +165,7 @@ def _pytest(request):
""" """
return PytestArg(request) return PytestArg(request)
class PytestArg: class PytestArg(object):
def __init__(self, request): def __init__(self, request):
self.request = request self.request = request
@ -180,7 +180,7 @@ def get_public_names(l):
return [x for x in l if x[0] != "_"] return [x for x in l if x[0] != "_"]
class ParsedCall: class ParsedCall(object):
def __init__(self, name, kwargs): def __init__(self, name, kwargs):
self.__dict__.update(kwargs) self.__dict__.update(kwargs)
self._name = name self._name = name
@ -191,7 +191,7 @@ class ParsedCall:
return "<ParsedCall %r(**%r)>" %(self._name, d) return "<ParsedCall %r(**%r)>" %(self._name, d)
class HookRecorder: class HookRecorder(object):
"""Record all hooks called in a plugin manager. """Record all hooks called in a plugin manager.
This wraps all the hook calls in the plugin manager, recording This wraps all the hook calls in the plugin manager, recording
@ -335,7 +335,7 @@ def testdir(request, tmpdir_factory):
rex_outcome = re.compile("(\d+) ([\w-]+)") rex_outcome = re.compile("(\d+) ([\w-]+)")
class RunResult: class RunResult(object):
"""The result of running a command. """The result of running a command.
Attributes: Attributes:
@ -380,7 +380,7 @@ class RunResult:
class Testdir: class Testdir(object):
"""Temporary test directory with tools to test/run pytest itself. """Temporary test directory with tools to test/run pytest itself.
This is based on the ``tmpdir`` fixture but provides a number of This is based on the ``tmpdir`` fixture but provides a number of
@ -707,7 +707,7 @@ class Testdir:
rec = [] rec = []
class Collect: class Collect(object):
def pytest_configure(x, config): def pytest_configure(x, config):
rec.append(self.make_hook_recorder(config.pluginmanager)) rec.append(self.make_hook_recorder(config.pluginmanager))
@ -718,7 +718,7 @@ class Testdir:
if len(rec) == 1: if len(rec) == 1:
reprec = rec.pop() reprec = rec.pop()
else: else:
class reprec: class reprec(object):
pass pass
reprec.ret = ret reprec.ret = ret
@ -742,13 +742,13 @@ class Testdir:
reprec = self.inline_run(*args, **kwargs) reprec = self.inline_run(*args, **kwargs)
except SystemExit as e: except SystemExit as e:
class reprec: class reprec(object):
ret = e.args[0] ret = e.args[0]
except Exception: except Exception:
traceback.print_exc() traceback.print_exc()
class reprec: class reprec(object):
ret = 3 ret = 3
finally: finally:
out, err = capture.reset() out, err = capture.reset()
@ -1033,7 +1033,7 @@ def getdecoded(out):
py.io.saferepr(out),) py.io.saferepr(out),)
class LineComp: class LineComp(object):
def __init__(self): def __init__(self):
self.stringio = py.io.TextIO() self.stringio = py.io.TextIO()
@ -1049,7 +1049,7 @@ class LineComp:
return LineMatcher(lines1).fnmatch_lines(lines2) return LineMatcher(lines1).fnmatch_lines(lines2)
class LineMatcher: class LineMatcher(object):
"""Flexible matching of text. """Flexible matching of text.
This is a convenience class to test large texts like the output of This is a convenience class to test large texts like the output of

View File

@ -55,7 +55,7 @@ def pytest_sessionstart(session):
def pytest_sessionfinish(session): def pytest_sessionfinish(session):
session._setupstate.teardown_all() session._setupstate.teardown_all()
class NodeInfo: class NodeInfo(object):
def __init__(self, location): def __init__(self, location):
self.location = location self.location = location
@ -150,7 +150,7 @@ def call_runtest_hook(item, when, **kwds):
ihook = getattr(item.ihook, hookname) ihook = getattr(item.ihook, hookname)
return CallInfo(lambda: ihook(item=item, **kwds), when=when) return CallInfo(lambda: ihook(item=item, **kwds), when=when)
class CallInfo: class CallInfo(object):
""" Result/Exception info a function invocation. """ """ Result/Exception info a function invocation. """
#: None or ExceptionInfo object. #: None or ExceptionInfo object.
excinfo = None excinfo = None

View File

@ -72,7 +72,7 @@ def xfail(reason=""):
xfail.Exception = XFailed xfail.Exception = XFailed
class MarkEvaluator: class MarkEvaluator(object):
def __init__(self, item, name): def __init__(self, item, name):
self.item = item self.item = item
self.name = name self.name = name

View File

@ -80,7 +80,7 @@ def pytest_report_teststatus(report):
letter = "f" letter = "f"
return report.outcome, letter, report.outcome.upper() return report.outcome, letter, report.outcome.upper()
class WarningReport: class WarningReport(object):
def __init__(self, code, message, nodeid=None, fslocation=None): def __init__(self, code, message, nodeid=None, fslocation=None):
self.code = code self.code = code
self.message = message self.message = message
@ -88,7 +88,7 @@ class WarningReport:
self.fslocation = fslocation self.fslocation = fslocation
class TerminalReporter: class TerminalReporter(object):
def __init__(self, config, file=None): def __init__(self, config, file=None):
import _pytest.config import _pytest.config
self.config = config self.config = config

View File

@ -6,7 +6,7 @@ import py
from _pytest.monkeypatch import MonkeyPatch from _pytest.monkeypatch import MonkeyPatch
class TempdirFactory: class TempdirFactory(object):
"""Factory for temporary directories under the common base temp directory. """Factory for temporary directories under the common base temp directory.
The base directory can be configured using the ``--basetemp`` option. The base directory can be configured using the ``--basetemp`` option.

View File

@ -75,7 +75,7 @@ __all__ = ["PluginManager", "PluginValidationError", "HookCallError",
_py3 = sys.version_info > (3, 0) _py3 = sys.version_info > (3, 0)
class HookspecMarker: class HookspecMarker(object):
""" Decorator helper class for marking functions as hook specifications. """ Decorator helper class for marking functions as hook specifications.
You can instantiate it with a project_name to get a decorator. You can instantiate it with a project_name to get a decorator.
@ -113,7 +113,7 @@ class HookspecMarker:
return setattr_hookspec_opts return setattr_hookspec_opts
class HookimplMarker: class HookimplMarker(object):
""" Decorator helper class for marking functions as hook implementations. """ Decorator helper class for marking functions as hook implementations.
You can instantiate with a project_name to get a decorator. You can instantiate with a project_name to get a decorator.
@ -770,7 +770,7 @@ class _HookCaller(object):
proc(res[0]) proc(res[0])
class HookImpl: class HookImpl(object):
def __init__(self, plugin, plugin_name, function, hook_impl_opts): def __init__(self, plugin, plugin_name, function, hook_impl_opts):
self.function = function self.function = function
self.argnames = varnames(self.function) self.argnames = varnames(self.function)