Fix flake8 in features branch

This commit is contained in:
Bruno Oliveira 2017-07-17 21:16:14 -03:00
parent 4fd92ef9ba
commit 7b1870a94e
13 changed files with 61 additions and 54 deletions

View File

@ -36,4 +36,4 @@ MARK_PARAMETERSET_UNPACKING = RemovedInPytest4Warning(
"Applying marks directly to parameters is deprecated," "Applying marks directly to parameters is deprecated,"
" please use pytest.param(..., marks=...) instead.\n" " please use pytest.param(..., marks=...) instead.\n"
"For more details, see: https://docs.pytest.org/en/latest/parametrize.html" "For more details, see: https://docs.pytest.org/en/latest/parametrize.html"
) )

View File

@ -8,6 +8,7 @@ from operator import attrgetter
from .compat import imap from .compat import imap
from .deprecated import MARK_INFO_ATTRIBUTE, MARK_PARAMETERSET_UNPACKING from .deprecated import MARK_INFO_ATTRIBUTE, MARK_PARAMETERSET_UNPACKING
def alias(name, warning=None): def alias(name, warning=None):
getter = attrgetter(name) getter = attrgetter(name)
@ -351,6 +352,7 @@ class MarkDecorator:
mark = Mark(self.name, args, kwargs) mark = Mark(self.name, args, kwargs)
return self.__class__(self.mark.combined_with(mark)) return self.__class__(self.mark.combined_with(mark))
def get_unpacked_marks(obj): def get_unpacked_marks(obj):
""" """
obtain the unpacked marks that are stored on a object obtain the unpacked marks that are stored on a object

View File

@ -281,7 +281,10 @@ class PyCollector(PyobjMixin, main.Collector):
obj = safe_getattr(obj, '__func__', False) obj = safe_getattr(obj, '__func__', False)
if obj is False: if obj is False:
# Python 2.6 wraps in a different way that we won't try to handle # Python 2.6 wraps in a different way that we won't try to handle
self.warn(code="C2", message="cannot collect static method %r because it is not a function (always the case in Python 2.6)" % name) msg = "cannot collect static method %r because " \
"it is not a function (always the case in Python 2.6)"
self.warn(
code="C2", message=msg % name)
return False return False
return ( return (
safe_getattr(obj, "__call__", False) and fixtures.getfixturemarker(obj) is None safe_getattr(obj, "__call__", False) and fixtures.getfixturemarker(obj) is None
@ -1510,6 +1513,7 @@ class ApproxNonIterable(object):
# the basic pytest Function item # the basic pytest Function item
# #
class Function(FunctionMixin, main.Item, fixtures.FuncargnamesCompatAttr): class Function(FunctionMixin, main.Item, fixtures.FuncargnamesCompatAttr):
""" a Function Item is responsible for setting up and executing a """ a Function Item is responsible for setting up and executing a
Python test function. Python test function.

View File

@ -9,6 +9,7 @@ import _pytest._code
# builtin pytest.approx helper # builtin pytest.approx helper
class ApproxBase(object): class ApproxBase(object):
""" """
Provide shared utilities for making approximate comparisons between numbers Provide shared utilities for making approximate comparisons between numbers
@ -26,8 +27,8 @@ class ApproxBase(object):
def __eq__(self, actual): def __eq__(self, actual):
return all( return all(
a == self._approx_scalar(x) a == self._approx_scalar(x)
for a, x in self._yield_comparisons(actual)) for a, x in self._yield_comparisons(actual))
__hash__ = None __hash__ = None
@ -138,7 +139,7 @@ class ApproxMapping(ApproxBase):
def __repr__(self): def __repr__(self):
return "approx({0!r})".format(dict( return "approx({0!r})".format(dict(
(k, self._approx_scalar(v)) (k, self._approx_scalar(v))
for k,v in self.expected.items())) for k, v in self.expected.items()))
def __eq__(self, actual): def __eq__(self, actual):
if set(actual.keys()) != set(self.expected.keys()): if set(actual.keys()) != set(self.expected.keys()):
@ -241,7 +242,7 @@ class ApproxScalar(ApproxBase):
absolute tolerance or a relative tolerance, depending on what the user absolute tolerance or a relative tolerance, depending on what the user
specified or which would be larger. specified or which would be larger.
""" """
set_default = lambda x, default: x if x is not None else default def set_default(x, default): return x if x is not None else default
# Figure out what the absolute tolerance should be. ``self.abs`` is # Figure out what the absolute tolerance should be. ``self.abs`` is
# either None or a value specified by the user. # either None or a value specified by the user.
@ -274,7 +275,6 @@ class ApproxScalar(ApproxBase):
return max(relative_tolerance, absolute_tolerance) return max(relative_tolerance, absolute_tolerance)
def approx(expected, rel=None, abs=None, nan_ok=False): def approx(expected, rel=None, abs=None, nan_ok=False):
""" """
Assert that two numbers (or two sets of numbers) are equal to each other Assert that two numbers (or two sets of numbers) are equal to each other
@ -574,7 +574,7 @@ def raises(expected_exception, *args, **kwargs):
frame = sys._getframe(1) frame = sys._getframe(1)
loc = frame.f_locals.copy() loc = frame.f_locals.copy()
loc.update(kwargs) loc.update(kwargs)
#print "raises frame scope: %r" % frame.f_locals # print "raises frame scope: %r" % frame.f_locals
try: try:
code = _pytest._code.Source(code).compile() code = _pytest._code.Source(code).compile()
py.builtin.exec_(code, frame.f_globals, loc) py.builtin.exec_(code, frame.f_globals, loc)
@ -593,6 +593,7 @@ def raises(expected_exception, *args, **kwargs):
raises.Exception = fail.Exception raises.Exception = fail.Exception
class RaisesContext(object): class RaisesContext(object):
def __init__(self, expected_exception, message, match_expr): def __init__(self, expected_exception, message, match_expr):
self.expected_exception = expected_exception self.expected_exception = expected_exception

View File

@ -144,10 +144,10 @@ class TestTraceback_f_g_h(object):
xyz() xyz()
""") """)
try: try:
exec (source.compile()) exec(source.compile())
except NameError: except NameError:
tb = _pytest._code.ExceptionInfo().traceback tb = _pytest._code.ExceptionInfo().traceback
print (tb[-1].getsource()) print(tb[-1].getsource())
s = str(tb[-1].getsource()) s = str(tb[-1].getsource())
assert s.startswith("def xyz():\n try:") assert s.startswith("def xyz():\n try:")
assert s.strip().endswith("except somenoname:") assert s.strip().endswith("except somenoname:")
@ -341,7 +341,7 @@ def test_excinfo_errisinstance():
def test_excinfo_no_sourcecode(): def test_excinfo_no_sourcecode():
try: try:
exec ("raise ValueError()") exec("raise ValueError()")
except ValueError: except ValueError:
excinfo = _pytest._code.ExceptionInfo() excinfo = _pytest._code.ExceptionInfo()
s = str(excinfo.traceback[-1]) s = str(excinfo.traceback[-1])
@ -431,7 +431,7 @@ class TestFormattedExcinfo(object):
def excinfo_from_exec(self, source): def excinfo_from_exec(self, source):
source = _pytest._code.Source(source).strip() source = _pytest._code.Source(source).strip()
try: try:
exec (source.compile()) exec(source.compile())
except KeyboardInterrupt: except KeyboardInterrupt:
raise raise
except: except:
@ -471,7 +471,7 @@ class TestFormattedExcinfo(object):
pr = FormattedExcinfo() pr = FormattedExcinfo()
co = compile("raise ValueError()", "", "exec") co = compile("raise ValueError()", "", "exec")
try: try:
exec (co) exec(co)
except ValueError: except ValueError:
excinfo = _pytest._code.ExceptionInfo() excinfo = _pytest._code.ExceptionInfo()
repr = pr.repr_excinfo(excinfo) repr = pr.repr_excinfo(excinfo)
@ -486,7 +486,7 @@ a = 1
raise ValueError() raise ValueError()
""", "", "exec") """, "", "exec")
try: try:
exec (co) exec(co)
except ValueError: except ValueError:
excinfo = _pytest._code.ExceptionInfo() excinfo = _pytest._code.ExceptionInfo()
repr = pr.repr_excinfo(excinfo) repr = pr.repr_excinfo(excinfo)
@ -992,7 +992,7 @@ raise ValueError()
tw = TWMock() tw = TWMock()
r.toterminal(tw) r.toterminal(tw)
for line in tw.lines: for line in tw.lines:
print (line) print(line)
assert tw.lines[0] == "" assert tw.lines[0] == ""
assert tw.lines[1] == " def f():" assert tw.lines[1] == " def f():"
assert tw.lines[2] == "> g()" assert tw.lines[2] == "> g()"
@ -1040,7 +1040,7 @@ raise ValueError()
tw = TWMock() tw = TWMock()
r.toterminal(tw) r.toterminal(tw)
for line in tw.lines: for line in tw.lines:
print (line) print(line)
assert tw.lines[0] == "" assert tw.lines[0] == ""
assert tw.lines[1] == " def f():" assert tw.lines[1] == " def f():"
assert tw.lines[2] == " try:" assert tw.lines[2] == " try:"

View File

@ -170,12 +170,12 @@ class TestSourceParsingAndCompiling(object):
def test_compile(self): def test_compile(self):
co = _pytest._code.compile("x=3") co = _pytest._code.compile("x=3")
d = {} d = {}
exec (co, d) exec(co, d)
assert d['x'] == 3 assert d['x'] == 3
def test_compile_and_getsource_simple(self): def test_compile_and_getsource_simple(self):
co = _pytest._code.compile("x=3") co = _pytest._code.compile("x=3")
exec (co) exec(co)
source = _pytest._code.Source(co) source = _pytest._code.Source(co)
assert str(source) == "x=3" assert str(source) == "x=3"
@ -342,8 +342,7 @@ def test_getstartingblock_multiline():
self.source = _pytest._code.Frame(frame).statement self.source = _pytest._code.Frame(frame).statement
x = A('x', x = A('x',
'y' 'y',
,
'z') 'z')
l = [i for i in x.source.lines if i.strip()] l = [i for i in x.source.lines if i.strip()]

View File

@ -9,6 +9,7 @@ from decimal import Decimal
from fractions import Fraction from fractions import Fraction
inf, nan = float('inf'), float('nan') inf, nan = float('inf'), float('nan')
class MyDocTestRunner(doctest.DocTestRunner): class MyDocTestRunner(doctest.DocTestRunner):
def __init__(self): def __init__(self):
@ -37,8 +38,8 @@ class TestApprox(object):
# Dictionaries aren't ordered, so we need to check both orders. # Dictionaries aren't ordered, so we need to check both orders.
assert repr(approx({'a': 1.0, 'b': 2.0})) in ( assert repr(approx({'a': 1.0, 'b': 2.0})) in (
"approx({{'a': 1.0 {pm} {tol1}, 'b': 2.0 {pm} {tol2}}})".format(pm=plus_minus, tol1=tol1, tol2=tol2), "approx({{'a': 1.0 {pm} {tol1}, 'b': 2.0 {pm} {tol2}}})".format(pm=plus_minus, tol1=tol1, tol2=tol2),
"approx({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})".format(pm=plus_minus, tol1=tol1, tol2=tol2), "approx({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})".format(pm=plus_minus, tol1=tol1, tol2=tol2),
) )
def test_operator_overloading(self): def test_operator_overloading(self):
@ -218,11 +219,11 @@ class TestApprox(object):
def test_expecting_nan(self): def test_expecting_nan(self):
examples = [ examples = [
(eq, nan, nan), (eq, nan, nan),
(eq, -nan, -nan), (eq, -nan, -nan),
(eq, nan, -nan), (eq, nan, -nan),
(ne, 0.0, nan), (ne, 0.0, nan),
(ne, inf, nan), (ne, inf, nan),
] ]
for op, a, x in examples: for op, a, x in examples:
# Nothing is equal to NaN by default. # Nothing is equal to NaN by default.
@ -266,10 +267,10 @@ class TestApprox(object):
def test_complex(self): def test_complex(self):
within_1e6 = [ within_1e6 = [
( 1.000001 + 1.0j, 1.0 + 1.0j), (1.000001 + 1.0j, 1.0 + 1.0j),
(1.0 + 1.000001j, 1.0 + 1.0j), (1.0 + 1.000001j, 1.0 + 1.0j),
(-1.000001 + 1.0j, -1.0 + 1.0j), (-1.000001 + 1.0j, -1.0 + 1.0j),
(1.0 - 1.000001j, 1.0 - 1.0j), (1.0 - 1.000001j, 1.0 - 1.0j),
] ]
for a, x in within_1e6: for a, x in within_1e6:
assert a == approx(x, rel=5e-6, abs=0) assert a == approx(x, rel=5e-6, abs=0)
@ -289,7 +290,7 @@ class TestApprox(object):
def test_list_wrong_len(self): def test_list_wrong_len(self):
assert [1, 2] != approx([1]) assert [1, 2] != approx([1])
assert [1, 2] != approx([1,2,3]) assert [1, 2] != approx([1, 2, 3])
def test_tuple(self): def test_tuple(self):
actual = (1 + 1e-7, 2 + 1e-8) actual = (1 + 1e-7, 2 + 1e-8)
@ -303,7 +304,7 @@ class TestApprox(object):
def test_tuple_wrong_len(self): def test_tuple_wrong_len(self):
assert (1, 2) != approx((1,)) assert (1, 2) != approx((1,))
assert (1, 2) != approx((1,2,3)) assert (1, 2) != approx((1, 2, 3))
def test_dict(self): def test_dict(self):
actual = {'a': 1 + 1e-7, 'b': 2 + 1e-8} actual = {'a': 1 + 1e-7, 'b': 2 + 1e-8}
@ -344,7 +345,7 @@ class TestApprox(object):
np = pytest.importorskip('numpy') np = pytest.importorskip('numpy')
a12 = np.array([[1, 2]]) a12 = np.array([[1, 2]])
a21 = np.array([[1],[2]]) a21 = np.array([[1], [2]])
assert a12 != approx(a21) assert a12 != approx(a21)
assert a21 != approx(a12) assert a21 != approx(a12)

View File

@ -151,7 +151,7 @@ class TestClass(object):
pass pass
""") """)
result = testdir.runpytest() result = testdir.runpytest()
if sys.version_info < (2,7): if sys.version_info < (2, 7):
# in 2.6, the code to handle static methods doesn't work # in 2.6, the code to handle static methods doesn't work
result.stdout.fnmatch_lines([ result.stdout.fnmatch_lines([
"*collected 0 items*", "*collected 0 items*",

View File

@ -119,6 +119,7 @@ class TestNewAPI(object):
testdir.runpytest() testdir.runpytest()
assert testdir.tmpdir.join('custom_cache_dir').isdir() assert testdir.tmpdir.join('custom_cache_dir').isdir()
def test_cache_reportheader(testdir): def test_cache_reportheader(testdir):
testdir.makepyfile(""" testdir.makepyfile("""
def test_hello(): def test_hello():

View File

@ -83,14 +83,14 @@ class TestCaptureManager(object):
assert outerr == ("", "") assert outerr == ("", "")
outerr = capman.suspendcapture() outerr = capman.suspendcapture()
assert outerr == ("", "") assert outerr == ("", "")
print ("hello") print("hello")
out, err = capman.suspendcapture() out, err = capman.suspendcapture()
if method == "no": if method == "no":
assert old == (sys.stdout, sys.stderr, sys.stdin) assert old == (sys.stdout, sys.stderr, sys.stdin)
else: else:
assert not out assert not out
capman.resumecapture() capman.resumecapture()
print ("hello") print("hello")
out, err = capman.suspendcapture() out, err = capman.suspendcapture()
if method != "no": if method != "no":
assert out == "hello\n" assert out == "hello\n"
@ -305,7 +305,7 @@ class TestLoggingInteraction(object):
assert 0 assert 0
""") """)
for optargs in (('--capture=sys',), ('--capture=fd',)): for optargs in (('--capture=sys',), ('--capture=fd',)):
print (optargs) print(optargs)
result = testdir.runpytest_subprocess(p, *optargs) result = testdir.runpytest_subprocess(p, *optargs)
s = result.stdout.str() s = result.stdout.str()
result.stdout.fnmatch_lines([ result.stdout.fnmatch_lines([
@ -331,7 +331,7 @@ class TestLoggingInteraction(object):
assert 0 assert 0
""") """)
for optargs in (('--capture=sys',), ('--capture=fd',)): for optargs in (('--capture=sys',), ('--capture=fd',)):
print (optargs) print(optargs)
result = testdir.runpytest_subprocess(p, *optargs) result = testdir.runpytest_subprocess(p, *optargs)
s = result.stdout.str() s = result.stdout.str()
result.stdout.fnmatch_lines([ result.stdout.fnmatch_lines([
@ -879,7 +879,7 @@ class TestStdCapture(object):
def test_capturing_readouterr(self): def test_capturing_readouterr(self):
with self.getcapture() as cap: with self.getcapture() as cap:
print ("hello world") print("hello world")
sys.stderr.write("hello error\n") sys.stderr.write("hello error\n")
out, err = cap.readouterr() out, err = cap.readouterr()
assert out == "hello world\n" assert out == "hello world\n"
@ -890,7 +890,7 @@ class TestStdCapture(object):
def test_capturing_readouterr_unicode(self): def test_capturing_readouterr_unicode(self):
with self.getcapture() as cap: with self.getcapture() as cap:
print ("hx\xc4\x85\xc4\x87") print("hx\xc4\x85\xc4\x87")
out, err = cap.readouterr() out, err = cap.readouterr()
assert out == py.builtin._totext("hx\xc4\x85\xc4\x87\n", "utf8") assert out == py.builtin._totext("hx\xc4\x85\xc4\x87\n", "utf8")
@ -905,7 +905,7 @@ class TestStdCapture(object):
def test_reset_twice_error(self): def test_reset_twice_error(self):
with self.getcapture() as cap: with self.getcapture() as cap:
print ("hello") print("hello")
out, err = cap.readouterr() out, err = cap.readouterr()
pytest.raises(ValueError, cap.stop_capturing) pytest.raises(ValueError, cap.stop_capturing)
assert out == "hello\n" assert out == "hello\n"
@ -919,7 +919,7 @@ class TestStdCapture(object):
sys.stderr.write("world") sys.stderr.write("world")
sys.stdout = capture.CaptureIO() sys.stdout = capture.CaptureIO()
sys.stderr = capture.CaptureIO() sys.stderr = capture.CaptureIO()
print ("not seen") print("not seen")
sys.stderr.write("not seen\n") sys.stderr.write("not seen\n")
out, err = cap.readouterr() out, err = cap.readouterr()
assert out == "hello" assert out == "hello"
@ -929,9 +929,9 @@ class TestStdCapture(object):
def test_capturing_error_recursive(self): def test_capturing_error_recursive(self):
with self.getcapture() as cap1: with self.getcapture() as cap1:
print ("cap1") print("cap1")
with self.getcapture() as cap2: with self.getcapture() as cap2:
print ("cap2") print("cap2")
out2, err2 = cap2.readouterr() out2, err2 = cap2.readouterr()
out1, err1 = cap1.readouterr() out1, err1 = cap1.readouterr()
assert out1 == "cap1\n" assert out1 == "cap1\n"
@ -961,9 +961,9 @@ class TestStdCapture(object):
assert sys.stdin is old assert sys.stdin is old
def test_stdin_nulled_by_default(self): def test_stdin_nulled_by_default(self):
print ("XXX this test may well hang instead of crashing") print("XXX this test may well hang instead of crashing")
print ("XXX which indicates an error in the underlying capturing") print("XXX which indicates an error in the underlying capturing")
print ("XXX mechanisms") print("XXX mechanisms")
with self.getcapture(): with self.getcapture():
pytest.raises(IOError, "sys.stdin.read()") pytest.raises(IOError, "sys.stdin.read()")

View File

@ -321,9 +321,9 @@ class TestConftestVisibility(object):
# use value from parent dir's # use value from parent dir's
""")) """))
print ("created directory structure:") print("created directory structure:")
for x in testdir.tmpdir.visit(): for x in testdir.tmpdir.visit():
print (" " + x.relto(testdir.tmpdir)) print(" " + x.relto(testdir.tmpdir))
return { return {
"runner": runner, "runner": runner,

View File

@ -791,11 +791,10 @@ def test_legacy_transfer():
def fake_method(self): def fake_method(self):
pass pass
transfer_markers(fake_method, FakeClass, FakeModule) transfer_markers(fake_method, FakeClass, FakeModule)
# legacy marks transfer smeared # legacy marks transfer smeared
assert fake_method.nofun assert fake_method.nofun
assert fake_method.fun assert fake_method.fun
# pristine marks dont transfer # pristine marks dont transfer
assert fake_method.pytestmark == [pytest.mark.fun.mark] assert fake_method.pytestmark == [pytest.mark.fun.mark]

View File

@ -226,7 +226,7 @@ class BaseFunctionalTests(object):
raise ValueError(42) raise ValueError(42)
""") """)
reps = rec.getreports("pytest_runtest_logreport") reps = rec.getreports("pytest_runtest_logreport")
print (reps) print(reps)
for i in range(2): for i in range(2):
assert reps[i].nodeid.endswith("test_method") assert reps[i].nodeid.endswith("test_method")
assert reps[i].passed assert reps[i].passed
@ -253,7 +253,7 @@ class BaseFunctionalTests(object):
assert True assert True
""") """)
reps = rec.getreports("pytest_runtest_logreport") reps = rec.getreports("pytest_runtest_logreport")
print (reps) print(reps)
assert len(reps) == 3 assert len(reps) == 3
# #
assert reps[0].nodeid.endswith("test_method") assert reps[0].nodeid.endswith("test_method")