3 new commits in pytest: https://bitbucket.org/hpk42/pytest/commits/eb3382c1cf50/ Changeset: eb3382c1cf50 Branch: flake8-clean User: RonnyPfannschmidt Date: 2015-02-22 16:10:00+00:00 Summary: flake8 clean testing/cx_freeze Affected #: 4 files
diff -r 7a1d32a342c0433d9c30889fa04d59fbd11d3557 -r eb3382c1cf5061a70396445727c1ca8102be95f3 testing/cx_freeze/runtests_script.py --- a/testing/cx_freeze/runtests_script.py +++ b/testing/cx_freeze/runtests_script.py @@ -6,4 +6,4 @@ if __name__ == '__main__': import sys import pytest - sys.exit(pytest.main()) \ No newline at end of file + sys.exit(pytest.main()) diff -r 7a1d32a342c0433d9c30889fa04d59fbd11d3557 -r eb3382c1cf5061a70396445727c1ca8102be95f3 testing/cx_freeze/runtests_setup.py --- a/testing/cx_freeze/runtests_setup.py +++ b/testing/cx_freeze/runtests_setup.py @@ -1,5 +1,6 @@ """ -Sample setup.py script that generates an executable with pytest runner embedded. +Sample setup.py script that generates an executable +with pytest runner embedded. """ if __name__ == '__main__': from cx_Freeze import setup, Executable @@ -8,8 +9,8 @@ setup( name="runtests", version="0.1", - description="exemple of how embedding py.test into an executable using cx_freeze", + description="exemple of how embedding py.test " + "into an executable using cx_freeze", executables=[Executable("runtests_script.py")], options={"build_exe": {'includes': pytest.freeze_includes()}}, ) - diff -r 7a1d32a342c0433d9c30889fa04d59fbd11d3557 -r eb3382c1cf5061a70396445727c1ca8102be95f3 testing/cx_freeze/tests/test_trivial.py --- a/testing/cx_freeze/tests/test_trivial.py +++ b/testing/cx_freeze/tests/test_trivial.py @@ -2,5 +2,6 @@ def test_upper(): assert 'foo'.upper() == 'FOO' + def test_lower(): - assert 'FOO'.lower() == 'foo' \ No newline at end of file + assert 'FOO'.lower() == 'foo' diff -r 7a1d32a342c0433d9c30889fa04d59fbd11d3557 -r eb3382c1cf5061a70396445727c1ca8102be95f3 testing/cx_freeze/tox_run.py --- a/testing/cx_freeze/tox_run.py +++ b/testing/cx_freeze/tox_run.py @@ -12,4 +12,4 @@ executable = os.path.join(os.getcwd(), 'build', 'runtests_script') if sys.platform.startswith('win'): executable += '.exe' - sys.exit(os.system('%s tests' % executable)) \ No newline at end of file + sys.exit(os.system('%s tests' % executable)) https://bitbucket.org/hpk42/pytest/commits/60e93163ce6f/ Changeset: 60e93163ce6f Branch: flake8-clean User: RonnyPfannschmidt Date: 2015-02-22 18:01:22+00:00 Summary: flake8 clean testing Affected #: 31 files diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/acceptance_test.py --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -1,4 +1,6 @@ -import py, pytest +import py +import pytest + class TestGeneralUsage: def test_config_error(self, testdir): @@ -65,14 +67,13 @@ print("---unconfigure") """) result = testdir.runpytest("-s", "asd") - assert result.ret == 4 # EXIT_USAGEERROR + assert result.ret == 4 # EXIT_USAGEERROR result.stderr.fnmatch_lines(["ERROR: file not found*asd"]) result.stdout.fnmatch_lines([ "*---configure", "*---unconfigure", ]) - def test_config_preparse_plugin_option(self, testdir): testdir.makepyfile(pytest_xyz=""" def pytest_addoption(parser): @@ -110,7 +111,7 @@ testdir.makepyfile(import_fails="import does_not_work") result = testdir.runpytest(p) result.stdout.fnmatch_lines([ - #XXX on jython this fails: "> import import_fails", + # XXX on jython this fails: "> import import_fails", "E ImportError: No module named *does_not_work*", ]) assert result.ret == 1 @@ -121,7 +122,7 @@ result = testdir.runpytest(p1, p2) assert result.ret result.stderr.fnmatch_lines([ - "*ERROR: not found:*%s" %(p2.basename,) + "*ERROR: not found:*%s" % (p2.basename,) ]) def test_issue486_better_reporting_on_conftest_load_failure(self, testdir): @@ -137,7 +138,6 @@ *ERROR*could not load*conftest.py* """) - def test_early_skip(self, testdir): testdir.mkdir("xyz") testdir.makeconftest(""" @@ -245,7 +245,7 @@ if path.basename.startswith("conftest"): return MyCollector(path, parent) """) - result = testdir.runpytest(c.basename+"::"+"xyz") + result = testdir.runpytest(c.basename + "::" + "xyz") assert result.ret == 0 result.stdout.fnmatch_lines([ "*1 pass*", @@ -300,7 +300,7 @@ x """) result = testdir.runpytest() - assert result.ret == 3 # internal error + assert result.ret == 3 # internal error result.stderr.fnmatch_lines([ "INTERNAL*pytest_configure*", "INTERNAL*x*", @@ -308,7 +308,8 @@ assert 'sessionstarttime' not in result.stderr.str() @pytest.mark.parametrize('lookfor', ['test_fun.py', 'test_fun.py::test_a']) - def test_issue134_report_syntaxerror_when_collecting_member(self, testdir, lookfor): + def test_issue134_report_syntaxerror_when_collecting_member( + self, testdir, lookfor): testdir.makepyfile(test_fun=""" def test_a(): pass @@ -546,6 +547,7 @@ "*1 failed*", ]) + class TestDurations: source = """ import time @@ -583,12 +585,12 @@ result = testdir.runpytest("--durations=0") assert result.ret == 0 for x in "123": - for y in 'call',: #'setup', 'call', 'teardown': + for y in 'call', : # 'setup', 'call', 'teardown': for line in result.stdout.lines: if ("test_%s" % x) in line and y in line: break else: - raise AssertionError("not found %s %s" % (x,y)) + raise AssertionError("not found %s %s" % (x, y)) def test_with_deselected(self, testdir): testdir.makepyfile(self.source) @@ -621,6 +623,7 @@ def test_2(): time.sleep(frag) """ + def test_setup_function(self, testdir): testdir.makepyfile(self.source) result = testdir.runpytest("--durations=10") @@ -631,4 +634,3 @@ * setup *test_1* * call *test_1* """) - diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/conftest.py --- a/testing/conftest.py +++ b/testing/conftest.py @@ -1,9 +1,10 @@ import pytest import sys +import os +import py pytest_plugins = "pytester", -import os, py class LsofFdLeakChecker(object): def get_open_files(self): @@ -18,7 +19,10 @@ def _parse_lsof_output(self, out): def isopen(line): return line.startswith('f') and ( - "deleted" not in line and 'mem' not in line and "txt" not in line and 'cwd' not in line) + "deleted" not in line and + 'mem' not in line and + "txt" not in line and + 'cwd' not in line) open_files = [] @@ -34,9 +38,11 @@ def pytest_addoption(parser): - parser.addoption('--lsof', - action="store_true", dest="lsof", default=False, - help=("run FD checks if lsof is available")) + parser.addoption( + '--lsof', + action="store_true", dest="lsof", default=False, + help=("run FD checks if lsof is available")) + def pytest_runtest_setup(item): config = item.config @@ -48,12 +54,13 @@ except py.process.cmdexec.Error: pass -#def pytest_report_header(): + +# ef pytest_report_header(): # return "pid: %s" % os.getpid() def check_open_files(config): lines2 = config._fd_leak_checker.get_open_files() - new_fds = set([t[0] for t in lines2]) - set([t[0] for t in config._openfiles]) + new_fds = set(t[0] for t in lines2) - set(t[0] for t in config._openfiles) open_files = [t for t in lines2 if t[0] in new_fds] if open_files: error = [] @@ -66,6 +73,7 @@ error.append(error[0]) raise AssertionError("\n".join(error)) + def pytest_runtest_teardown(item, __multicall__): item.config._basedir.chdir() if hasattr(item.config, '_openfiles'): @@ -84,6 +92,7 @@ 'python3.5': r'C:\Python35\python.exe', } + def getexecutable(name, cache={}): try: return cache[name] @@ -92,16 +101,18 @@ if executable: if name == "jython": import subprocess - popen = subprocess.Popen([str(executable), "--version"], + popen = subprocess.Popen( + [str(executable), "--version"], universal_newlines=True, stderr=subprocess.PIPE) out, err = popen.communicate() if not err or "2.5" not in err: executable = None if "2.5.2" in err: - executable = None # http://bugs.jython.org/issue1790 + executable = None # http://bugs.jython.org/issue1790 cache[name] = executable return executable + @pytest.fixture(params=['python2.6', 'python2.7', 'python3.3', "python3.4", 'pypy', 'pypy3']) def anypython(request): diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_argcomplete.py --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -1,8 +1,10 @@ from __future__ import with_statement -import py, pytest +import py +import pytest # test for _argcomplete but not specific for any application + def equal_with_bash(prefix, ffc, fc, out=None): res = ffc(prefix) res_bash = set(fc(prefix)) @@ -14,15 +16,18 @@ out.write(' bash - python: %s\n' % (res_bash - set(res))) return retval + # copied from argcomplete.completers as import from there # also pulls in argcomplete.__init__ which opens filedescriptor 9 # this gives an IOError at the end of testrun def _wrapcall(*args, **kargs): try: - if py.std.sys.version_info > (2,7): - return py.std.subprocess.check_output(*args,**kargs).decode().splitlines() + if py.std.sys.version_info > (2, 7): + return py.std.subprocess.check_output( + *args, **kargs).decode().splitlines() if 'stdout' in kargs: - raise ValueError('stdout argument not allowed, it will be overridden.') + raise ValueError( + 'stdout argument not allowed, it will be overridden.') process = py.std.subprocess.Popen( stdout=py.std.subprocess.PIPE, *args, **kargs) output, unused_err = process.communicate() @@ -36,9 +41,11 @@ except py.std.subprocess.CalledProcessError: return [] + class FilesCompleter(object): 'File completer class, optionally takes a list of allowed extensions' - def __init__(self,allowednames=(),directories=True): + + def __init__(self, allowednames=(), directories=True): # Fix if someone passes in a string instead of a list if type(allowednames) is str: allowednames = [allowednames] @@ -50,25 +57,31 @@ completion = [] if self.allowednames: if self.directories: - files = _wrapcall(['bash','-c', - "compgen -A directory -- '{p}'".format(p=prefix)]) - completion += [ f + '/' for f in files] + files = _wrapcall( + ['bash', '-c', + "compgen -A directory -- '{p}'".format(p=prefix)]) + completion += [f + '/' for f in files] for x in self.allowednames: - completion += _wrapcall(['bash', '-c', - "compgen -A file -X '!*.{0}' -- '{p}'".format(x,p=prefix)]) + completion += _wrapcall( + ['bash', '-c', + "compgen -A file -X '!*.{0}' -- '{p}'".format( + x, p=prefix)]) else: - completion += _wrapcall(['bash', '-c', - "compgen -A file -- '{p}'".format(p=prefix)]) + completion += _wrapcall( + ['bash', '-c', + "compgen -A file -- '{p}'".format(p=prefix)]) - anticomp = _wrapcall(['bash', '-c', - "compgen -A directory -- '{p}'".format(p=prefix)]) + anticomp = _wrapcall( + ['bash', '-c', + "compgen -A directory -- '{p}'".format(p=prefix)]) - completion = list( set(completion) - set(anticomp)) + completion = list(set(completion) - set(anticomp)) if self.directories: completion += [f + '/' for f in anticomp] return completion + # the following barfs with a syntax error on py2.5 # @pytest.mark.skipif("sys.version_info < (2,6)") class TestArgComplete: diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_assertion.py --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -2,7 +2,8 @@ import sys import textwrap -import py, pytest +import py +import pytest import _pytest.assertion as plugin from _pytest.assertion import reinterpret from _pytest.assertion import util @@ -15,6 +16,7 @@ def mock_config(): class Config(object): verbose = False + def getoption(self, name): if name == 'verbose': return self.verbose @@ -25,6 +27,7 @@ def interpret(expr): return reinterpret.reinterpret(expr, py.code.Frame(sys._getframe(1))) + class TestBinReprIntegration: pytestmark = needsnewassert @@ -48,6 +51,7 @@ "*test_check*PASS*", ]) + def callequal(left, right, verbose=False): config = mock_config() config.verbose = verbose @@ -68,15 +72,15 @@ assert '+ eggs' in diff def test_text_skipping(self): - lines = callequal('a'*50 + 'spam', 'a'*50 + 'eggs') + lines = callequal('a' * 50 + 'spam', 'a' * 50 + 'eggs') assert 'Skipping' in lines[1] for line in lines: - assert 'a'*50 not in line + assert 'a' * 50 not in line def test_text_skipping_verbose(self): - lines = callequal('a'*50 + 'spam', 'a'*50 + 'eggs', verbose=True) - assert '- ' + 'a'*50 + 'spam' in lines - assert '+ ' + 'a'*50 + 'eggs' in lines + lines = callequal('a' * 50 + 'spam', 'a' * 50 + 'eggs', verbose=True) + assert '- ' + 'a' * 50 + 'spam' in lines + assert '+ ' + 'a' * 50 + 'eggs' in lines def test_multiline_text_diff(self): left = 'foo\nspam\nbar' @@ -123,7 +127,8 @@ def test_iterable_full_diff(self, left, right, expected): """Test the full diff assertion failure explanation. - When verbose is False, then just a -v notice to get the diff is rendered, + When verbose is False, + then just a -v notice to get the diff is rendered, when verbose is True, then ndiff of the pprint is returned. """ expl = callequal(left, right, verbose=False) @@ -194,9 +199,9 @@ assert len(expl) > 1 def test_list_tuples(self): - expl = callequal([], [(1,2)]) + expl = callequal([], [(1, 2)]) assert len(expl) > 1 - expl = callequal([(1,2)], []) + expl = callequal([(1, 2)], []) assert len(expl) > 1 def test_list_bad_repr(self): @@ -350,6 +355,7 @@ *1 failed* """) + @needsnewassert def test_rewritten(testdir): testdir.makepyfile(""" @@ -358,11 +364,13 @@ """) assert testdir.runpytest().ret == 0 + def test_reprcompare_notin(mock_config): detail = plugin.pytest_assertrepr_compare( mock_config, 'not in', 'foo', 'aaafoobbb')[1:] assert detail == ["'foo' is contained here:", ' aaafoobbb', '? +++'] + @needsnewassert def test_pytest_assertrepr_compare_integration(testdir): testdir.makepyfile(""" @@ -380,6 +388,7 @@ "*E*50*", ]) + @needsnewassert def test_sequence_comparison_uses_repr(testdir): testdir.makepyfile(""" @@ -415,7 +424,6 @@ "*truncated*use*-vv*", ]) - result = testdir.runpytest('-vv') result.stdout.fnmatch_lines([ "*- 197", @@ -437,12 +445,12 @@ b_conftest.write('def pytest_assertrepr_compare(): return ["summary b"]') result = testdir.runpytest() result.stdout.fnmatch_lines([ - '*def test_base():*', - '*E*assert 1 == 2*', - '*def test_a():*', - '*E*assert summary a*', - '*def test_b():*', - '*E*assert summary b*']) + '*def test_base():*', + '*E*assert 1 == 2*', + '*def test_a():*', + '*E*assert summary a*', + '*def test_b():*', + '*E*assert summary b*']) def test_assertion_options(testdir): @@ -464,6 +472,7 @@ result = testdir.runpytest(*opt) assert "3 == 4" not in result.stdout.str() + def test_old_assert_mode(testdir): testdir.makepyfile(""" def test_in_old_mode(): @@ -472,6 +481,7 @@ result = testdir.runpytest("--assert=reinterp") assert result.ret == 0 + def test_triple_quoted_string_issue113(testdir): testdir.makepyfile(""" def test_hello(): @@ -483,6 +493,7 @@ ]) assert 'SyntaxError' not in result.stdout.str() + def test_traceback_failure(testdir): p1 = testdir.makepyfile(""" def g(): @@ -503,7 +514,7 @@ "", "*test_*.py:6: ", "_ _ _ *", - #"", + # "", " def f(x):", "> assert x == g()", "E assert 3 == 2", @@ -512,7 +523,7 @@ "*test_traceback_failure.py:4: AssertionError" ]) - result = testdir.runpytest(p1) # "auto" + result = testdir.runpytest(p1) # "auto" result.stdout.fnmatch_lines([ "*test_traceback_failure.py F", "====* FAILURES *====", @@ -531,7 +542,11 @@ "*test_traceback_failure.py:4: AssertionError" ]) -@pytest.mark.skipif("sys.version_info < (2,5) or '__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')" ) + +@pytest.mark.skipif( + "sys.version_info < (2,5) or " + "'__pypy__' in sys.builtin_module_names or " + "sys.platform.startswith('java')") def test_warn_missing(testdir): testdir.makepyfile("") result = testdir.run(sys.executable, "-OO", "-m", "pytest", "-h") @@ -543,6 +558,7 @@ "*WARNING*assert statements are not executed*", ]) + def test_recursion_source_decode(testdir): testdir.makepyfile(""" def test_something(): @@ -557,15 +573,16 @@ <Module*> """) + def test_AssertionError_message(testdir): testdir.makepyfile(""" def test_hello(): x,y = 1,2 - assert 0, (x,y) + assert 0, (x, y) """) result = testdir.runpytest() result.stdout.fnmatch_lines(""" *def test_hello* - *assert 0, (x,y)* + *assert 0, (x, y)* *AssertionError: (1, 2)* """) diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_assertrewrite.py --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -4,20 +4,20 @@ import zipfile import py import pytest - -ast = pytest.importorskip("ast") -if sys.platform.startswith("java"): - # XXX should be xfail - pytest.skip("assert rewrite does currently not work on jython") - +import ast from _pytest.assertion import util from _pytest.assertion.rewrite import rewrite_asserts, PYTEST_TAG def setup_module(mod): + if sys.platform.startswith("java"): + # XXX should be xfail + pytest.skip("assert rewrite does currently not work on jython") + mod._old_reprcompare = util._reprcompare py.code._reprcompare = None + def teardown_module(mod): util._reprcompare = mod._old_reprcompare del mod._old_reprcompare @@ -28,6 +28,7 @@ rewrite_asserts(tree) return tree + def getmsg(f, extra_ns=None, must_pass=False): """Rewrite the assertions in f, run it, and get the failure message.""" src = '\n'.join(py.code.Code(f).source().lines) @@ -102,21 +103,28 @@ def f(): assert False assert getmsg(f) == "assert False" + def f(): f = False assert f assert getmsg(f) == "assert False" + def f(): assert a_global # noqa - assert getmsg(f, {"a_global" : False}) == "assert False" + + assert getmsg(f, {"a_global": False}) == "assert False" + def f(): assert sys == 42 - assert getmsg(f, {"sys" : sys}) == "assert sys == 42" + assert getmsg(f, {"sys": sys}) == "assert sys == 42" + def f(): assert cls == 42 # noqa + class X(object): pass - assert getmsg(f, {"cls" : X}) == "assert cls == 42" + + assert getmsg(f, {"cls": X}) == "assert cls == 42" def test_assert_already_has_message(self): def f(): @@ -189,45 +197,57 @@ f = g = False assert f and g assert getmsg(f) == "assert (False)" + def f(): f = True g = False assert f and g assert getmsg(f) == "assert (True and False)" + def f(): f = False g = True assert f and g assert getmsg(f) == "assert (False)" + def f(): f = g = False assert f or g assert getmsg(f) == "assert (False or False)" + def f(): f = g = False assert not f and not g getmsg(f, must_pass=True) + def x(): return False + def f(): assert x() and x() - assert getmsg(f, {"x" : x}) == "assert (x())" + + assert getmsg(f, {"x": x}) == "assert (x())" + def f(): assert False or x() - assert getmsg(f, {"x" : x}) == "assert (False or x())" + assert getmsg(f, {"x": x}) == "assert (False or x())" + def f(): assert 1 in {} and 2 in {} assert getmsg(f) == "assert (1 in {})" + def f(): x = 1 y = 2 - assert x in {1 : None} and y in {} + assert x in {1: None} and y in {} assert getmsg(f) == "assert (1 in {1: None} and 2 in {})" + def f(): f = True g = False assert f or g getmsg(f, must_pass=True) + def f(): f = g = h = lambda: True assert f() and g() and h() @@ -237,6 +257,7 @@ def f(): assert True or explode # noqa getmsg(f, must_pass=True) + def f(): x = 1 assert x == 1 or x == 2 @@ -247,14 +268,17 @@ x = True assert not x assert getmsg(f) == "assert not True" + def f(): x = 0 assert ~x + 1 assert getmsg(f) == "assert (~0 + 1)" + def f(): x = 3 assert -x + x assert getmsg(f) == "assert (-3 + 3)" + def f(): x = 0 assert +x + x @@ -266,6 +290,7 @@ y = -1 assert x + y assert getmsg(f) == "assert (1 + -1)" + def f(): assert not 5 % 4 assert getmsg(f) == "assert not (5 % 4)" @@ -274,6 +299,7 @@ def f(): assert 3 % 2 and False assert getmsg(f) == "assert ((3 % 2) and False)" + def f(): assert False or 4 % 2 assert getmsg(f) == "assert (False or (4 % 2))" @@ -281,39 +307,48 @@ def test_call(self): def g(a=42, *args, **kwargs): return False - ns = {"g" : g} + ns = {"g": g} + def f(): assert g() assert getmsg(f, ns) == """assert g()""" + def f(): assert g(1) assert getmsg(f, ns) == """assert g(1)""" + def f(): assert g(1, 2) assert getmsg(f, ns) == """assert g(1, 2)""" + def f(): assert g(1, g=42) assert getmsg(f, ns) == """assert g(1, g=42)""" + def f(): assert g(1, 3, g=23) assert getmsg(f, ns) == """assert g(1, 3, g=23)""" + def f(): seq = [1, 2, 3] assert g(*seq) assert getmsg(f, ns) == """assert g(*[1, 2, 3])""" + def f(): x = "a" - assert g(**{x : 2}) + assert g(**{x: 2}) assert getmsg(f, ns) == """assert g(**{'a': 2})""" def test_attribute(self): class X(object): g = 3 - ns = {"x" : X} + ns = {"x": X} + def f(): - assert not x.g # noqa + assert not x.g # noqa assert getmsg(f, ns) == """assert not 3 + where 3 = x.g""" + def f(): x.a = False # noqa assert x.a # noqa @@ -324,18 +359,22 @@ a, b = range(2) assert b < a assert getmsg(f) == """assert 1 < 0""" + def f(): a, b, c = range(3) assert a > b > c assert getmsg(f) == """assert 0 > 1""" + def f(): a, b, c = range(3) assert a < b > c assert getmsg(f) == """assert 1 > 2""" + def f(): a, b, c = range(3) assert a < b <= c getmsg(f, must_pass=True) + def f(): a, b, c = range(3) assert a < b @@ -353,12 +392,15 @@ def my_reprcompare(op, left, right): return "42" monkeypatch.setattr(util, "_reprcompare", my_reprcompare) + def f(): assert 42 < 3 assert getmsg(f) == "assert 42" + def my_reprcompare(op, left, right): return "%s %s %s" % (left, op, right) monkeypatch.setattr(util, "_reprcompare", my_reprcompare) + def f(): assert 1 < 3 < 5 <= 4 < 7 assert getmsg(f) == "assert 5 <= 4" @@ -368,10 +410,13 @@ class A(object): def __nonzero__(self): raise ValueError(42) + def __lt__(self, other): return A() + def __repr__(self): return "<MY42 object>" + def myany(x): return False assert myany(A() < 0) @@ -434,7 +479,7 @@ def test_readonly(self, testdir): sub = testdir.mkdir("testing") sub.join("test_readonly.py").write( - py.builtin._totext(""" + py.builtin._totext(""" def test_rewritten(): assert "@py_builtins" in globals() """).encode("utf-8"), "wb") @@ -461,8 +506,8 @@ import pytest def test_optimized(): "hello" - assert test_optimized.__doc__ is None""" - ) + assert test_optimized.__doc__ is None + """) p = py.path.local.make_numbered_dir(prefix="runpytest-", keep=None, rootdir=testdir.tmpdir) tmp = "--basetemp=%s" % p @@ -486,19 +531,22 @@ assert testdir.runpytest().ret == 0 def test_translate_newlines(self, testdir): - content = "def test_rewritten():\r\n assert '@py_builtins' in globals()" + content = ("def test_rewritten():\r\n" + " assert '@py_builtins' in globals()") b = content.encode("utf-8") testdir.tmpdir.join("test_newlines.py").write(b, "wb") assert testdir.runpytest().ret == 0 - @pytest.mark.skipif(sys.version_info < (3,3), - reason='packages without __init__.py not supported on python 2') + @pytest.mark.skipif( + sys.version_info < (3, 3), + reason='packages without __init__.py not supported on python 2') def test_package_without__init__py(self, testdir): pkg = testdir.mkdir('a_package_without_init_py') pkg.join('module.py').ensure() testdir.makepyfile("import a_package_without_init_py.module") assert testdir.runpytest().ret == 0 + class TestAssertionRewriteHookDetails(object): def test_loader_is_package_false_for_module(self, testdir): testdir.makepyfile(test_fun=""" @@ -581,6 +629,7 @@ source_path = tmpdir.ensure("source.py") pycpath = tmpdir.join("pyc").strpath assert _write_pyc(state, [1], source_path.stat(), pycpath) + def open(*args): e = IOError() e.errno = 10 @@ -607,7 +656,8 @@ def test_load_resource(): assert isinstance(__loader__, AssertionRewritingHook) - res = pkg_resources.resource_string(__name__, 'resource.txt') + res = pkg_resources.resource_string( + __name__, 'resource.txt') res = res.decode('ascii') assert res == 'Load me please.' """, diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_capture.py --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -44,10 +44,10 @@ os.write(fd, tobytes(obj)) - def StdCaptureFD(out=True, err=True, in_=True): return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture) + def StdCapture(out=True, err=True, in_=True): return capture.MultiCapture(out, err, in_, Capture=capture.SysCapture) @@ -66,8 +66,9 @@ assert parser._groups[0].options[0].default == "sys" @needsosdup - @pytest.mark.parametrize("method", - ['no', 'sys', pytest.mark.skipif('not hasattr(os, "dup")', 'fd')]) + @pytest.mark.parametrize("method", [ + 'no', 'sys', + pytest.mark.skipif('not hasattr(os, "dup")', 'fd')]) def test_capturing_basic_api(self, method): capouter = StdCaptureFD() old = sys.stdout, sys.stderr, sys.stdin @@ -107,7 +108,7 @@ @pytest.mark.parametrize("method", ['fd', 'sys']) def test_capturing_unicode(testdir, method): - if hasattr(sys, "pypy_version_info") and sys.pypy_version_info < (2,2): + if hasattr(sys, "pypy_version_info") and sys.pypy_version_info < (2, 2): pytest.xfail("does not work on pypy < 2.2") if sys.version_info >= (3, 0): obj = "'b\u00f6y'" @@ -229,7 +230,7 @@ "setup func1*", "in func1*", "teardown func1*", - #"*1 fixture failure*" + # "*1 fixture failure*" ]) def test_teardown_capturing_final(self, testdir): @@ -615,6 +616,7 @@ if not f.closed: f.close() + @needsosdup def test_dupfile(tmpfile): flist = [] @@ -633,12 +635,14 @@ assert "01234" in repr(s) tmpfile.close() + def test_dupfile_on_bytesio(): io = py.io.BytesIO() f = capture.safe_text_dupfile(io, "wb") f.write("hello") assert io.getvalue() == b"hello" + def test_dupfile_on_textio(): io = py.io.TextIO() f = capture.safe_text_dupfile(io, "wb") @@ -961,6 +965,7 @@ capfile2 = cap.err.tmpfile assert capfile2 == capfile + @needsosdup def test_close_and_capture_again(testdir): testdir.makepyfile(""" @@ -980,7 +985,6 @@ """) - @pytest.mark.parametrize('method', ['SysCapture', 'FDCapture']) def test_capturing_and_logging_fundamentals(testdir, method): if method == "StdCaptureFD" and not hasattr(os, 'dup'): diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_collection.py --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -1,7 +1,9 @@ -import pytest, py +import pytest +import py from _pytest.main import Session + class TestCollector: def test_collect_versus_item(self): from pytest import Collector, Item @@ -41,11 +43,11 @@ assert not (fn1 == fn3) assert fn1 != fn3 - for fn in fn1,fn2,fn3: + for fn in fn1, fn2, fn3: assert fn != 3 assert fn != modcol - assert fn != [1,2,3] - assert [1,2,3] != fn + assert fn != [1, 2, 3] + assert [1, 2, 3] != fn assert modcol != fn def test_getparent(self, testdir): @@ -67,7 +69,6 @@ parent = fn.getparent(pytest.Class) assert parent is cls - def test_getcustomfile_roundtrip(self, testdir): hello = testdir.makefile(".xxx", hello="world") testdir.makepyfile(conftest=""" @@ -85,6 +86,7 @@ assert len(nodes) == 1 assert isinstance(nodes[0], pytest.File) + class TestCollectFS: def test_ignored_certain_directories(self, testdir): tmpdir = testdir.tmpdir @@ -116,9 +118,11 @@ rec = testdir.inline_run("xyz123/test_2.py") rec.assertoutcome(failed=1) + class TestCollectPluginHookRelay: def test_pytest_collect_file(self, testdir): wascalled = [] + class Plugin: def pytest_collect_file(self, path, parent): wascalled.append(path) @@ -129,6 +133,7 @@ def test_pytest_collect_directory(self, testdir): wascalled = [] + class Plugin: def pytest_collect_directory(self, path, parent): wascalled.append(path.basename) @@ -138,6 +143,7 @@ assert "hello" in wascalled assert "world" in wascalled + class TestPrunetraceback: def test_collection_error(self, testdir): p = testdir.makepyfile(""" @@ -289,6 +295,7 @@ "*test_x*" ]) + class TestSession: def test_parsearg(self, testdir): p = testdir.makepyfile("def test_func(): pass") @@ -303,11 +310,11 @@ assert rcol.fspath == subdir parts = rcol._parsearg(p.basename) - assert parts[0] == target + assert parts[0] == target assert len(parts) == 1 parts = rcol._parsearg(p.basename + "::test_func") - assert parts[0] == target - assert parts[1] == "test_func" + assert parts[0] == target + assert parts[1] == "test_func" assert len(parts) == 2 def test_collect_topdir(self, testdir): @@ -318,14 +325,13 @@ topdir = testdir.tmpdir rcol = Session(config) assert topdir == rcol.fspath - #rootid = rcol.nodeid - #root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0] - #assert root2 == rcol, rootid + # rootid = rcol.nodeid + # root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0] + # assert root2 == rcol, rootid colitems = rcol.perform_collect([rcol.nodeid], genitems=False) assert len(colitems) == 1 assert colitems[0].fspath == p - def test_collect_protocol_single_function(self, testdir): p = testdir.makepyfile("def test_func(): pass") id = "::".join([p.basename, "test_func"]) @@ -392,7 +398,7 @@ "collector.__class__.__name__ == 'Module'"), ("pytest_pycollect_makeitem", "name == 'test_func'"), ("pytest_collectreport", "report.nodeid.startswith(p.basename)"), - #("pytest_collectreport", + # ("pytest_collectreport", # "report.fspath == %r" % str(rcol.fspath)), ]) @@ -409,7 +415,7 @@ ("pytest_collectstart", "collector.fspath == test_aaa"), ("pytest_pycollect_makeitem", "name == 'test_func'"), ("pytest_collectreport", - "report.nodeid.startswith('aaa/test_aaa.py')"), + "report.nodeid.startswith('aaa/test_aaa.py')"), ]) def test_collect_two_commandline_args(self, testdir): @@ -457,6 +463,7 @@ item, = items assert item.nodeid.endswith("TestClass::()::test_method") + class Test_getinitialnodes: def test_global_file(self, testdir, tmpdir): x = tmpdir.ensure("x.py") @@ -483,6 +490,7 @@ for col in col.listchain(): assert col.config is config + class Test_genitems: def test_check_collect_hashes(self, testdir): p = testdir.makepyfile(""" diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_config.py --- a/testing/test_config.py +++ b/testing/test_config.py @@ -1,7 +1,9 @@ -import py, pytest +import py +import pytest from _pytest.config import getcfg + class TestParseIni: def test_getcfg_and_config(self, testdir, tmpdir): sub = tmpdir.mkdir("sub") @@ -16,7 +18,7 @@ assert config.inicfg['name'] == 'value' def test_getcfg_empty_path(self, tmpdir): - getcfg([''], ['setup.cfg']) #happens on py.test "" + getcfg([''], ['setup.cfg']) # happens on py.test "" def test_append_parse_args(self, testdir, tmpdir, monkeypatch): monkeypatch.setenv('PYTEST_ADDOPTS', '--color no -rs --tb="short"') @@ -29,10 +31,10 @@ assert config.option.reportchars == 's' assert config.option.tbstyle == 'short' assert config.option.verbose - #config = testdir.Config() - #args = [tmpdir,] - #config._preparse(args, addopts=False) - #assert len(args) == 1 + # config = testdir.Config() + # args = [tmpdir,] + # config._preparse(args, addopts=False) + # assert len(args) == 1 def test_tox_ini_wrong_version(self, testdir): testdir.makefile('.ini', tox=""" @@ -78,6 +80,7 @@ result = testdir.runpytest("--confcutdir=.") assert result.ret == 0 + class TestConfigCmdlineParsing: def test_parsing_again_fails(self, testdir): config = testdir.parseconfig() @@ -92,13 +95,14 @@ [pytest] custom = 0 """) - testdir.makefile(".cfg", custom = """ + testdir.makefile(".cfg", custom=""" [pytest] custom = 1 """) config = testdir.parseconfig("-c", "custom.cfg") assert config.getini("custom") == "1" + class TestConfigAPI: def test_config_trace(self, testdir): config = testdir.parseconfig() @@ -131,7 +135,8 @@ def test_config_getvalueorskip(self, testdir): config = testdir.parseconfig() - pytest.raises(pytest.skip.Exception, + pytest.raises( + pytest.skip.Exception, "config.getvalueorskip('hello')") verbose = config.getvalueorskip("verbose") assert verbose == config.option.verbose @@ -263,6 +268,7 @@ assert len(l) == 2 assert l == ["456", "123"] + def test_options_on_small_file_do_not_blow_up(testdir): def runfiletest(opts): reprec = testdir.inline_run(*opts) @@ -279,14 +285,19 @@ ['--traceconfig'], ['-v'], ['-v', '-v']): runfiletest(opts + [path]) + def test_preparse_ordering_with_setuptools(testdir, monkeypatch): pkg_resources = pytest.importorskip("pkg_resources") + def my_iter(name): assert name == "pytest11" + class EntryPoint: name = "mytestplugin" + class dist: pass + def load(self): class PseudoPlugin: x = 42 @@ -301,12 +312,16 @@ plugin = config.pluginmanager.getplugin("mytestplugin") assert plugin.x == 42 + def test_plugin_preparse_prevents_setuptools_loading(testdir, monkeypatch): pkg_resources = pytest.importorskip("pkg_resources") + def my_iter(name): assert name == "pytest11" + class EntryPoint: name = "mytestplugin" + def load(self): assert 0, "should not arrive here" return iter([EntryPoint()]) @@ -315,6 +330,7 @@ plugin = config.pluginmanager.getplugin("mytestplugin") assert plugin == -1 + def test_cmdline_processargs_simple(testdir): testdir.makeconftest(""" def pytest_cmdline_preparse(args): @@ -332,12 +348,14 @@ result = testdir.runpytest("-m", "hello" * 500) assert result.ret == 0 + def test_notify_exception(testdir, capfd): config = testdir.parseconfig() excinfo = pytest.raises(ValueError, "raise ValueError(1)") config.notify_exception(excinfo) out, err = capfd.readouterr() assert "ValueError" in err + class A: def pytest_internalerror(self, excrepr): return True @@ -348,8 +366,9 @@ def test_load_initial_conftest_last_ordering(testdir): - from _pytest.config import get_plugin_manager + from _pytest.config import get_plugin_manager pm = get_plugin_manager() + class My: def pytest_load_initial_conftests(self): pass @@ -360,6 +379,7 @@ assert l[-2] == m.pytest_load_initial_conftests assert l[-3].__module__ == "_pytest.config" + class TestWarning: def test_warn_config(self, testdir): testdir.makeconftest(""" diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_conftest.py --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -1,4 +1,5 @@ -import py, pytest +import py +import pytest from _pytest.config import Conftest @@ -13,11 +14,13 @@ tmpdir.ensure("adir/b/__init__.py") return tmpdir + def ConftestWithSetinitial(path): conftest = Conftest() conftest_setinitial(conftest, [path]) return conftest + def conftest_setinitial(conftest, args, confcutdir=None): class Namespace: def __init__(self): @@ -25,6 +28,7 @@ self.confcutdir = str(confcutdir) conftest.setinitial(Namespace()) + class TestConftestValueAccessGlobal: def test_basic_init(self, basedir): conftest = Conftest() @@ -41,12 +45,13 @@ assert conftest.rget_with_confmod("b", adir.join("b"))[1] == 2 assert len(l) == 2 - def test_immediate_initialiation_and_incremental_are_the_same(self, basedir): + def test_immediate_initialiation_and_incremental_are_the_same(self, + basedir): conftest = Conftest() len(conftest._path2confmods) conftest.getconftestmodules(basedir) snap1 = len(conftest._path2confmods) - #assert len(conftest._path2confmods) == snap1 + 1 + # assert len(conftest._path2confmods) == snap1 + 1 conftest.getconftestmodules(basedir.join('adir')) assert len(conftest._path2confmods) == snap1 + 1 conftest.getconftestmodules(basedir.join('b')) @@ -68,11 +73,12 @@ startdir.ensure("xx", dir=True) conftest = ConftestWithSetinitial(startdir) mod, value = conftest.rget_with_confmod("a", startdir) - assert value == 1.5 + assert value == 1.5 path = py.path.local(mod.__file__) assert path.dirpath() == basedir.join("adir", "b") assert path.purebasename.startswith("conftest") + def test_conftest_in_nonpkg_with_init(tmpdir): tmpdir.ensure("adir-1.0/conftest.py").write("a=1 ; Directory = 3") tmpdir.ensure("adir-1.0/b/conftest.py").write("b=2 ; a = 1.5") @@ -80,6 +86,7 @@ tmpdir.ensure("adir-1.0/__init__.py") ConftestWithSetinitial(tmpdir.join("adir-1.0", "b")) + def test_doubledash_considered(testdir): conf = testdir.mkdir("--option") conf.join("conftest.py").ensure() @@ -88,6 +95,7 @@ l = conftest.getconftestmodules(conf) assert len(l) == 1 + def test_issue151_load_all_conftests(testdir): names = "code proj src".split() for name in names: @@ -99,6 +107,7 @@ d = list(conftest._conftestpath2mod.values()) assert len(d) == len(names) + def test_conftest_global_import(testdir): testdir.makeconftest("x=3") p = testdir.makepyfile(""" @@ -120,6 +129,7 @@ res = testdir.runpython(p) assert res.ret == 0 + def test_conftestcutdir(testdir): conf = testdir.makeconftest("") p = testdir.mkdir("x") @@ -139,6 +149,7 @@ assert len(l) == 1 assert l[0].__file__.startswith(str(conf)) + def test_conftestcutdir_inplace_considered(testdir): conf = testdir.makeconftest("") conftest = Conftest() @@ -147,6 +158,7 @@ assert len(l) == 1 assert l[0].__file__.startswith(str(conf)) + @pytest.mark.parametrize("name", 'test tests whatever .dotdir'.split()) def test_setinitial_conftest_subdirs(testdir, name): sub = testdir.mkdir(name) @@ -154,12 +166,13 @@ conftest = Conftest() conftest_setinitial(conftest, [sub.dirpath()], confcutdir=testdir.tmpdir) if name not in ('whatever', '.dotdir'): - assert subconftest in conftest._conftestpath2mod + assert subconftest in conftest._conftestpath2mod assert len(conftest._conftestpath2mod) == 1 else: - assert subconftest not in conftest._conftestpath2mod + assert subconftest not in conftest._conftestpath2mod assert len(conftest._conftestpath2mod) == 0 + def test_conftest_confcutdir(testdir): testdir.makeconftest("assert 0") x = testdir.mkdir("x") @@ -170,6 +183,7 @@ result = testdir.runpytest("-h", "--confcutdir=%s" % x, x) result.stdout.fnmatch_lines(["*--xyz*"]) + def test_conftest_existing_resultlog(testdir): x = testdir.mkdir("tests") x.join("conftest.py").write(py.code.Source(""" @@ -180,6 +194,7 @@ result = testdir.runpytest("-h", "--resultlog", "result.log") result.stdout.fnmatch_lines(["*--xyz*"]) + def test_conftest_existing_junitxml(testdir): x = testdir.mkdir("tests") x.join("conftest.py").write(py.code.Source(""" @@ -190,11 +205,13 @@ result = testdir.runpytest("-h", "--junitxml", "junit.xml") result.stdout.fnmatch_lines(["*--xyz*"]) + def test_conftest_import_order(testdir, monkeypatch): ct1 = testdir.makeconftest("") sub = testdir.mkdir("sub") ct2 = sub.join("conftest.py") ct2.write("") + def impct(p): return p conftest = Conftest() diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_core.py --- a/testing/test_core.py +++ b/testing/test_core.py @@ -1,5 +1,7 @@ -import pytest, py, os -from _pytest.core import * # noqa +import pytest +import py +import os +from _pytest.core import * # noqa from _pytest.config import get_plugin_manager @@ -11,8 +13,8 @@ def test_preparse_args(self): pluginmanager = PluginManager() - pytest.raises(ImportError, lambda: - pluginmanager.consider_preparse(["xyz", "-p", "hello123"])) + with pytest.raises(ImportError): + pluginmanager.consider_preparse(["xyz", "-p", "hello123"]) def test_plugin_prevent_register(self): pluginmanager = PluginManager() @@ -34,7 +36,8 @@ def test_plugin_double_register(self): pm = PluginManager() pm.register(42, name="abc") - pytest.raises(ValueError, lambda: pm.register(42, name="abc")) + with pytest.raises(ValueError): + pm.register(42, name="abc") def test_plugin_skip(self, testdir, monkeypatch): p = testdir.makepyfile(skipping1=""" @@ -66,11 +69,14 @@ def test_consider_setuptools_instantiation(self, monkeypatch): pkg_resources = pytest.importorskip("pkg_resources") + def my_iter(name): assert name == "pytest11" + class EntryPoint: name = "pytest_mytestplugin" dist = None + def load(self): class PseudoPlugin: x = 42 @@ -84,7 +90,8 @@ assert plugin.x == 42 def test_consider_setuptools_not_installed(self, monkeypatch): - monkeypatch.setitem(py.std.sys.modules, 'pkg_resources', + monkeypatch.setitem( + py.std.sys.modules, 'pkg_resources', py.std.types.ModuleType("pkg_resources")) pluginmanager = PluginManager() pluginmanager.consider_setuptools_entrypoints() @@ -105,8 +112,9 @@ def test_import_plugin_importname(self, testdir): pluginmanager = PluginManager() - pytest.raises(ImportError, 'pluginmanager.import_plugin("qweqwex.y")') - pytest.raises(ImportError, 'pluginmanager.import_plugin("pytest_qweqwx.y")') + pytest.raises(ImportError, pluginmanager.import_plugin, "qweqwex.y") + pytest.raises(ImportError, pluginmanager.import_plugin, + "pytest_qweqwx.y") testdir.syspathinsert() pluginname = "pytest_hello" @@ -123,8 +131,9 @@ def test_import_plugin_dotted_name(self, testdir): pluginmanager = PluginManager() - pytest.raises(ImportError, 'pluginmanager.import_plugin("qweqwex.y")') - pytest.raises(ImportError, 'pluginmanager.import_plugin("pytest_qweqwex.y")') + pytest.raises(ImportError, pluginmanager.import_plugin, "qweqwex.y") + pytest.raises(ImportError, pluginmanager.import_plugin, + "pytest_qweqwex.y") testdir.syspathinsert() testdir.mkpydir("pkg").join("plug.py").write("x=3") @@ -150,7 +159,7 @@ aplugin = testdir.makepyfile(pytest_a="#") pluginmanager = get_plugin_manager() reprec = testdir.make_hook_recorder(pluginmanager) - #syspath.prepend(aplugin.dirpath()) + # syspath.prepend(aplugin.dirpath()) py.std.sys.path.insert(0, str(aplugin.dirpath())) pluginmanager.consider_module(mod) call = reprec.getcall(pluginmanager.hook.pytest_plugin_registered.name) @@ -172,7 +181,9 @@ def test_pm(self): pp = PluginManager() - class A: pass + + class A: + pass a1, a2 = A(), A() pp.register(a1) assert pp.isregistered(a1) @@ -187,7 +198,9 @@ def test_pm_ordering(self): pp = PluginManager() - class A: pass + + class A: + pass a1, a2 = A(), A() pp.register(a1) pp.register(a2, "hello") @@ -207,7 +220,7 @@ assert mod in l pytest.raises(ValueError, "pp.register(mod)") pytest.raises(ValueError, lambda: pp.register(mod)) - #assert not pp.isregistered(mod2) + # assert not pp.isregistered(mod2) assert pp.getplugins() == l def test_canonical_import(self, monkeypatch): @@ -220,6 +233,7 @@ def test_register_mismatch_method(self): pp = get_plugin_manager() + class hello: def pytest_gurgel(self): pass @@ -227,6 +241,7 @@ def test_register_mismatch_arg(self): pp = get_plugin_manager() + class hello: def pytest_configure(self, asd): pass @@ -234,6 +249,7 @@ def test_register(self): pm = get_plugin_manager() + class MyPlugin: pass my = MyPlugin() @@ -251,10 +267,13 @@ def test_listattr(self): plugins = PluginManager() + class api1: x = 41 + class api2: x = 42 + class api3: x = 43 plugins.register(api1()) @@ -266,8 +285,10 @@ def test_hook_tracing(self): pm = get_plugin_manager() saveindent = [] + class api1: x = 41 + def pytest_plugin_registered(self, plugin): saveindent.append(pm.trace.root.indent) raise ValueError(42) @@ -285,6 +306,7 @@ assert pm.trace.root.indent == indent assert saveindent[0] > indent + class TestPytestPluginInteractions: def test_addhooks_conftestplugin(self, testdir): @@ -356,6 +378,7 @@ def test_configure(self, testdir): config = testdir.parseconfig() l = [] + class A: def pytest_configure(self, config): l.append(self) @@ -376,6 +399,7 @@ def test_listattr(self): pluginmanager = PluginManager() + class My2: x = 42 pluginmanager.register(My2()) @@ -391,6 +415,7 @@ class P2: def m(self): return 23 + class P3: def m(self): return 19 @@ -418,12 +443,16 @@ result = testdir.runpython(p) assert result.ret == 0 + def test_varnames(): + def f(x): i = 3 # noqa + class A: def f(self, y): pass + class B(object): def __call__(self, z): pass @@ -431,20 +460,25 @@ assert varnames(A().f) == ('y',) assert varnames(B()) == ('z',) + def test_varnames_default(): def f(x, y=3): pass assert varnames(f) == ("x",) + def test_varnames_class(): class C: def __init__(self, x): pass + class D: pass + assert varnames(C) == ("x",) assert varnames(D) == () + class TestMultiCall: def test_uses_copy_of_methods(self): l = [lambda: 42] @@ -479,6 +513,7 @@ def test_keyword_args(self): def f(x): return x + 1 + class A: def f(self, x, y): return x + y @@ -486,7 +521,7 @@ assert "'x': 23" in repr(multicall) assert "'y': 24" in repr(multicall) reslist = multicall.execute() - assert reslist == [24+23, 24] + assert reslist == [24 + 23, 24] assert "2 results" in repr(multicall) def test_keyword_args_with_defaultargs(self): @@ -514,6 +549,7 @@ def test_call_none_is_no_result(self): def m1(): return 1 + def m2(): return None res = MultiCall([m1, m2], {}, firstresult=True).execute() @@ -523,6 +559,7 @@ def test_hookwrapper(self): l = [] + def m1(): l.append("m1 init") yield None @@ -542,6 +579,7 @@ def test_hookwrapper_order(self): l = [] + def m1(): l.append("m1 init") yield 1 @@ -581,10 +619,10 @@ pluginmanager.register(p3) methods = pluginmanager.listattr('m') assert methods == [p2.m, p3.m, p1.m] - ## listattr keeps a cache and deleting - ## a function attribute requires clearing it - #pluginmanager._listattrcache.clear() - #del P1.m.__dict__['tryfirst'] + # # listattr keeps a cache and deleting + # # a function attribute requires clearing it + # pluginmanager._listattrcache.clear() + # del P1.m.__dict__['tryfirst'] def test_hookwrapper_not_yield(self): def m1(): @@ -617,6 +655,7 @@ hook = pm.hook assert hasattr(hook, 'hello') assert repr(hook.hello).find("hello") != -1 + class Plugin: def hello(self, arg): return arg + 1 @@ -633,6 +672,7 @@ def hello(self, arg): "api hook 1" pm = PluginManager(Api, prefix="he") + class Plugin: def hello(self, argwrong): return arg + 1 @@ -642,6 +682,7 @@ def test_only_kwargs(self): pm = PluginManager() + class Api: def hello(self, arg): "api hook 1" @@ -654,6 +695,7 @@ "api hook 1" hello.firstresult = True pm = PluginManager([Api], "he") + class Plugin: def hello(self, arg): return arg + 1 @@ -661,6 +703,7 @@ res = pm.hook.hello(arg=3) assert res == 4 + class TestTracer: def test_simple(self): from _pytest.core import TagTracer @@ -695,8 +738,9 @@ log("last") assert len(l) == 7 names = [x[:x.rfind(' [')] for x in l] - assert names == ['hello', ' line1', ' line2', - ' line3', ' line4', ' line5', 'last'] + assert names == [ + 'hello', ' line1', ' line2', + ' line3', ' line4', ' line5', 'last'] def test_readable_output_dictargs(self): from _pytest.core import TagTracer @@ -705,8 +749,8 @@ out = rootlogger.format_message(['test'], [1]) assert out == ['1 [test]\n'] - out2= rootlogger.format_message(['test'], ['test', {'a':1}]) - assert out2 ==[ + out2 = rootlogger.format_message(['test'], ['test', {'a': 1}]) + assert out2 == [ 'test [test]\n', ' a: 1\n' ] @@ -716,7 +760,7 @@ rootlogger = TagTracer() log = rootlogger.get("1") log2 = log.get("2") - assert log2.tags == tuple("12") + assert log2.tags == tuple("12") l = [] rootlogger.setprocessor(tuple("12"), lambda *args: l.append(args)) log("not seen") @@ -732,7 +776,6 @@ tags, args = l2[0] assert args == ("seen",) - def test_setmyprocessor(self): from _pytest.core import TagTracer rootlogger = TagTracer() @@ -749,6 +792,7 @@ assert "2" in tags assert args == (42,) + def test_default_markers(testdir): result = testdir.runpytest("--markers") result.stdout.fnmatch_lines([ @@ -756,12 +800,14 @@ "*trylast*last*", ]) + def test_importplugin_issue375(testdir): testdir.makepyfile(qwe="import aaaa") excinfo = pytest.raises(ImportError, lambda: importplugin("qwe")) assert "qwe" not in str(excinfo.value) assert "aaaa" in str(excinfo.value) + class TestWrapMethod: def test_basic_happypath(self): class A: @@ -769,6 +815,7 @@ return "A.f" l = [] + def f(self): l.append(1) box = yield @@ -777,7 +824,7 @@ undo = add_method_wrapper(A, f) assert A().f() == "A.f" - assert l == [1,2] + assert l == [1, 2] undo() l[:] = [] assert A().f() == "A.f" @@ -805,6 +852,7 @@ raise ValueError(val) l = [] + def error(self, val): l.append(val) yield @@ -852,9 +900,10 @@ def test_modify_call_args(self): class A: def error(self, val1, val2): - raise ValueError(val1+val2) + raise ValueError(val1 + val2) l = [] + def error(self): box = yield (1,), {'val2': 2} assert box.excinfo[1].args == (3,) diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_doctest.py --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -1,10 +1,15 @@ from _pytest.doctest import DoctestItem, DoctestModule, DoctestTextfile -import py, pytest +import py +import pytest import pdb -xfail_if_pdbpp_installed = pytest.mark.xfail(hasattr(pdb, "__author__"), - reason="doctest/pdbpp problem: https://bitbucket.org/antocuni/pdb/issue/24/doctests-fail-when-pdbpp-is-installed", run=False) +xfail_if_pdbpp_installed = pytest.mark.xfail( + hasattr(pdb, "__author__"), + reason="doctest/pdbpp problem: " + "https://bitbucket.org/antocuni/pdb/issue/24/" + "doctests-fail-when-pdbpp-is-installed", run=False) + class TestDoctests: @@ -17,7 +22,7 @@ 4 """) for x in (testdir.tmpdir, checkfile): - #print "checking that %s returns custom items" % (x,) + # print "checking that %s returns custom items" % (x,) items, reprec = testdir.inline_genitems(x) assert len(items) == 1 assert isinstance(items[0], DoctestTextfile) @@ -27,15 +32,13 @@ def test_collect_module_empty(self, testdir): path = testdir.makepyfile(whatever="#") for p in (path, testdir.tmpdir): - items, reprec = testdir.inline_genitems(p, - '--doctest-modules') + items, reprec = testdir.inline_genitems(p, '--doctest-modules') assert len(items) == 0 def test_collect_module_single_modulelevel_doctest(self, testdir): path = testdir.makepyfile(whatever='""">>> pass"""') for p in (path, testdir.tmpdir): - items, reprec = testdir.inline_genitems(p, - '--doctest-modules') + items, reprec = testdir.inline_genitems(p, '--doctest-modules') assert len(items) == 1 assert isinstance(items[0], DoctestItem) assert isinstance(items[0].parent, DoctestModule) @@ -47,8 +50,7 @@ ">>> magic = 42 " """) for p in (path, testdir.tmpdir): - items, reprec = testdir.inline_genitems(p, - '--doctest-modules') + items, reprec = testdir.inline_genitems(p, '--doctest-modules') assert len(items) == 2 assert isinstance(items[0], DoctestItem) assert isinstance(items[1], DoctestItem) @@ -72,16 +74,15 @@ ''' """) for p in (path, testdir.tmpdir): - items, reprec = testdir.inline_genitems(p, - '--doctest-modules') + items, reprec = testdir.inline_genitems(p, '--doctest-modules') assert len(items) == 2 assert isinstance(items[0], DoctestItem) assert isinstance(items[1], DoctestItem) assert isinstance(items[0].parent, DoctestModule) assert items[0].parent is items[1].parent - @pytest.mark.xfail('hasattr(sys, "pypy_version_info")', reason= - "pypy leaks one FD") + @pytest.mark.xfail('hasattr(sys, "pypy_version_info")', + reason="pypy leaks one FD") def test_simple_doctestfile(self, testdir): p = testdir.maketxtfile(test_doc=""" >>> x = 1 @@ -92,7 +93,7 @@ reprec.assertoutcome(failed=1) def test_new_pattern(self, testdir): - p = testdir.maketxtfile(xdoc =""" + p = testdir.maketxtfile(xdoc=""" >>> x = 1 >>> x == 1 False @@ -127,13 +128,13 @@ result = testdir.runpytest("--doctest-modules") result.stdout.fnmatch_lines([ "*hello*", - "*EXAMPLE LOCATION UNKNOWN, not showing all tests of that example*", + "*EXAMPLE LOCATION UNKNOWN, " + "not showing all tests of that example*", "*1/0*", "*UNEXPECTED*ZeroDivision*", "*1 failed*", ]) - def test_doctest_unex_importerror(self, testdir): testdir.tmpdir.join("hello.py").write(py.code.Source(""" import asdalsdkjaslkdjasd @@ -183,7 +184,6 @@ "*:5: DocTestFailure" ]) - def test_txtfile_failing(self, testdir): p = testdir.maketxtfile(""" >>> i = 0 diff -r eb3382c1cf5061a70396445727c1ca8102be95f3 -r 60e93163ce6fc37867fe22c1d243306215b490b2 testing/test_genscript.py --- a/testing/test_genscript.py +++ b/testing/test_genscript.py @@ -6,6 +6,7 @@ def standalone(request): return Standalone(request) + class Standalone: def __init__(self, request): self.testdir = request.getfuncargvalue("testdir") @@ -19,10 +20,11 @@ testdir.chdir() return testdir._run(anypython, self.script, *args) + def test_gen(testdir, anypython, standalone): - if sys.version_info >= (2,7): + if sys.version_info >= (2, 7): result = testdir._run(anypython, "-c", - "import sys;print (sys.version_info >=(2,7))") + "import sys;print (sys.version_info >=(2, 7))") assert result.ret == 0 if result.stdout.str() == "False": pytest.skip("genscript called from python2.7 cannot work " @@ -45,4 +47,3 @@ includes = pytest.freeze_includes() assert len(includes) > 1 assert '_pytest.genscript' in includes - This diff is so big that we needed to truncate the remainder. https://bitbucket.org/hpk42/pytest/commits/6f78944be6a2/ Changeset: 6f78944be6a2 Branch: flake8-clean User: RonnyPfannschmidt Date: 2015-02-22 18:07:29+00:00 Summary: finish flake8 clean Affected #: 1 file diff -r 60e93163ce6fc37867fe22c1d243306215b490b2 -r 6f78944be6a29393f796f7e1cd266abad32f694d setup.py --- a/setup.py +++ b/setup.py @@ -2,17 +2,20 @@ import sys from setuptools import setup, Command -classifiers = ['Development Status :: 6 - Mature', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Operating System :: POSIX', - 'Operating System :: Microsoft :: Windows', - 'Operating System :: MacOS :: MacOS X', - 'Topic :: Software Development :: Testing', - 'Topic :: Software Development :: Libraries', - 'Topic :: Utilities'] + [ - ('Programming Language :: Python :: %s' % x) - for x in '2 2.6 2.7 3 3.2 3.3 3.4'.split()] +classifiers = [ + 'Development Status :: 6 - Mature', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Operating System :: POSIX', + 'Operating System :: Microsoft :: Windows', + 'Operating System :: MacOS :: MacOS X', + 'Topic :: Software Development :: Testing', + 'Topic :: Software Development :: Libraries', + 'Topic :: Utilities', +] + [ + ('Programming Language :: Python :: %s' % x) + for x in '2 2.6 2.7 3 3.2 3.3 3.4'.split() +] long_description = open('README.rst').read() 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. _______________________________________________ pytest-commit mailing list pytest-commit@python.org https://mail.python.org/mailman/listinfo/pytest-commit