fix some pep8 issues, more to go ... is there a tool that helps with pep8-ifying?

This commit is contained in:
holger krekel 2012-06-21 11:20:29 +02:00
parent ccc04b9fc4
commit 42d44bfd43
6 changed files with 61 additions and 53 deletions

View File

@ -526,10 +526,13 @@ if __name__ == '__main__':
# example: # example:
def f(): def f():
return 5 return 5
def g(): def g():
return 3 return 3
def h(x): def h(x):
return 'never' return 'never'
check("f() * g() == 5") check("f() * g() == 5")
check("not f()") check("not f()")
check("not (f() and g() or 0)") check("not (f() and g() or 0)")

View File

@ -44,4 +44,3 @@ if sys.version_info >= (2, 6) or (sys.platform.startswith("java")):
from _pytest.assertion.newinterpret import interpret as reinterpret from _pytest.assertion.newinterpret import interpret as reinterpret
else: else:
reinterpret = reinterpret_old reinterpret = reinterpret_old

View File

@ -95,7 +95,8 @@ class AssertionRewritingHook(object):
finally: finally:
self.session = sess self.session = sess
else: else:
state.trace("matched test file (was specified on cmdline): %r" % (fn,)) state.trace("matched test file (was specified on cmdline): %r" %
(fn,))
# The requested module looks like a test file, so rewrite it. This is # The requested module looks like a test file, so rewrite it. This is
# the most magical part of the process: load the source, rewrite the # the most magical part of the process: load the source, rewrite the
# asserts, and load the rewritten source. We also cache the rewritten # asserts, and load the rewritten source. We also cache the rewritten
@ -121,14 +122,14 @@ class AssertionRewritingHook(object):
# because we're in a zip file. # because we're in a zip file.
write = False write = False
elif e == errno.EACCES: elif e == errno.EACCES:
state.trace("read only directory: %r" % (fn_pypath.dirname,)) state.trace("read only directory: %r" % fn_pypath.dirname)
write = False write = False
else: else:
raise raise
cache_name = fn_pypath.basename[:-3] + PYC_TAIL cache_name = fn_pypath.basename[:-3] + PYC_TAIL
pyc = os.path.join(cache_dir, cache_name) pyc = os.path.join(cache_dir, cache_name)
# Notice that even if we're in a read-only directory, I'm going to check # Notice that even if we're in a read-only directory, I'm going
# for a cached pyc. This may not be optimal... # to check for a cached pyc. This may not be optimal...
co = _read_pyc(fn_pypath, pyc) co = _read_pyc(fn_pypath, pyc)
if co is None: if co is None:
state.trace("rewriting %r" % (fn,)) state.trace("rewriting %r" % (fn,))
@ -160,10 +161,11 @@ class AssertionRewritingHook(object):
return sys.modules[name] return sys.modules[name]
def _write_pyc(co, source_path, pyc): def _write_pyc(co, source_path, pyc):
# Technically, we don't have to have the same pyc format as (C)Python, since # Technically, we don't have to have the same pyc format as
# these "pycs" should never be seen by builtin import. However, there's # (C)Python, since these "pycs" should never be seen by builtin
# little reason deviate, and I hope sometime to be able to use # import. However, there's little reason deviate, and I hope
# imp.load_compiled to load them. (See the comment in load_module above.) # sometime to be able to use imp.load_compiled to load them. (See
# the comment in load_module above.)
mtime = int(source_path.mtime()) mtime = int(source_path.mtime())
try: try:
fp = open(pyc, "wb") fp = open(pyc, "wb")
@ -240,9 +242,8 @@ def _read_pyc(source, pyc):
except EnvironmentError: except EnvironmentError:
return None return None
# Check for invalid or out of date pyc file. # Check for invalid or out of date pyc file.
if (len(data) != 8 or if (len(data) != 8 or data[:4] != imp.get_magic() or
data[:4] != imp.get_magic() or struct.unpack("<l", data[4:])[0] != mtime):
struct.unpack("<l", data[4:])[0] != mtime):
return None return None
co = marshal.load(fp) co = marshal.load(fp)
if not isinstance(co, types.CodeType): if not isinstance(co, types.CodeType):
@ -280,35 +281,35 @@ def _call_reprcompare(ops, results, expls, each_obj):
unary_map = { unary_map = {
ast.Not : "not %s", ast.Not: "not %s",
ast.Invert : "~%s", ast.Invert: "~%s",
ast.USub : "-%s", ast.USub: "-%s",
ast.UAdd : "+%s" ast.UAdd: "+%s"
} }
binop_map = { binop_map = {
ast.BitOr : "|", ast.BitOr: "|",
ast.BitXor : "^", ast.BitXor: "^",
ast.BitAnd : "&", ast.BitAnd: "&",
ast.LShift : "<<", ast.LShift: "<<",
ast.RShift : ">>", ast.RShift: ">>",
ast.Add : "+", ast.Add: "+",
ast.Sub : "-", ast.Sub: "-",
ast.Mult : "*", ast.Mult: "*",
ast.Div : "/", ast.Div: "/",
ast.FloorDiv : "//", ast.FloorDiv: "//",
ast.Mod : "%%", # escaped for string formatting ast.Mod: "%%", # escaped for string formatting
ast.Eq : "==", ast.Eq: "==",
ast.NotEq : "!=", ast.NotEq: "!=",
ast.Lt : "<", ast.Lt: "<",
ast.LtE : "<=", ast.LtE: "<=",
ast.Gt : ">", ast.Gt: ">",
ast.GtE : ">=", ast.GtE: ">=",
ast.Pow : "**", ast.Pow: "**",
ast.Is : "is", ast.Is: "is",
ast.IsNot : "is not", ast.IsNot: "is not",
ast.In : "in", ast.In: "in",
ast.NotIn : "not in" ast.NotIn: "not in"
} }
@ -341,7 +342,7 @@ class AssertionRewriter(ast.NodeVisitor):
lineno = 0 lineno = 0
for item in mod.body: for item in mod.body:
if (expect_docstring and isinstance(item, ast.Expr) and if (expect_docstring and isinstance(item, ast.Expr) and
isinstance(item.value, ast.Str)): isinstance(item.value, ast.Str)):
doc = item.value.s doc = item.value.s
if "PYTEST_DONT_REWRITE" in doc: if "PYTEST_DONT_REWRITE" in doc:
# The module has disabled assertion rewriting. # The module has disabled assertion rewriting.
@ -462,7 +463,8 @@ class AssertionRewriter(ast.NodeVisitor):
body.append(raise_) body.append(raise_)
# Clear temporary variables by setting them to None. # Clear temporary variables by setting them to None.
if self.variables: if self.variables:
variables = [ast.Name(name, ast.Store()) for name in self.variables] variables = [ast.Name(name, ast.Store())
for name in self.variables]
clear = ast.Assign(variables, ast.Name("None", ast.Load())) clear = ast.Assign(variables, ast.Name("None", ast.Load()))
self.statements.append(clear) self.statements.append(clear)
# Fix line numbers. # Fix line numbers.
@ -548,7 +550,8 @@ class AssertionRewriter(ast.NodeVisitor):
new_kwarg, expl = self.visit(call.kwargs) new_kwarg, expl = self.visit(call.kwargs)
arg_expls.append("**" + expl) arg_expls.append("**" + expl)
expl = "%s(%s)" % (func_expl, ', '.join(arg_expls)) expl = "%s(%s)" % (func_expl, ', '.join(arg_expls))
new_call = ast.Call(new_func, new_args, new_kwargs, new_star, new_kwarg) new_call = ast.Call(new_func, new_args, new_kwargs,
new_star, new_kwarg)
res = self.assign(new_call) res = self.assign(new_call)
res_expl = self.explanation_param(self.display(res)) res_expl = self.explanation_param(self.display(res))
outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl) outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)

View File

@ -116,9 +116,7 @@ def assertrepr_compare(op, left, right):
excinfo = py.code.ExceptionInfo() excinfo = py.code.ExceptionInfo()
explanation = ['(pytest_assertion plugin: representation of ' explanation = ['(pytest_assertion plugin: representation of '
'details failed. Probably an object has a faulty __repr__.)', 'details failed. Probably an object has a faulty __repr__.)',
str(excinfo) str(excinfo)]
]
if not explanation: if not explanation:
return None return None

View File

@ -133,8 +133,10 @@ class HookProxy:
def __init__(self, fspath, config): def __init__(self, fspath, config):
self.fspath = fspath self.fspath = fspath
self.config = config self.config = config
def __getattr__(self, name): def __getattr__(self, name):
hookmethod = getattr(self.config.hook, name) hookmethod = getattr(self.config.hook, name)
def call_matching_hooks(**kwargs): def call_matching_hooks(**kwargs):
plugins = self.config._getmatchingplugins(self.fspath) plugins = self.config._getmatchingplugins(self.fspath)
return hookmethod.pcall(plugins, **kwargs) return hookmethod.pcall(plugins, **kwargs)
@ -143,8 +145,9 @@ class HookProxy:
def compatproperty(name): def compatproperty(name):
def fget(self): def fget(self):
return getattr(pytest, name) return getattr(pytest, name)
return property(fget, None, None, return property(fget, None, None,
"deprecated attribute %r, use pytest.%s" % (name,name)) "deprecated attribute %r, use pytest.%s" % (name, name))
class Node(object): class Node(object):
""" base class for all Nodes in the collection tree. """ base class for all Nodes in the collection tree.
@ -184,7 +187,8 @@ class Node(object):
return cls return cls
def __repr__(self): def __repr__(self):
return "<%s %r>" %(self.__class__.__name__, getattr(self, 'name', None)) return "<%s %r>" %(self.__class__.__name__,
getattr(self, 'name', None))
# methods for ordering nodes # methods for ordering nodes
@property @property
@ -201,8 +205,8 @@ class Node(object):
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, Node): if not isinstance(other, Node):
return False return False
return self.__class__ == other.__class__ and \ return (self.__class__ == other.__class__ and
self.name == other.name and self.parent == other.parent self.name == other.name and self.parent == other.parent)
def __ne__(self, other): def __ne__(self, other):
return not self == other return not self == other
@ -371,7 +375,8 @@ class Session(FSCollector):
def __init__(self, config): def __init__(self, config):
super(Session, self).__init__(py.path.local(), parent=None, super(Session, self).__init__(py.path.local(), parent=None,
config=config, session=self) config=config, session=self)
assert self.config.pluginmanager.register(self, name="session", prepend=True) assert self.config.pluginmanager.register(
self, name="session", prepend=True)
self._testsfailed = 0 self._testsfailed = 0
self.shouldstop = False self.shouldstop = False
self.trace = config.trace.root.get("collection") self.trace = config.trace.root.get("collection")
@ -457,7 +462,7 @@ class Session(FSCollector):
if path.check(dir=1): if path.check(dir=1):
assert not names, "invalid arg %r" %(arg,) assert not names, "invalid arg %r" %(arg,)
for path in path.visit(fil=lambda x: x.check(file=1), for path in path.visit(fil=lambda x: x.check(file=1),
rec=self._recurse, bf=True, sort=True): rec=self._recurse, bf=True, sort=True):
for x in self._collectfile(path): for x in self._collectfile(path):
yield x yield x
else: else:
@ -469,13 +474,13 @@ class Session(FSCollector):
ihook = self.gethookproxy(path) ihook = self.gethookproxy(path)
if not self.isinitpath(path): if not self.isinitpath(path):
if ihook.pytest_ignore_collect(path=path, config=self.config): if ihook.pytest_ignore_collect(path=path, config=self.config):
return () return ()
return ihook.pytest_collect_file(path=path, parent=self) return ihook.pytest_collect_file(path=path, parent=self)
def _recurse(self, path): def _recurse(self, path):
ihook = self.gethookproxy(path.dirpath()) ihook = self.gethookproxy(path.dirpath())
if ihook.pytest_ignore_collect(path=path, config=self.config): if ihook.pytest_ignore_collect(path=path, config=self.config):
return return
for pat in self._norecursepatterns: for pat in self._norecursepatterns:
if path.check(fnmatch=pat): if path.check(fnmatch=pat):
return False return False

View File

@ -77,4 +77,4 @@ rsyncdirs=tox.ini pytest.py _pytest testing
python_files=test_*.py *_test.py python_files=test_*.py *_test.py
python_classes=Test Acceptance python_classes=Test Acceptance
python_functions=test python_functions=test
pep8ignore = E401 E225 E261 E128 E124 pep8ignore = E401 E225 E261 E128 E124 E302