[Pytest-commit] commit/pytest: 3 new changesets

commits-noreply at bitbucket.org commits-noreply at bitbucket.org
Sun Feb 22 14:27:52 CET 2015


3 new commits in pytest:

https://bitbucket.org/hpk42/pytest/commits/70703aae8a84/
Changeset:   70703aae8a84
Branch:      flake8-clean
User:        RonnyPfannschmidt
Date:        2015-02-22 12:50:00+00:00
Summary:     flake8 clean _pytest/assertion
Affected #:  4 files

diff -r 605bc8fa35f9d9156aa5c404c3d750ddd3b9f8c2 -r 70703aae8a84684ae8bc4da981e0a036178a6a00 _pytest/assertion/reinterpret.py
--- a/_pytest/assertion/reinterpret.py
+++ b/_pytest/assertion/reinterpret.py
@@ -5,7 +5,7 @@
 
 
 class AssertionError(BuiltinAssertionError):
-    def __init__(self, *args):
+    def __init__(self, *args):  # noqa too complex
         BuiltinAssertionError.__init__(self, *args)
         if args:
             # on Python2.6 we get len(args)==2 for: assert 0, (x,y)

diff -r 605bc8fa35f9d9156aa5c404c3d750ddd3b9f8c2 -r 70703aae8a84684ae8bc4da981e0a036178a6a00 _pytest/assertion/rewrite.py
--- a/_pytest/assertion/rewrite.py
+++ b/_pytest/assertion/rewrite.py
@@ -13,6 +13,7 @@
 
 import py
 from _pytest.assertion import util
+_format_explanation = util.format_explanation  # noqa
 
 
 # pytest caches rewritten pycs in __pycache__.
@@ -35,6 +36,7 @@
 REWRITE_NEWLINES = sys.version_info[:2] != (2, 7) and sys.version_info < (3, 2)
 ASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3
 
+
 class AssertionRewritingHook(object):
     """PEP302 Import hook which rewrites asserts."""
 
@@ -47,7 +49,7 @@
         self.fnpats = session.config.getini("python_files")
         self.session = session
 
-    def find_module(self, name, path=None):
+    def find_module(self, name, path=None):  # noqa too complex
         if self.session is None:
             return None
         sess = self.session
@@ -162,8 +164,6 @@
             raise
         return sys.modules[name]
 
-
-
     def is_package(self, name):
         try:
             fd, fn, desc = imp.find_module(name)
@@ -202,7 +202,7 @@
         fp = open(pyc, "wb")
     except IOError:
         err = sys.exc_info()[1].errno
-        state.trace("error writing pyc file at %s: errno=%s" %(pyc, err))
+        state.trace("error writing pyc file at %s: errno=%s" % (pyc, err))
         # we ignore any failure to write the cache file
         # there are many reasons, permission-denied, __pycache__ being a
         # file etc.
@@ -223,7 +223,8 @@
 cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+")
 BOM_UTF8 = '\xef\xbb\xbf'
 
-def _rewrite_test(state, fn):
+
+def _rewrite_test(state, fn):  # noqa: too complex
     """Try to read and rewrite *fn* and return the code object."""
     try:
         stat = fn.stat()
@@ -245,8 +246,8 @@
         end1 = source.find("\n")
         end2 = source.find("\n", end1 + 1)
         if (not source.startswith(BOM_UTF8) and
-            cookie_re.match(source[0:end1]) is None and
-            cookie_re.match(source[end1 + 1:end2]) is None):
+                cookie_re.match(source[0:end1]) is None and
+                cookie_re.match(source[end1 + 1:end2]) is None):
             if hasattr(state, "_indecode"):
                 # encodings imported us again, so don't rewrite.
                 return None, None
@@ -279,6 +280,7 @@
         return None, None
     return stat, co
 
+
 def _make_rewritten_pyc(state, source_stat, pyc, co):
     """Try to dump rewritten code to *pyc*."""
     if sys.platform.startswith("win"):
@@ -292,6 +294,7 @@
         if _write_pyc(state, co, source_stat, proc_pyc):
             os.rename(proc_pyc, pyc)
 
+
 def _read_pyc(source, pyc, trace=lambda x: None):
     """Possibly read a pytest pyc containing rewritten code.
 
@@ -349,8 +352,6 @@
     return repr.replace(t("\n"), t("\\n"))
 
 
-from _pytest.assertion.util import format_explanation as _format_explanation # noqa
-
 def _format_assertmsg(obj):
     """Format the custom assertion message given.
 
@@ -378,9 +379,11 @@
         s = s.replace(t("\\n"), t("\n~"))
     return s
 
+
 def _should_repr_global_name(obj):
     return not hasattr(obj, "__name__") and not py.builtin.callable(obj)
 
+
 def _format_boolop(explanations, is_or):
     explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")"
     if py.builtin._istext(explanation):
@@ -389,6 +392,7 @@
         t = py.builtin.bytes
     return explanation.replace(t('%'), t('%%'))
 
+
 def _call_reprcompare(ops, results, expls, each_obj):
     for i, res, expl in zip(range(len(ops)), results, expls):
         try:
@@ -422,7 +426,7 @@
     ast.Mult: "*",
     ast.Div: "/",
     ast.FloorDiv: "//",
-    ast.Mod: "%%", # escaped for string formatting
+    ast.Mod: "%%",  # escaped for string formatting
     ast.Eq: "==",
     ast.NotEq: "!=",
     ast.Lt: "<",
@@ -502,7 +506,7 @@
 
     """
 
-    def run(self, mod):
+    def run(self, mod):  # noqa: too complex
         """Find all assert statements in *mod* and rewrite them."""
         if not mod.body:
             # Nothing to do.
@@ -701,11 +705,12 @@
         levels = len(boolop.values) - 1
         self.push_format_context()
         # Process each operand, short-circuting if needed.
+        cond = None
         for i, v in enumerate(boolop.values):
             if i:
                 fail_inner = []
                 # cond is set in a prior loop iteration below
-                self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa
+                self.on_failure.append(ast.If(cond, fail_inner, []))
                 self.on_failure = fail_inner
             self.push_format_context()
             res, expl = self.visit(v)

diff -r 605bc8fa35f9d9156aa5c404c3d750ddd3b9f8c2 -r 70703aae8a84684ae8bc4da981e0a036178a6a00 _pytest/assertion/util.py
--- a/_pytest/assertion/util.py
+++ b/_pytest/assertion/util.py
@@ -122,18 +122,24 @@
     basestring = str
 
 
-def assertrepr_compare(config, op, left, right):
+def assertrepr_compare(config, op, left, right):  # noqa too complex
     """Return specialised explanations for some operators/operands"""
     width = 80 - 15 - len(op) - 2  # 15 chars indentation, 1 space around op
     left_repr = py.io.saferepr(left, maxsize=int(width/2))
     right_repr = py.io.saferepr(right, maxsize=width-len(left_repr))
     summary = u('%s %s %s') % (left_repr, op, right_repr)
 
-    issequence = lambda x: (isinstance(x, (list, tuple, Sequence))
-                            and not isinstance(x, basestring))
-    istext = lambda x: isinstance(x, basestring)
-    isdict = lambda x: isinstance(x, dict)
-    isset = lambda x: isinstance(x, (set, frozenset))
+    def issequence(x):
+        return isinstance(x, (list, tuple, Sequence)) and not istext(x)
+
+    def istext(x):
+        return isinstance(x, basestring)
+
+    def isdict(x):
+        return isinstance(x, dict)
+
+    def isset(x):
+        return isinstance(x, (set, frozenset))
 
     def isiterable(obj):
         try:
@@ -176,7 +182,7 @@
     return [summary] + explanation
 
 
-def _diff_text(left, right, verbose=False):
+def _diff_text(left, right, verbose=False):  # noqa too complex
     """Return the explanation for the diff between text or bytes
 
     Unless --verbose is used this will skip leading and trailing
@@ -244,8 +250,8 @@
         explanation += [
             u('Right contains more items, first extra item: %s') %
             py.io.saferepr(right[len(left)],)]
-    return explanation  # + _diff_text(pprint.pformat(left),
-                        #              pprint.pformat(right))
+    # explanation +=  _diff_text(pprint.pformat(left), pprint.pformat(right))
+    return explanation
 
 
 def _compare_eq_set(left, right, verbose=False):

diff -r 605bc8fa35f9d9156aa5c404c3d750ddd3b9f8c2 -r 70703aae8a84684ae8bc4da981e0a036178a6a00 tox.ini
--- a/tox.ini
+++ b/tox.ini
@@ -145,3 +145,5 @@
 
 [flake8]
 max-complexity = 10
+exclude = _pytest/assertion/oldinterpret.py,_pytest/assertion/newinterpret.py
+


https://bitbucket.org/hpk42/pytest/commits/509d62feb916/
Changeset:   509d62feb916
Branch:      flake8-clean
User:        RonnyPfannschmidt
Date:        2015-02-22 13:25:03+00:00
Summary:     flake8 clean _pytest/python
Affected #:  1 file

diff -r 70703aae8a84684ae8bc4da981e0a036178a6a00 -r 509d62feb91604048b1af64ce23b7e1cd563c0c8 _pytest/python.py
--- a/_pytest/python.py
+++ b/_pytest/python.py
@@ -18,6 +18,7 @@
 # used to work around a python2 exception info leak
 exc_clear = getattr(sys, 'exc_clear', lambda: None)
 
+
 def getfslineno(obj):
     # xxx let decorators etc specify a sane ordering
     while hasattr(obj, "__wrapped__"):
@@ -28,6 +29,7 @@
     assert isinstance(fslineno[1], int), obj
     return fslineno
 
+
 def getimfunc(func):
     try:
         return func.__func__
@@ -50,7 +52,7 @@
     def __call__(self, function):
         if isclass(function):
             raise ValueError(
-                    "class fixtures not supported (may be in the future)")
+                "class fixtures not supported (may be in the future)")
         function._pytestfixturefunction = self
         return function
 
@@ -82,14 +84,15 @@
        they will be generated automatically from the params.
 
     """
-    if callable(scope) and params is None and autouse == False:
+    if callable(scope) and params is None and autouse is False:
         # direct decoration
         return FixtureFunctionMarker(
-                "function", params, autouse)(scope)
+            "function", params, autouse)(scope)
     if params is not None and not isinstance(params, (list, tuple)):
         params = list(params)
     return FixtureFunctionMarker(scope, params, autouse, ids=ids)
 
+
 def yield_fixture(scope="function", params=None, autouse=False, ids=None):
     """ (return a) decorator to mark a yield-fixture factory function
     (EXPERIMENTAL).
@@ -99,16 +102,17 @@
     statement to provide a fixture.  See
     http://pytest.org/en/latest/yieldfixture.html for more info.
     """
-    if callable(scope) and params is None and autouse == False:
+    if callable(scope) and params is None and autouse is False:
         # direct decoration
         return FixtureFunctionMarker(
-                "function", params, autouse, yieldctx=True)(scope)
+            "function", params, autouse, yieldctx=True)(scope)
     else:
         return FixtureFunctionMarker(scope, params, autouse,
                                      yieldctx=True, ids=ids)
 
 defaultfuncargprefixmarker = fixture()
 
+
 def pyobj_property(name):
     def get(self):
         node = self.getparent(getattr(pytest, name))
@@ -121,20 +125,26 @@
 
 def pytest_addoption(parser):
     group = parser.getgroup("general")
-    group.addoption('--fixtures', '--funcargs',
-               action="store_true", dest="showfixtures", default=False,
-               help="show available fixtures, sorted by plugin appearance")
-    parser.addini("usefixtures", type="args", default=[],
+    group.addoption(
+        '--fixtures', '--funcargs',
+        action="store_true", dest="showfixtures", default=False,
+        help="show available fixtures, sorted by plugin appearance")
+    parser.addini(
+        "usefixtures", type="args", default=[],
         help="list of default fixtures to be used with this project")
-    parser.addini("python_files", type="args",
+    parser.addini(
+        "python_files", type="args",
         default=['test_*.py', '*_test.py'],
         help="glob-style file patterns for Python test module discovery")
-    parser.addini("python_classes", type="args", default=["Test",],
+    parser.addini(
+        "python_classes", type="args", default=["Test"],
         help="prefixes or glob names for Python test class discovery")
-    parser.addini("python_functions", type="args", default=["test",],
+    parser.addini(
+        "python_functions", type="args", default=["test"],
         help="prefixes or glob names for Python test function and "
              "method discovery")
 
+
 def pytest_cmdline_main(config):
     if config.option.showfixtures:
         showfixtures(config)
@@ -149,8 +159,10 @@
     for marker in markers:
         metafunc.parametrize(*marker.args, **marker.kwargs)
 
+
 def pytest_configure(config):
-    config.addinivalue_line("markers",
+    config.addinivalue_line(
+        "markers",
         "parametrize(argnames, argvalues): call a test function multiple "
         "times passing in different arguments in turn. argvalues generally "
         "needs to be a list of values if argnames specifies only one name "
@@ -160,27 +172,36 @@
         "see http://pytest.org/latest/parametrize.html for more info and "
         "examples."
     )
-    config.addinivalue_line("markers",
+    config.addinivalue_line(
+        "markers",
         "usefixtures(fixturename1, fixturename2, ...): mark tests as needing "
-        "all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures "
+        "all of the specified fixtures. "
+        "see http://pytest.org/latest/fixture.html#usefixtures "
     )
 
+
 def pytest_sessionstart(session):
     session._fixturemanager = FixtureManager(session)
 
+
 @pytest.mark.trylast
 def pytest_namespace():
     raises.Exception = pytest.fail.Exception
     return {
         'fixture': fixture,
         'yield_fixture': yield_fixture,
-        'raises' : raises,
+        'raises': raises,
         'collect': {
-        'Module': Module, 'Class': Class, 'Instance': Instance,
-        'Function': Function, 'Generator': Generator,
-        '_fillfuncargs': fillfixtures}
+            'Module': Module,
+            'Class': Class,
+            'Instance': Instance,
+            'Function': Function,
+            'Generator': Generator,
+            '_fillfuncargs': fillfixtures,
+        },
     }
 
+
 @fixture(scope="session")
 def pytestconfig(request):
     """ the pytest config object with access to command line opts."""
@@ -200,6 +221,7 @@
         testfunction(**testargs)
     return True
 
+
 def pytest_collect_file(path, parent):
     ext = path.ext
     if ext == ".py":
@@ -208,13 +230,15 @@
                 if path.fnmatch(pat):
                     break
             else:
-               return
+                return
         ihook = parent.session.gethookproxy(path)
         return ihook.pytest_pycollect_makemodule(path=path, parent=parent)
 
+
 def pytest_pycollect_makemodule(path, parent):
     return Module(path, parent)
 
+
 @pytest.mark.hookwrapper
 def pytest_pycollect_makeitem(collector, name, obj):
     outcome = yield
@@ -227,13 +251,15 @@
             Class = collector._getcustomclass("Class")
             outcome.force_result(Class(name, parent=collector))
     elif collector.funcnamefilter(name) and hasattr(obj, "__call__") and\
-        getfixturemarker(obj) is None:
+            getfixturemarker(obj) is None:
         # mock seems to store unbound methods (issue473), normalize it
         obj = getattr(obj, "__func__", obj)
         if not isfunction(obj):
-            collector.warn(code="C2", message=
-                "cannot collect %r because it is not a function."
-                % name, )
+            collector.warn(
+                code="C2",
+                message="cannot collect %r "
+                        "because it is not a function." % name)
+
         if getattr(obj, "__test__", True):
             if is_generator(obj):
                 res = Generator(name, parent=collector)
@@ -241,18 +267,21 @@
                 res = list(collector._genfunctions(name, obj))
             outcome.force_result(res)
 
+
 def is_generator(func):
     try:
-        return py.code.getrawcode(func).co_flags & 32 # generator function
-    except AttributeError: # builtin functions have no bytecode
+        return py.code.getrawcode(func).co_flags & 32  # generator function
+    except AttributeError:  # builtin functions have no bytecode
         # assume them to not be generators
         return False
 
+
 class PyobjContext(object):
     module = pyobj_property("Module")
     cls = pyobj_property("Class")
     instance = pyobj_property("Instance")
 
+
 class PyobjMixin(PyobjContext):
     def obj():
         def fget(self):
@@ -261,6 +290,7 @@
             except AttributeError:
                 self._obj = obj = self._getobj()
                 return obj
+
         def fset(self, value):
             self._obj = value
         return property(fget, fset, None, "underlying python object")
@@ -308,6 +338,7 @@
         assert isinstance(lineno, int)
         return fspath, lineno, modpath
 
+
 class PyCollector(PyobjMixin, pytest.Collector):
 
     def funcnamefilter(self, name):
@@ -358,7 +389,7 @@
         return l
 
     def makeitem(self, name, obj):
-        #assert self.ihook.fspath == self.fspath, self
+        # assert self.ihook.fspath == self.fspath, self
         return self.ihook.pytest_pycollect_makeitem(
             collector=self, name=name, obj=obj)
 
@@ -387,11 +418,12 @@
             add_funcarg_pseudo_fixture_def(self, metafunc, fm)
 
             for callspec in metafunc._calls:
-                subname = "%s[%s]" %(name, callspec.id)
+                subname = "%s[%s]" % (name, callspec.id)
                 yield Function(name=subname, parent=self,
                                callspec=callspec, callobj=funcobj,
                                fixtureinfo=fixtureinfo,
-                               keywords={callspec.id:True})
+                               keywords={callspec.id: True})
+
 
 def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager):
     # this function will transform all collected calls to a functions
@@ -401,7 +433,7 @@
     # XXX we can probably avoid this algorithm  if we modify CallSpec2
     # to directly care for creating the fixturedefs within its methods.
     if not metafunc._calls[0].funcargs:
-        return # this function call does not have direct parametrization
+        return  # this function call does not have direct parametrization
     # collect funcargs of all callspecs into a list of values
     arg2params = {}
     arg2scope = {}
@@ -437,10 +469,11 @@
         if node and argname in node._name2pseudofixturedef:
             arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]]
         else:
-            fixturedef =  FixtureDef(fixturemanager, '', argname,
-                           get_direct_param_fixture_func,
-                           arg2scope[argname],
-                           valuelist, False, False)
+            fixturedef = FixtureDef(
+                fixturemanager, '', argname,
+                get_direct_param_fixture_func,
+                arg2scope[argname],
+                valuelist, False, False)
             arg2fixturedefs[argname] = [fixturedef]
             if node is not None:
                 node._name2pseudofixturedef[argname] = fixturedef
@@ -449,12 +482,14 @@
 def get_direct_param_fixture_func(request):
     return request.param
 
+
 class FuncFixtureInfo:
     def __init__(self, argnames, names_closure, name2fixturedefs):
         self.argnames = argnames
         self.names_closure = names_closure
         self.name2fixturedefs = name2fixturedefs
 
+
 def transfer_markers(funcobj, cls, mod):
     # XXX this should rather be code in the mark plugin or the mark
     # plugin should merge with the python plugin.
@@ -469,6 +504,7 @@
         else:
             pytestmark(funcobj)
 
+
 class Module(pytest.File, PyCollector):
     """ Collector for test classes and functions. """
     def _getobj(self):
@@ -495,9 +531,9 @@
                 "  %s\n"
                 "HINT: remove __pycache__ / .pyc files and/or use a "
                 "unique basename for your test file modules"
-                 % e.args
+                % e.args
             )
-        #print "imported test module", mod
+        # print "imported test module", mod
         self.config.pluginmanager.consider_module(mod)
         return mod
 
@@ -506,7 +542,7 @@
         if setup_module is None:
             setup_module = xunitsetup(self.obj, "setup_module")
         if setup_module is not None:
-            #XXX: nose compat hack, move to nose plugin
+            # XXX: nose compat hack, move to nose plugin
             # if it takes a positional arg, its probably a pytest style one
             # so we pass the current module object
             if inspect.getargspec(setup_module)[0]:
@@ -517,14 +553,13 @@
         if fin is None:
             fin = getattr(self.obj, 'teardown_module', None)
         if fin is not None:
-            #XXX: nose compat hack, move to nose plugin
+            # XXX: nose compat hack, move to nose plugin
             # if it takes a positional arg, it's probably a pytest style one
             # so we pass the current module object
             if inspect.getargspec(fin)[0]:
-                finalizer = lambda: fin(self.obj)
+                self.addfinalizer(lambda: fin(self.obj))
             else:
-                finalizer = fin
-            self.addfinalizer(finalizer)
+                self.addfinalizer(fin)
 
 
 class Class(PyCollector):
@@ -532,7 +567,7 @@
     def collect(self):
         if hasinit(self.obj):
             self.warn("C1", "cannot collect test class %r because it has a "
-                "__init__ constructor" % self.obj.__name__)
+                      "__init__ constructor" % self.obj.__name__)
             return []
         return [self._getcustomclass("Instance")(name="()", parent=self)]
 
@@ -549,6 +584,7 @@
             fin_class = getattr(fin_class, '__func__', fin_class)
             self.addfinalizer(lambda: fin_class(self.obj))
 
+
 class Instance(PyCollector):
     def _getobj(self):
         obj = self.parent.obj()
@@ -562,6 +598,7 @@
         self.obj = self._getobj()
         return self.obj
 
+
 class FunctionMixin(PyobjMixin):
     """ mixin for the code common to Function and Generator.
     """
@@ -610,8 +647,8 @@
         if excinfo.errisinstance(pytest.fail.Exception):
             if not excinfo.value.pytrace:
                 return str(excinfo.value)
-        return super(FunctionMixin, self)._repr_failure_py(excinfo,
-            style=style)
+        return super(FunctionMixin, self)._repr_failure_py(
+            excinfo, style=style)
 
     def repr_failure(self, excinfo, outerr=None):
         assert outerr is None, "XXX outerr usage is deprecated"
@@ -634,13 +671,16 @@
         for i, x in enumerate(self.obj()):
             name, call, args = self.getcallargs(x)
             if not callable(call):
-                raise TypeError("%r yielded non callable test %r" %(self.obj, call,))
+                raise TypeError(
+                    "%r yielded non callable test %r" % (self.obj, call,))
             if name is None:
                 name = "[%d]" % i
             else:
                 name = "['%s']" % name
             if name in seen:
-                raise ValueError("%r generated tests with non-unique name %r" %(self, name))
+                raise ValueError(
+                    "%r generated tests with non-unique name %r"
+                    % (self, name))
             seen[name] = True
             l.append(self.Function(name, self, args=args, callobj=call))
         return l
@@ -665,7 +705,6 @@
             return True
 
 
-
 def fillfixtures(function):
     """ fill missing funcargs for a test function. """
     try:
@@ -690,6 +729,7 @@
 
 _notexists = object()
 
+
 class CallSpec2(object):
     def __init__(self, metafunc):
         self.metafunc = metafunc
@@ -718,7 +758,7 @@
 
     def _checkargnotcontained(self, arg):
         if arg in self.params or arg in self.funcargs:
-            raise ValueError("duplicate %r" %(arg,))
+            raise ValueError("duplicate %r" % (arg,))
 
     def getparam(self, name):
         try:
@@ -734,7 +774,7 @@
 
     def setmulti(self, valtype, argnames, valset, id, keywords, scopenum,
                  param_index):
-        for arg,val in zip(argnames, valset):
+        for arg, val in zip(argnames, valset):
             self._checkargnotcontained(arg)
             getattr(self, valtype)[arg] = val
             self.indices[arg] = param_index
@@ -766,6 +806,7 @@
         """ alias attribute for ``fixturenames`` for pre-2.3 compatibility"""
         return self.fixturenames
 
+
 class Metafunc(FuncargnamesCompatAttr):
     def __init__(self, function, fixtureinfo, config, cls=None, module=None):
         self.config = config
@@ -779,7 +820,7 @@
         self._ids = py.builtin.set()
 
     def parametrize(self, argnames, argvalues, indirect=False, ids=None,
-        scope=None):
+                    scope=None):
         """ Add new invocations to the underlying test function using the list
         of argvalues for the given argnames.  Parametrization is performed
         during the collection phase.  If you need to setup expensive resources
@@ -803,9 +844,9 @@
         :arg ids: list of string ids, or a callable.
             If strings, each is corresponding to the argvalues so that they are
             part of the test id.
-            If callable, it should take one argument (a single argvalue) and return
-            a string or return None. If None, the automatically generated id for that
-            argument will be used.
+            If callable, it should take one argument (a single argvalue)
+            and return a string or return None. If None,
+            the automatically generated id for that argument will be used.
             If no ids are provided they will be generated automatically from
             the argvalues.
 
@@ -841,10 +882,10 @@
             scope = "function"
         scopenum = scopes.index(scope)
         if not indirect:
-            #XXX should we also check for the opposite case?
+            # XXX should we also check for the opposite case?
             for arg in argnames:
                 if arg not in self.fixturenames:
-                    raise ValueError("%r uses no fixture %r" %(
+                    raise ValueError("%r uses no fixture %r" % (
                                      self.function, arg))
         valtype = indirect and "params" or "funcargs"
         idfn = None
@@ -852,7 +893,7 @@
             idfn = ids
             ids = None
         if ids and len(ids) != len(argvalues):
-            raise ValueError('%d tests specified with %d ids' %(
+            raise ValueError('%d tests specified with %d ids' % (
                              len(argvalues), len(ids)))
         if not ids:
             ids = idmaker(argnames, argvalues, idfn)
@@ -861,9 +902,10 @@
             for param_index, valset in enumerate(argvalues):
                 assert len(valset) == len(argnames)
                 newcallspec = callspec.copy(self)
-                newcallspec.setmulti(valtype, argnames, valset, ids[param_index],
-                                     newkeywords.get(param_index, {}), scopenum,
-                                     param_index)
+                newcallspec.setmulti(
+                    valtype, argnames, valset, ids[param_index],
+                    newkeywords.get(param_index, {}), scopenum,
+                    param_index)
                 newcalls.append(newcallspec)
         self._calls = newcalls
 
@@ -880,8 +922,8 @@
         :arg id: used for reporting and identification purposes.  If you
             don't supply an `id` an automatic unique id will be generated.
 
-        :arg param: a parameter which will be exposed to a later fixture function
-            invocation through the ``request.param`` attribute.
+        :arg param: a parameter which will be exposed to a later fixture
+            function invocation through the ``request.param`` attribute.
         """
         assert funcargs is None or isinstance(funcargs, dict)
         if funcargs is not None:
@@ -914,13 +956,15 @@
             pass
     if isinstance(val, (float, int, str, bool, NoneType)):
         return str(val)
-    return str(argname)+str(idx)
+    return str(argname) + str(idx)
+
 
 def _idvalset(idx, valset, argnames, idfn):
     this_id = [_idval(val, argname, idx, idfn)
                for val, argname in zip(valset, argnames)]
     return "-".join(this_id)
 
+
 def idmaker(argnames, argvalues, idfn=None):
     ids = [_idvalset(valindex, valset, argnames, idfn)
            for valindex, valset in enumerate(argvalues)]
@@ -929,10 +973,12 @@
         ids = [str(i) + testid for i, testid in enumerate(ids)]
     return ids
 
+
 def showfixtures(config):
     from _pytest.main import wrap_session
     return wrap_session(config, _showfixtures_main)
 
+
 def _showfixtures_main(config, session):
     session.perform_collect()
     curdir = py.path.local()
@@ -967,12 +1013,12 @@
         if currentmodule != module:
             if not module.startswith("_pytest."):
                 tw.line()
-                tw.sep("-", "fixtures defined from %s" %(module,))
+                tw.sep("-", "fixtures defined from %s" % (module,))
                 currentmodule = module
         if verbose <= 0 and argname[0] == "_":
             continue
         if verbose > 0:
-            funcargspec = "%s -- %s" %(argname, bestrel,)
+            funcargspec = "%s -- %s" % (argname, bestrel,)
         else:
             funcargspec = argname
         tw.line(funcargspec, green=True)
@@ -982,8 +1028,8 @@
             for line in doc.split("\n"):
                 tw.line("    " + line.strip())
         else:
-            tw.line("    %s: no docstring available" %(loc,),
-                red=True)
+            tw.line("    %s: no docstring available" % (loc,), red=True)
+
 
 def getlocation(function, curdir):
     import inspect
@@ -991,10 +1037,11 @@
     lineno = py.builtin._getcode(function).co_firstlineno
     if fn.relto(curdir):
         fn = fn.relto(curdir)
-    return "%s:%d" %(fn, lineno+1)
+    return "%s:%d" % (fn, lineno + 1)
 
 # builtin pytest.raises helper
 
+
 def raises(ExpectedException, *args, **kwargs):
     """ assert that a code block/function call raises @ExpectedException
     and raise a failure exception otherwise.
@@ -1067,7 +1114,7 @@
         frame = sys._getframe(1)
         loc = frame.f_locals.copy()
         loc.update(kwargs)
-        #print "raises frame scope: %r" % frame.f_locals
+        # print "raises frame scope: %r" % frame.f_locals
         try:
             code = py.code.Source(code).compile()
             py.builtin.exec_(code, frame.f_globals, loc)
@@ -1083,6 +1130,7 @@
             return py.code.ExceptionInfo()
     pytest.fail("DID NOT RAISE")
 
+
 class RaisesContext(object):
     def __init__(self, ExpectedException):
         self.ExpectedException = ExpectedException
@@ -1103,11 +1151,13 @@
 #  the basic pytest Function item
 #
 
+
 class Function(FunctionMixin, pytest.Item, FuncargnamesCompatAttr):
     """ a Function Item is responsible for setting up and executing a
     Python test function.
     """
     _genid = None
+
     def __init__(self, name, parent, args=None, config=None,
                  callspec=None, callobj=NOTSET, keywords=None, session=None,
                  fixtureinfo=None):
@@ -1153,7 +1203,7 @@
 
     def _getobj(self):
         name = self.name
-        i = name.find("[") # parametrization
+        i = name.find("[")  # parametrization
         if i != -1:
             name = name[:i]
         return getattr(self.parent.obj, name)
@@ -1178,7 +1228,7 @@
             pass
         else:
             fs, lineno = self._getfslineno()
-            pytest.skip("got empty parameter set, function %s at %s:%d" %(
+            pytest.skip("got empty parameter set, function %s at %s:%d" % (
                 self.function.__name__, fs, lineno))
         super(Function, self).setup()
         fillfixtures(self)
@@ -1190,9 +1240,11 @@
 scope2props["instance"] = scope2props["class"] + ("instance", )
 scope2props["function"] = scope2props["instance"] + ("function", "keywords")
 
+
 def scopeproperty(name=None, doc=None):
     def decoratescope(func):
         scopename = name or func.__name__
+
         def provide(self):
             if func.__name__ in scope2props[self.scope]:
                 return func(self)
@@ -1216,7 +1268,7 @@
         self.fixturename = None
         #: Scope string, one of "function", "cls", "module", "session"
         self.scope = "function"
-        self._funcargs  = {}
+        self._funcargs = {}
         self._fixturedefs = {}
         fixtureinfo = pyfuncitem._fixtureinfo
         self._arg2fixturedefs = fixtureinfo.name2fixturedefs.copy()
@@ -1229,7 +1281,6 @@
         """ underlying collection node (depends on current request scope)"""
         return self._getscopeitem(self.scope)
 
-
     def _getnextfixturedef(self, argname):
         fixturedefs = self._arg2fixturedefs.get(argname, None)
         if fixturedefs is None:
@@ -1237,7 +1288,7 @@
             # getfuncargvalue(argname) usage which was naturally
             # not known at parsing/collection time
             fixturedefs = self._fixturemanager.getfixturedefs(
-                            argname, self._pyfuncitem.parent.nodeid)
+                argname, self._pyfuncitem.parent.nodeid)
             self._arg2fixturedefs[argname] = fixturedefs
         # fixturedefs list is immutable so we maintain a decreasing index
         index = self._arg2index.get(argname, 0) - 1
@@ -1251,7 +1302,6 @@
         """ the pytest config object associated with this request. """
         return self._pyfuncitem.config
 
-
     @scopeproperty()
     def function(self):
         """ test function object if the request has a per-function scope. """
@@ -1282,7 +1332,7 @@
 
     @scopeproperty()
     def fspath(self):
-        """ the file system path of the test module which collected this test. """
+        """ file system path of the test module which collected this test. """
         return self._pyfuncitem.fspath
 
     @property
@@ -1331,7 +1381,8 @@
             if argname not in item.funcargs:
                 item.funcargs[argname] = self.getfuncargvalue(argname)
 
-    def cached_setup(self, setup, teardown=None, scope="module", extrakey=None):
+    def cached_setup(self, setup, teardown=None,
+                     scope="module", extrakey=None):
         """ (deprecated) Return a testing resource managed by ``setup`` &
         ``teardown`` calls.  ``scope`` and ``extrakey`` determine when the
         ``teardown`` function will be called so that subsequent calls to
@@ -1347,7 +1398,7 @@
         :arg extrakey: added to internal caching key of (funcargname, scope).
         """
         if not hasattr(self.config, '_setupcache'):
-            self.config._setupcache = {} # XXX weakref?
+            self.config._setupcache = {}  # XXX weakref?
         cachekey = (self.fixturename, self._getscopeitem(scope), extrakey)
         cache = self.config._setupcache
         try:
@@ -1355,9 +1406,10 @@
         except KeyError:
             __tracebackhide__ = True
             if scopemismatch(self.scope, scope):
-                raise ScopeMismatchError("You tried to access a %r scoped "
-                    "resource with a %r scoped request object" %(
-                    (scope, self.scope)))
+                raise ScopeMismatchError(
+                    "You tried to access a %r scoped "
+                    "resource with a %r scoped request object"
+                    % (scope, self.scope))
             __tracebackhide__ = False
             val = setup()
             cache[cachekey] = val
@@ -1437,10 +1489,11 @@
             if scopemismatch(self.scope, scope):
                 # try to report something helpful
                 lines = subrequest._factorytraceback()
-                raise ScopeMismatchError("You tried to access the %r scoped "
+                raise ScopeMismatchError(
+                    "You tried to access the %r scoped "
                     "fixture %r with a %r scoped request object, "
-                    "involved factories\n%s" %(
-                    (scope, argname, self.scope, "\n".join(lines))))
+                    "involved factories\n%s"
+                    % (scope, argname, self.scope, "\n".join(lines)))
             __tracebackhide__ = False
 
         # clear sys.exc_info before invoking the fixture (python bug?)
@@ -1462,7 +1515,7 @@
             fs, lineno = getfslineno(factory)
             p = self._pyfuncitem.session.fspath.bestrelpath(fs)
             args = inspect.formatargspec(*inspect.getargspec(factory))
-            lines.append("%s:%d:  def %s%s" %(
+            lines.append("%s:%d:  def %s%s" % (
                 p, lineno, factory.__name__, args))
         return lines
 
@@ -1478,7 +1531,7 @@
         return node
 
     def __repr__(self):
-        return "<FixtureRequest for %r>" %(self.node)
+        return "<FixtureRequest for %r>" % (self.node)
 
 
 class SubRequest(FixtureRequest):
@@ -1494,7 +1547,7 @@
         self._fixturedef = fixturedef
         self.addfinalizer = fixturedef.addfinalizer
         self._pyfuncitem = request._pyfuncitem
-        self._funcargs  = request._funcargs
+        self._funcargs = request._funcargs
         self._fixturedefs = request._fixturedefs
         self._arg2fixturedefs = request._arg2fixturedefs
         self._arg2index = request._arg2index
@@ -1512,9 +1565,12 @@
 
 scopes = "session module class function".split()
 scopenum_function = scopes.index("function")
+
+
 def scopemismatch(currentscope, newscope):
     return scopes.index(newscope) > scopes.index(currentscope)
 
+
 class FixtureLookupError(LookupError):
     """ could not return a requested Fixture (missing or invalid). """
     def __init__(self, argname, request, msg=None):
@@ -1530,12 +1586,14 @@
         stack.extend(map(lambda x: x.func, self.fixturestack))
         msg = self.msg
         if msg is not None:
-            stack = stack[:-1] # the last fixture raise an error, let's present
-                               # it at the requesting side
+            # the last fixture raise an error, let's present
+            # it at the requesting side
+            stack = stack[:-1]
+
         for function in stack:
             fspath, lineno = getfslineno(function)
             lines, _ = inspect.getsourcelines(function)
-            addline("file %s, line %s" % (fspath, lineno+1))
+            addline("file %s, line %s" % (fspath, lineno + 1))
             for i, line in enumerate(lines):
                 line = line.rstrip()
                 addline("  " + line)
@@ -1551,10 +1609,12 @@
                 if faclist:
                     available.append(name)
             msg = "fixture %r not found" % (self.argname,)
-            msg += "\n available fixtures: %s" %(", ".join(available),)
+            msg += "\n available fixtures: %s" % (", ".join(available),)
             msg += "\n use 'py.test --fixtures [testpath]' for help on them."
 
-        return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
+        return FixtureLookupErrorRepr(
+            fspath, lineno, tblines, msg, self.argname)
+
 
 class FixtureLookupErrorRepr(TerminalRepr):
     def __init__(self, filename, firstlineno, tblines, errorstring, argname):
@@ -1565,13 +1625,14 @@
         self.argname = argname
 
     def toterminal(self, tw):
-        #tw.line("FixtureLookupError: %s" %(self.argname), red=True)
+        # tw.line("FixtureLookupError: %s" %(self.argname), red=True)
         for tbline in self.tblines:
             tw.line(tbline.rstrip())
         for line in self.errorstring.split("\n"):
             tw.line("        " + line.strip(), red=True)
         tw.line()
-        tw.line("%s:%d" % (self.filename, self.firstlineno+1))
+        tw.line("%s:%d" % (self.filename, self.firstlineno + 1))
+
 
 class FixtureManager:
     """
@@ -1616,10 +1677,11 @@
         self._seenplugins = set()
         self._holderobjseen = set()
         self._arg2finish = {}
-        self._nodeid_and_autousenames = [("", self.config.getini("usefixtures"))]
+        self._nodeid_and_autousenames = [
+            ("", self.config.getini("usefixtures"))
+        ]
         session.config.pluginmanager.register(self, "funcmanage")
 
-
     def getfixtureinfo(self, node, func, cls, funcargs=True):
         if funcargs and not hasattr(node, "nofuncargs"):
             if cls is not None:
@@ -1638,8 +1700,8 @@
                                                               node)
         return FuncFixtureInfo(argnames, names_closure, arg2fixturedefs)
 
-    ### XXX this hook should be called for historic events like pytest_configure
-    ### so that we don't have to do the below pytest_configure hook
+    # XXX this hook should be called for historic events like pytest_configure
+    # so that we don't have to do the below pytest_configure hook
     def pytest_plugin_registered(self, plugin):
         if plugin in self._seenplugins:
             return
@@ -1674,7 +1736,7 @@
             if nodeid.startswith(baseid):
                 if baseid:
                     i = len(baseid)
-                    nextchar = nodeid[i:i+1]
+                    nextchar = nodeid[i:i + 1]
                     if nextchar and nextchar not in ":/":
                         continue
                 autousenames.extend(basenames)
@@ -1693,6 +1755,7 @@
 
         parentid = parentnode.nodeid
         fixturenames_closure = self._getautousenames(parentid)
+
         def merge(otherlist):
             for arg in otherlist:
                 if arg not in fixturenames_closure:
@@ -1715,7 +1778,7 @@
         for argname in metafunc.fixturenames:
             faclist = metafunc._arg2fixturedefs.get(argname)
             if faclist is None:
-                continue # will raise FixtureLookupError at setup time
+                continue  # will raise FixtureLookupError at setup time
             for fixturedef in faclist:
                 if fixturedef.params is not None:
                     metafunc.parametrize(argname, fixturedef.params,
@@ -1789,39 +1852,45 @@
 
 def fail_fixturefunc(fixturefunc, msg):
     fs, lineno = getfslineno(fixturefunc)
-    location = "%s:%s" % (fs, lineno+1)
+    location = "%s:%s" % (fs, lineno + 1)
     source = py.code.Source(fixturefunc)
     pytest.fail(msg + ":\n\n" + str(source.indent()) + "\n" + location,
                 pytrace=False)
 
+
 def call_fixture_func(fixturefunc, request, kwargs, yieldctx):
     if yieldctx:
         if not is_generator(fixturefunc):
-            fail_fixturefunc(fixturefunc,
+            fail_fixturefunc(
+                fixturefunc,
                 msg="yield_fixture requires yield statement in function")
         iter = fixturefunc(**kwargs)
         next = getattr(iter, "__next__", None)
         if next is None:
             next = getattr(iter, "next")
         res = next()
+
         def teardown():
             try:
                 next()
             except StopIteration:
                 pass
             else:
-                fail_fixturefunc(fixturefunc,
+                fail_fixturefunc(
+                    fixturefunc,
                     "yield_fixture function has more than one 'yield'")
         request.addfinalizer(teardown)
     else:
         if is_generator(fixturefunc):
-            fail_fixturefunc(fixturefunc,
+            fail_fixturefunc(
+                fixturefunc,
                 msg="pytest.fixture functions cannot use ``yield``. "
                     "Instead write and return an inner function/generator "
                     "and let the consumer call and iterate over it.")
         res = fixturefunc(**kwargs)
     return res
 
+
 class FixtureDef:
     """ A container for a factory definition. """
     def __init__(self, fixturemanager, baseid, argname, func, scope, params,
@@ -1904,6 +1973,7 @@
         return ("<FixtureDef name=%r scope=%r baseid=%r >" %
                 (self.argname, self.scope, self.baseid))
 
+
 def num_mock_patch_args(function):
     """ return number of arguments used up by mock arguments (if any) """
     patchings = getattr(function, "patchings", None)
@@ -1912,13 +1982,13 @@
     mock = sys.modules.get("mock", sys.modules.get("unittest.mock", None))
     if mock is not None:
         return len([p for p in patchings
-                        if not p.attribute_name and p.new is mock.DEFAULT])
+                    if not p.attribute_name and p.new is mock.DEFAULT])
     return len(patchings)
 
 
 def getfuncargnames(function, startindex=None):
     # XXX merge with main.py's varnames
-    #assert not inspect.isclass(function)
+    # assert not inspect.isclass(function)
     realfunction = function
     while hasattr(realfunction, "__wrapped__"):
         realfunction = realfunction.__wrapped__
@@ -1940,6 +2010,7 @@
 # down to the lower scopes such as to minimize number of "high scope"
 # setups and teardowns
 
+
 def reorder_items(items):
     argkeys_cache = {}
     for scopenum in range(0, scopenum_function):
@@ -1950,15 +2021,16 @@
                 d[item] = keys
     return reorder_items_atscope(items, set(), argkeys_cache, 0)
 
+
 def reorder_items_atscope(items, ignore, argkeys_cache, scopenum):
     if scopenum >= scopenum_function or len(items) < 3:
         return items
     items_done = []
     while 1:
         items_before, items_same, items_other, newignore = \
-                slice_items(items, ignore, argkeys_cache[scopenum])
+            slice_items(items, ignore, argkeys_cache[scopenum])
         items_before = reorder_items_atscope(
-                            items_before, ignore, argkeys_cache,scopenum+1)
+            items_before, ignore, argkeys_cache, scopenum + 1)
         if items_same is None:
             # nothing to reorder in this scope
             assert items_other is None
@@ -1989,7 +2061,7 @@
                     for item in it:
                         argkeys = scoped_argkeys_cache.get(item)
                         if argkeys and slicing_argkey in argkeys and \
-                            slicing_argkey not in ignore:
+                                slicing_argkey not in ignore:
                             items_same.append(item)
                         else:
                             items_other.append(item)
@@ -1998,6 +2070,7 @@
                     return (items_before, items_same, items_other, newignore)
     return items, None, None, None
 
+
 def get_parametrized_fixture_keys(item, scopenum):
     """ return list of keys for all parametrized arguments which match
     the specified scope. """
@@ -2027,6 +2100,7 @@
     if getfixturemarker(meth) is None:
         return meth
 
+
 def getfixturemarker(obj):
     """ return fixturemarker or None if it doesn't exist or raised
     exceptions."""
@@ -2044,6 +2118,8 @@
     'module': Module,
     'function': pytest.Item,
 }
+
+
 def get_scope_node(node, scope):
     cls = scopename2class.get(scope)
     if cls is None:


https://bitbucket.org/hpk42/pytest/commits/95468cc0bb31/
Changeset:   95468cc0bb31
Branch:      flake8-clean
User:        RonnyPfannschmidt
Date:        2015-02-22 13:27:37+00:00
Summary:     missed whitespace in assertion util
Affected #:  1 file

diff -r 509d62feb91604048b1af64ce23b7e1cd563c0c8 -r 95468cc0bb318ead1f108e9d0f15e33bfa3550c9 _pytest/assertion/util.py
--- a/_pytest/assertion/util.py
+++ b/_pytest/assertion/util.py
@@ -57,8 +57,10 @@
         end = start + i
         where = end
         if explanation[end - 1] == '\n':
-            explanation = (explanation[:start] + explanation[start+15:end-1] +
-                           explanation[end+1:])
+            explanation = (
+                explanation[:start] +
+                explanation[start + 15:end - 1] +
+                explanation[end + 1:])
             where -= 17
     return explanation
 
@@ -101,7 +103,7 @@
             stack.append(len(result))
             stackcnt[-1] += 1
             stackcnt.append(0)
-            result.append(u(' +') + u('  ')*(len(stack)-1) + s + line[1:])
+            result.append(u(' +') + u('  ') * (len(stack) - 1) + s + line[1:])
         elif line.startswith('}'):
             stack.pop()
             stackcnt.pop()
@@ -110,7 +112,7 @@
             assert line[0] in ['~', '>']
             stack[-1] += 1
             indent = len(stack) if line.startswith('~') else len(stack) - 1
-            result.append(u('  ')*indent + line[1:])
+            result.append(u('  ') * indent + line[1:])
     assert len(stack) == 1
     return result
 
@@ -125,8 +127,8 @@
 def assertrepr_compare(config, op, left, right):  # noqa too complex
     """Return specialised explanations for some operators/operands"""
     width = 80 - 15 - len(op) - 2  # 15 chars indentation, 1 space around op
-    left_repr = py.io.saferepr(left, maxsize=int(width/2))
-    right_repr = py.io.saferepr(right, maxsize=width-len(left_repr))
+    left_repr = py.io.saferepr(left, maxsize=int(width / 2))
+    right_repr = py.io.saferepr(right, maxsize=width - len(left_repr))
     summary = u('%s %s %s') % (left_repr, op, right_repr)
 
     def issequence(x):
@@ -301,7 +303,7 @@
 def _notin_text(term, text, verbose=False):
     index = text.find(term)
     head = text[:index]
-    tail = text[index+len(term):]
+    tail = text[index + len(term):]
     correct_text = head + tail
     diff = _diff_text(correct_text, text, verbose)
     newdiff = [u('%s is contained here:') % py.io.saferepr(term, maxsize=42)]

Repository URL: https://bitbucket.org/hpk42/pytest/

--

This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.


More information about the pytest-commit mailing list