From 8a7d98fed9a9bf14576066dae15c63d6320661b2 Mon Sep 17 00:00:00 2001 From: Pauli Virtanen Date: Mon, 10 Jul 2017 21:07:55 +0200 Subject: [PATCH 01/58] Make YIELD_TEST warning less spammy Emit it only once per each generator, rather than for each generated function. Also add information about which test caused it to be emitted. --- _pytest/python.py | 2 +- changelog/2562.trivial | 1 + testing/deprecated_test.py | 4 ++++ 3 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 changelog/2562.trivial diff --git a/_pytest/python.py b/_pytest/python.py index 06f74ce4b8a..1b4aeecedeb 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -615,7 +615,7 @@ def collect(self): 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)) - self.config.warn('C1', deprecated.YIELD_TESTS, fslocation=self.fspath) + self.warn('C1', deprecated.YIELD_TESTS) return l def getcallargs(self, obj): diff --git a/changelog/2562.trivial b/changelog/2562.trivial new file mode 100644 index 00000000000..605c7cf7400 --- /dev/null +++ b/changelog/2562.trivial @@ -0,0 +1 @@ +Emit yield test warning only once per generator diff --git a/testing/deprecated_test.py b/testing/deprecated_test.py index 0c41a71bf73..a59ad128be7 100644 --- a/testing/deprecated_test.py +++ b/testing/deprecated_test.py @@ -9,12 +9,16 @@ def func1(arg, arg2): def test_gen(): yield "m1", func1, 15, 3*5 yield "m2", func1, 42, 6*7 + def test_gen2(): + for k in range(10): + yield func1, 1, 1 """) result = testdir.runpytest('-ra') result.stdout.fnmatch_lines([ '*yield tests are deprecated, and scheduled to be removed in pytest 4.0*', '*2 passed*', ]) + assert result.stdout.str().count('yield tests are deprecated') == 2 def test_funcarg_prefix_deprecation(testdir): From 73b07e14393b6fdbacfc304e55c6c08d94be8108 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Tue, 11 Jul 2017 21:45:27 -0300 Subject: [PATCH 02/58] Add docs for Item.add_report_section in the docs Fix #2381 --- _pytest/main.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/_pytest/main.py b/_pytest/main.py index 1a6ba2781a3..2cc15598f6f 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -518,6 +518,21 @@ def __init__(self, name, parent=None, config=None, session=None): self._report_sections = [] def add_report_section(self, when, key, content): + """ + Adds a new report section, similar to what's done internally to add stdout and + stderr captured output:: + + item.add_report_section("call", "stdout", "report section contents") + + :param str when: + One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``. + :param str key: + Name of the section, can be customized at will. Pytest uses ``"stdout"`` and + ``"stderr"`` internally. + + :param str content: + The full contents as a string. + """ if content: self._report_sections.append((when, key, content)) From e6b9a81ccf0af175e9b0fb90dcd1919a17c7db74 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Wed, 12 Jul 2017 16:22:16 -0300 Subject: [PATCH 03/58] Add a link to our backwards compatibility policy to our side-bar It is important enough that it should be easier to find --- doc/en/_templates/globaltoc.html | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/en/_templates/globaltoc.html b/doc/en/_templates/globaltoc.html index af427198a62..fdd4dd59b32 100644 --- a/doc/en/_templates/globaltoc.html +++ b/doc/en/_templates/globaltoc.html @@ -9,6 +9,7 @@

{{ _('Table Of Contents') }}

  • Contact
  • Talks/Posts
  • Changelog
  • +
  • Backwards Compatibility
  • License
  • From 97fdc9a7fef504fc90756a00c1316f02a8ce0bc9 Mon Sep 17 00:00:00 2001 From: Alex Hartoto Date: Thu, 13 Jul 2017 12:01:21 -0700 Subject: [PATCH 04/58] Ensure final collected line doesn't include artifacts We sometimes would see the following line: collected 1 item s just because previous write to the terminal includes number of characters greater than 'collected 1 item'. --- _pytest/terminal.py | 3 +++ changelog/2571.trivial | 1 + 2 files changed, 4 insertions(+) create mode 100644 changelog/2571.trivial diff --git a/_pytest/terminal.py b/_pytest/terminal.py index af89d0fc2b2..0bf861ebefa 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -290,6 +290,9 @@ def report_collect(self, final=False): if self.isatty: if final: line += " \n" + # Rewrite with empty line so we will not see the artifact of + # previous write + self.rewrite('') self.rewrite(line, bold=True) else: self.write_line(line) diff --git a/changelog/2571.trivial b/changelog/2571.trivial new file mode 100644 index 00000000000..45750f122d4 --- /dev/null +++ b/changelog/2571.trivial @@ -0,0 +1 @@ +Ensure final collected line doesn't include artifacts of previous write. From e5169a026a0da6a23c4068157824fd7b82b2337e Mon Sep 17 00:00:00 2001 From: Martin Altmayer Date: Sat, 15 Jul 2017 13:33:11 +0200 Subject: [PATCH 05/58] #2574: --fixtures, --fixtures-per-test keep indentation of docstring --- _pytest/python.py | 26 ++++++++++++---- testing/python/fixture.py | 65 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 81 insertions(+), 10 deletions(-) diff --git a/_pytest/python.py b/_pytest/python.py index 83413bbf9a1..edea9db3d76 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -7,6 +7,7 @@ import os import collections import math +from textwrap import dedent from itertools import count import py @@ -1003,14 +1004,12 @@ def write_fixture(fixture_def): funcargspec = argname tw.line(funcargspec, green=True) - INDENT = ' {0}' fixture_doc = fixture_def.func.__doc__ if fixture_doc: - for line in fixture_doc.strip().split('\n'): - tw.line(INDENT.format(line.strip())) + write_docstring(tw, fixture_doc) else: - tw.line(INDENT.format('no docstring available'), red=True) + tw.line(' no docstring available', red=True) def write_item(item): name2fixturedefs = item._fixtureinfo.name2fixturedefs @@ -1084,13 +1083,28 @@ def _showfixtures_main(config, session): loc = getlocation(fixturedef.func, curdir) doc = fixturedef.func.__doc__ or "" if doc: - for line in doc.strip().split("\n"): - tw.line(" " + line.strip()) + write_docstring(tw, doc) else: tw.line(" %s: no docstring available" %(loc,), red=True) +def write_docstring(tw, doc): + INDENT = " " + doc = doc.rstrip() + if "\n" in doc: + firstline, rest = doc.split("\n", 1) + else: + firstline, rest = doc, "" + + if firstline.strip(): + tw.line(INDENT + firstline.strip()) + + if rest: + for line in dedent(rest).split("\n"): + tw.write(INDENT + line + "\n") + + # builtin pytest.raises helper def raises(expected_exception, *args, **kwargs): diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 1e58a555046..846728d64af 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -2713,7 +2713,7 @@ def test_hello(): """) def test_show_fixtures_trimmed_doc(self, testdir): - p = testdir.makepyfile(''' + p = testdir.makepyfile(dedent(''' import pytest @pytest.fixture def arg1(): @@ -2729,9 +2729,9 @@ def arg2(): line2 """ - ''') + ''')) result = testdir.runpytest("--fixtures", p) - result.stdout.fnmatch_lines(""" + result.stdout.fnmatch_lines(dedent(""" * fixtures defined from test_show_fixtures_trimmed_doc * arg2 line1 @@ -2740,7 +2740,64 @@ def arg2(): line1 line2 - """) + """)) + + def test_show_fixtures_indented_doc(self, testdir): + p = testdir.makepyfile(dedent(''' + import pytest + @pytest.fixture + def fixture1(): + """ + line1 + indented line + """ + ''')) + result = testdir.runpytest("--fixtures", p) + result.stdout.fnmatch_lines(dedent(""" + * fixtures defined from test_show_fixtures_indented_doc * + fixture1 + line1 + indented line + """)) + + def test_show_fixtures_indented_doc_first_line_unindented(self, testdir): + p = testdir.makepyfile(dedent(''' + import pytest + @pytest.fixture + def fixture1(): + """line1 + line2 + indented line + """ + ''')) + result = testdir.runpytest("--fixtures", p) + result.stdout.fnmatch_lines(dedent(""" + * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented * + fixture1 + line1 + line2 + indented line + """)) + + def test_show_fixtures_indented_in_class(self, testdir): + p = testdir.makepyfile(dedent(''' + import pytest + class TestClass: + @pytest.fixture + def fixture1(): + """line1 + line2 + indented line + """ + ''')) + result = testdir.runpytest("--fixtures", p) + result.stdout.fnmatch_lines(dedent(""" + * fixtures defined from test_show_fixtures_indented_in_class * + fixture1 + line1 + line2 + indented line + """)) def test_show_fixtures_different_files(self, testdir): From 2a979797ef637583a22d1e794da8de79f942732a Mon Sep 17 00:00:00 2001 From: Martin Altmayer Date: Sat, 15 Jul 2017 13:43:59 +0200 Subject: [PATCH 06/58] Add a changelog entry. --- changelog/2574.bugfix | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog/2574.bugfix diff --git a/changelog/2574.bugfix b/changelog/2574.bugfix new file mode 100644 index 00000000000..49a01342b69 --- /dev/null +++ b/changelog/2574.bugfix @@ -0,0 +1 @@ +The options --fixtures and --fixtures-per-test will now keep indentation within docstrings. From cc39f41c535e9206986b9e93e6b0880f0d5cdbe4 Mon Sep 17 00:00:00 2001 From: Martin Altmayer Date: Sat, 15 Jul 2017 13:54:18 +0200 Subject: [PATCH 07/58] Add myself to AUTHORS as required by the PR help text. --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index ca282870fb9..6807238fc0f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -104,6 +104,7 @@ Marcin Bachry Mark Abramowitz Markus Unterwaditzer Martijn Faassen +Martin Altmayer Martin K. Scherer Martin Prusse Mathieu Clabaut From 796ffa51230c82899f99fc3723ea6c6620f983a6 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:27:37 +0200 Subject: [PATCH 08/58] reformatted tox.ini --- tox.ini | 204 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 104 insertions(+), 100 deletions(-) diff --git a/tox.ini b/tox.ini index d8b27300f57..ac8bf13b853 100644 --- a/tox.ini +++ b/tox.ini @@ -1,53 +1,54 @@ [tox] -minversion=2.0 -distshare={homedir}/.tox/distshare +minversion = 2.0 +distshare = {homedir}/.tox/distshare # make sure to update environment list on appveyor.yml -envlist= - linting - py26 - py27 - py33 - py34 - py35 - py36 - py37 - pypy - {py27,py35}-{pexpect,xdist,trial} - py27-nobyte - doctesting - freeze - docs +envlist = + linting + py26 + py27 + py33 + py34 + py35 + py36 + py37 + pypy + {py27,py35}-{pexpect,xdist,trial} + py27-nobyte + doctesting + freeze + docs [testenv] -commands= pytest --lsof -rfsxX {posargs:testing} +commands = pytest --lsof -rfsxX {posargs:testing} passenv = USER USERNAME -deps= +deps = hypothesis>=3.5.2 nose mock requests [testenv:py26] -commands= pytest --lsof -rfsxX {posargs:testing} +commands = pytest --lsof -rfsxX {posargs:testing} # pinning mock to last supported version for python 2.6 -deps= +deps = hypothesis<3.0 nose mock<1.1 [testenv:py27-subprocess] -changedir=. -basepython=python2.7 -deps=pytest-xdist>=1.13 +changedir = . +basepython = python2.7 +deps = + pytest-xdist>=1.13 mock nose -commands= - pytest -n3 -rfsxX --runpytest=subprocess {posargs:testing} +commands = + pytest -n3 -rfsxX --runpytest=subprocess {posargs:testing} [testenv:linting] -skipsdist=True -usedevelop=True +skipsdist = True +usedevelop = True basepython = python2.7 # needed to keep check-manifest working setenv = @@ -55,143 +56,146 @@ setenv = deps = flake8 # pygments required by rst-lint - pygments + pygments restructuredtext_lint commands = flake8 pytest.py _pytest testing {envpython} scripts/check-rst.py [testenv:py27-xdist] -deps=pytest-xdist>=1.13 +deps = + pytest-xdist>=1.13 mock nose hypothesis>=3.5.2 -commands= - pytest -n1 -rfsxX {posargs:testing} +commands = + pytest -n1 -rfsxX {posargs:testing} [testenv:py35-xdist] -deps={[testenv:py27-xdist]deps} -commands= - pytest -n3 -rfsxX {posargs:testing} +deps = {[testenv:py27-xdist]deps} +commands = + pytest -n3 -rfsxX {posargs:testing} [testenv:py27-pexpect] -changedir=testing -platform=linux|darwin -deps=pexpect -commands= - pytest -rfsxX test_pdb.py test_terminal.py test_unittest.py +changedir = testing +platform = linux|darwin +deps = pexpect +commands = + pytest -rfsxX test_pdb.py test_terminal.py test_unittest.py [testenv:py35-pexpect] -changedir=testing -platform=linux|darwin -deps={[testenv:py27-pexpect]deps} -commands= - pytest -rfsxX test_pdb.py test_terminal.py test_unittest.py +changedir = testing +platform = linux|darwin +deps = {[testenv:py27-pexpect]deps} +commands = + pytest -rfsxX test_pdb.py test_terminal.py test_unittest.py [testenv:py27-nobyte] -deps= +deps = pytest-xdist>=1.13 hypothesis>=3.5.2 -distribute=true -setenv= +distribute = true +setenv = PYTHONDONTWRITEBYTECODE=1 -commands= - pytest -n3 -rfsxX {posargs:testing} +commands = + pytest -n3 -rfsxX {posargs:testing} [testenv:py27-trial] -deps=twisted -commands= - pytest -ra {posargs:testing/test_unittest.py} +deps = twisted +commands = + pytest -ra {posargs:testing/test_unittest.py} [testenv:py35-trial] -deps={[testenv:py27-trial]deps} -commands= - pytest -ra {posargs:testing/test_unittest.py} +deps = {[testenv:py27-trial]deps} +commands = + pytest -ra {posargs:testing/test_unittest.py} [testenv:docs] -skipsdist=True -usedevelop=True -basepython=python -changedir=doc/en -deps= +skipsdist = True +usedevelop = True +basepython = python +changedir = doc/en +deps = sphinx PyYAML -commands= +commands = sphinx-build -W -b html . _build [testenv:doctesting] basepython = python -usedevelop=True -skipsdist=True +usedevelop = True +skipsdist = True # ensure the given pyargs cant mean anytrhing else -changedir=doc/ -deps= +changedir = doc/ +deps = PyYAML -commands= +commands = pytest -rfsxX en pytest --doctest-modules --pyargs _pytest [testenv:regen] -changedir=doc/en -skipsdist=True +changedir = doc/en +skipsdist = True basepython = python3.5 -deps=sphinx - PyYAML - regendoc>=0.6.1 -whitelist_externals= +deps = + sphinx + PyYAML + regendoc>=0.6.1 +whitelist_externals = rm make -commands= +commands = rm -rf /tmp/doc-exec* make regen [testenv:jython] -changedir=testing -commands= +changedir = testing +commands = {envpython} {envbindir}/py.test-jython -rfsxX {posargs} [testenv:freeze] -changedir=testing/freeze -deps=pyinstaller -commands= +changedir = testing/freeze +deps = pyinstaller +commands = {envpython} create_executable.py {envpython} tox_run.py [testenv:coveralls] passenv = TRAVIS TRAVIS_JOB_ID TRAVIS_BRANCH COVERALLS_REPO_TOKEN -usedevelop=True -basepython=python3.5 -changedir=. +usedevelop = True +basepython = python3.5 +changedir = . deps = {[testenv]deps} coveralls -commands= +commands = coverage run --source=_pytest -m pytest testing coverage report -m coveralls [pytest] -minversion=2.0 -plugins=pytester +minversion = 2.0 +plugins = pytester #--pyargs --doctest-modules --ignore=.tox -addopts= -rxsX -p pytester --ignore=testing/cx_freeze -rsyncdirs=tox.ini pytest.py _pytest testing -python_files=test_*.py *_test.py testing/*/*.py -python_classes=Test Acceptance -python_functions=test +addopts = -rxsX -p pytester --ignore=testing/cx_freeze +rsyncdirs = tox.ini pytest.py _pytest testing +python_files = test_*.py *_test.py testing/*/*.py +python_classes = Test Acceptance +python_functions = test norecursedirs = .tox ja .hg cx_freeze_source -filterwarnings= - # produced by path.local - ignore:bad escape.*:DeprecationWarning:re - # produced by path.readlines - ignore:.*U.*mode is deprecated:DeprecationWarning - # produced by pytest-xdist - ignore:.*type argument to addoption.*:DeprecationWarning - # produced by python >=3.5 on execnet (pytest-xdist) - ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning +filterwarnings = + # produced by path.local + ignore:bad escape.*:DeprecationWarning:re + # produced by path.readlines + ignore:.*U.*mode is deprecated:DeprecationWarning + # produced by pytest-xdist + ignore:.*type argument to addoption.*:DeprecationWarning + # produced by python >=3.5 on execnet (pytest-xdist) + ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore =E401,E225,E261,E128,E124,E301,E302,E121,E303,W391,E501,E231,E126,E701,E265,E241,E251,E226,E101,W191,E131,E203,E122,E123,E271,E712,E222,E127,E125,E221,W292,E111,E113,E293,E262,W293,E129,E702,E201,E272,E202,E704,E731,E402 +ignore = E101,E111,E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731,W191,W292,W293,W391 +max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 6af2abdb53ed5277d7c43bfec0ec646b2a35a814 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:06 +0200 Subject: [PATCH 09/58] Fixed flake8 warnings W191 indentation contains tabs W292 no newline at end of file W293 blank line contains whitespace W391 blank line at end of file --- _pytest/_code/code.py | 2 +- _pytest/_code/source.py | 2 -- _pytest/fixtures.py | 1 - testing/code/test_source.py | 5 ++++- testing/freeze/create_executable.py | 1 - testing/freeze/runtests_script.py | 2 +- testing/freeze/tests/test_trivial.py | 2 +- testing/freeze/tox_run.py | 2 +- testing/python/approx.py | 1 - testing/python/fixture.py | 3 --- testing/test_config.py | 1 - testing/test_doctest.py | 1 - testing/test_junitxml.py | 1 - testing/test_pastebin.py | 2 -- testing/test_resultlog.py | 2 -- testing/test_runner.py | 2 -- tox.ini | 2 +- 17 files changed, 9 insertions(+), 23 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 5b7cc41911e..03b3c3994fc 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -645,7 +645,7 @@ def _truncate_recursive_traceback(self, traceback): traceback = traceback[:recursionindex + 1] else: extraline = None - + return traceback, extraline def repr_excinfo(self, excinfo): diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 8e6148410a1..93c59cace0e 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -410,5 +410,3 @@ def getstatementrange_old(lineno, source, assertion=False): if trysource.isparseable(): return start, end raise SyntaxError("no valid source range around line %d " % (lineno,)) - - diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 64d21b9f696..f6a4be79066 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -1126,4 +1126,3 @@ def _matchfactories(self, fixturedefs, nodeid): for fixturedef in fixturedefs: if nodeid.startswith(fixturedef.baseid): yield fixturedef - diff --git a/testing/code/test_source.py b/testing/code/test_source.py index bdbc00d196b..e456da4094c 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -325,7 +325,7 @@ def __init__(self, *args): self.source = _pytest._code.Frame(frame).statement x = A('x', - 'y' \ + 'y' , 'z') @@ -400,6 +400,7 @@ def method(self): s2 = _pytest._code.Source(tmpdir.join("a.py").pyimport().A) assert str(source).strip() == str(s2).strip() + if True: def x(): pass @@ -462,6 +463,7 @@ class A(object): assert lineno == A_lineno assert getfslineno(3) == ("", -1) + class B(object): pass B.__name__ = "B2" @@ -471,6 +473,7 @@ def test_code_of_object_instance_with_call(): class A(object): pass pytest.raises(TypeError, lambda: _pytest._code.Source(A())) + class WithCall(object): def __call__(self): pass diff --git a/testing/freeze/create_executable.py b/testing/freeze/create_executable.py index 8cf259c4024..f4f6088ef7d 100644 --- a/testing/freeze/create_executable.py +++ b/testing/freeze/create_executable.py @@ -10,4 +10,3 @@ hidden.extend(['--hidden-import', x]) args = ['pyinstaller', '--noconfirm'] + hidden + ['runtests_script.py'] subprocess.check_call(' '.join(args), shell=True) - diff --git a/testing/freeze/runtests_script.py b/testing/freeze/runtests_script.py index cb961fc6caf..d281601c068 100644 --- a/testing/freeze/runtests_script.py +++ b/testing/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 --git a/testing/freeze/tests/test_trivial.py b/testing/freeze/tests/test_trivial.py index 6cf6b05adb2..f0f29ee60b7 100644 --- a/testing/freeze/tests/test_trivial.py +++ b/testing/freeze/tests/test_trivial.py @@ -3,4 +3,4 @@ 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 --git a/testing/freeze/tox_run.py b/testing/freeze/tox_run.py index 5310ac1b722..3fc38804095 100644 --- a/testing/freeze/tox_run.py +++ b/testing/freeze/tox_run.py @@ -9,4 +9,4 @@ executable = os.path.join(os.getcwd(), 'dist', 'runtests_script', '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)) diff --git a/testing/python/approx.py b/testing/python/approx.py index d7063e2150f..d9bbaa4e0c0 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -309,4 +309,3 @@ def test_foo(): '*At index 0 diff: 3 != 4 * {0}'.format(expected), '=* 1 failed in *=', ]) - diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 1e58a555046..ff49346c607 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -3026,6 +3026,3 @@ def test_foo(request): E*{1}:5 *1 failed* """.format(fixfile.strpath, testfile.basename)) - - - diff --git a/testing/test_config.py b/testing/test_config.py index 0d8e6abfc25..ddabf6a29f7 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -826,4 +826,3 @@ def test_with_existing_file_in_subdir(self, tmpdir): rootdir, inifile, inicfg = determine_setup(None, ['a/exist']) assert rootdir == tmpdir assert inifile is None - diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 26f9c846966..4a813e5c068 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -932,4 +932,3 @@ def test_doctest_report_invalid(self, testdir): result.stderr.fnmatch_lines([ "*error: argument --doctest-report: invalid choice: 'obviously_invalid_format' (choose from*" ]) - diff --git a/testing/test_junitxml.py b/testing/test_junitxml.py index bc637b0352d..af6eabf983f 100644 --- a/testing/test_junitxml.py +++ b/testing/test_junitxml.py @@ -1057,4 +1057,3 @@ def test_func(): assert result.ret == 0 node = dom.find_first_by_tag("testsuite") node.assert_attr(name=expected) - diff --git a/testing/test_pastebin.py b/testing/test_pastebin.py index 3fe66e97210..f7716f8fd28 100644 --- a/testing/test_pastebin.py +++ b/testing/test_pastebin.py @@ -114,5 +114,3 @@ def test_create_new_paste(self, pastebin, mocked_urlopen): assert 'lexer=%s' % lexer in data.decode() assert 'code=full-paste-contents' in data.decode() assert 'expiry=1week' in data.decode() - - diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py index cb083225ce5..fd167c36b22 100644 --- a/testing/test_resultlog.py +++ b/testing/test_resultlog.py @@ -224,5 +224,3 @@ def test_func(): """) result = testdir.runpytest("--resultlog=log") assert result.ret == 2 - - diff --git a/testing/test_runner.py b/testing/test_runner.py index def80ea5fb4..eb7e161a348 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -754,5 +754,3 @@ def test_func(): rep = reports[1] assert rep.capstdout == '' assert rep.capstderr == '' - - diff --git a/tox.ini b/tox.ini index ac8bf13b853..100a22d45db 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E101,E111,E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731,W191,W292,W293,W391 +ignore = E101,E111,E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 6146ac97d9f79bb9ee5f8a26cbe4298f6fe06987 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:06 +0200 Subject: [PATCH 10/58] Fixed E101 flake8 errors indentation contains mixed spaces and tabs --- _pytest/doctest.py | 2 +- _pytest/pytester.py | 10 +++++----- _pytest/python.py | 2 +- testing/test_conftest.py | 8 ++++---- testing/test_doctest.py | 2 +- testing/test_monkeypatch.py | 2 +- testing/test_unittest.py | 2 +- testing/test_warnings.py | 4 ++-- tox.ini | 2 +- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/_pytest/doctest.py b/_pytest/doctest.py index fde6dd71dfb..cbd39652e0a 100644 --- a/_pytest/doctest.py +++ b/_pytest/doctest.py @@ -332,7 +332,7 @@ def _fix_spoof_python2(runner, encoding): should patch only doctests for text files because they don't have a way to declare their encoding. Doctests in docstrings from Python modules don't have the same problem given that Python already decoded the strings. - + This fixes the problem related in issue #2434. """ from _pytest.compat import _PY2 diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 901caa340b8..768d922cf90 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -1032,11 +1032,11 @@ def spawn(self, cmd, expect_timeout=10.0): return child def getdecoded(out): - try: - return out.decode("utf-8") - except UnicodeDecodeError: - return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % ( - py.io.saferepr(out),) + try: + return out.decode("utf-8") + except UnicodeDecodeError: + return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % ( + py.io.saferepr(out),) class LineComp: diff --git a/_pytest/python.py b/_pytest/python.py index 83413bbf9a1..1720c876213 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -151,7 +151,7 @@ def pytest_collect_file(path, parent): if path.fnmatch(pat): break else: - return + return ihook = parent.session.gethookproxy(path) return ihook.pytest_pycollect_makemodule(path=path, parent=parent) diff --git a/testing/test_conftest.py b/testing/test_conftest.py index b6fd7814cdc..ed01c541085 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -319,25 +319,25 @@ def test_no_conftest(fxtr): # N.B.: "swc" stands for "subdir with conftest.py" # "snc" stands for "subdir no [i.e. without] conftest.py" @pytest.mark.parametrize("chdir,testarg,expect_ntests_passed", [ - # Effective target: package/.. + # Effective target: package/.. ("runner", "..", 3), ("package", "..", 3), ("swc", "../..", 3), ("snc", "../..", 3), - # Effective target: package + # Effective target: package ("runner", "../package", 3), ("package", ".", 3), ("swc", "..", 3), ("snc", "..", 3), - # Effective target: package/swc + # Effective target: package/swc ("runner", "../package/swc", 1), ("package", "./swc", 1), ("swc", ".", 1), ("snc", "../swc", 1), - # Effective target: package/snc + # Effective target: package/snc ("runner", "../package/snc", 1), ("package", "./snc", 1), ("swc", "../snc", 1), diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 4a813e5c068..0aa60e8ac72 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -535,7 +535,7 @@ def test_unicode_doctest_module(self, testdir): p = testdir.makepyfile(test_unicode_doctest_module=""" # -*- encoding: utf-8 -*- from __future__ import unicode_literals - + def fix_bad_unicode(text): ''' >>> print(fix_bad_unicode('único')) diff --git a/testing/test_monkeypatch.py b/testing/test_monkeypatch.py index 1efcf7f95bf..789c8d1e717 100644 --- a/testing/test_monkeypatch.py +++ b/testing/test_monkeypatch.py @@ -323,6 +323,6 @@ def test_issue1338_name_resolving(): pytest.importorskip('requests') monkeypatch = MonkeyPatch() try: - monkeypatch.delattr('requests.sessions.Session.request') + monkeypatch.delattr('requests.sessions.Session.request') finally: monkeypatch.undo() diff --git a/testing/test_unittest.py b/testing/test_unittest.py index af9851997ad..b3a06cb5a13 100644 --- a/testing/test_unittest.py +++ b/testing/test_unittest.py @@ -788,7 +788,7 @@ def test_one(self): def test_unittest_skip_issue1169(testdir): testdir.makepyfile(test_foo=""" import unittest - + class MyTestCase(unittest.TestCase): @unittest.skip("skipping due to reasons") def test_skip(self): diff --git a/testing/test_warnings.py b/testing/test_warnings.py index 69bda1172fa..213cc53705b 100644 --- a/testing/test_warnings.py +++ b/testing/test_warnings.py @@ -173,9 +173,9 @@ def test_works_with_filterwarnings(testdir): class MyWarning(Warning): pass - + warnings.filterwarnings("error", category=MyWarning) - + class TestWarnings(object): def test_my_warning(self): try: diff --git a/tox.ini b/tox.ini index 100a22d45db..a9f354872f8 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E101,E111,E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E111,E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 8de49e8742f08f17a46c64674b34e772f685a9e4 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 11/58] Fixed E111 flake8 errors indentation is not a multiple of four --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index a9f354872f8..4caeb4c83cf 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E111,E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 64a4b9058c4d27b47992f3d816e7969fcdddd102 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 12/58] Fixed E113 flake8 errors unexpected indentation --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 4caeb4c83cf..db8f94d070d 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E113,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 0be97624b745581af68bb9a0e2c1d04a249c55bf Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 13/58] Fixed E121 flake8 errors continuation line under-indented for hanging indent --- _pytest/fixtures.py | 2 +- _pytest/recwarn.py | 2 +- _pytest/runner.py | 2 +- testing/python/approx.py | 18 +++++++++--------- testing/python/fixture.py | 14 ++++++-------- testing/test_terminal.py | 6 +++--- tox.ini | 2 +- 7 files changed, 22 insertions(+), 24 deletions(-) diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index f6a4be79066..593e80b900f 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -527,7 +527,7 @@ def _check_scope(self, argname, invoking_scope, requested_scope): fail("ScopeMismatch: You tried to access the %r scoped " "fixture %r with a %r scoped request object, " "involved factories\n%s" % ( - (requested_scope, argname, invoking_scope, "\n".join(lines))), + (requested_scope, argname, invoking_scope, "\n".join(lines))), pytrace=False) def _factorytraceback(self): diff --git a/_pytest/recwarn.py b/_pytest/recwarn.py index 9cc404a4901..cc787455046 100644 --- a/_pytest/recwarn.py +++ b/_pytest/recwarn.py @@ -200,5 +200,5 @@ def __exit__(self, *exc_info): from _pytest.runner import fail fail("DID NOT WARN. No warnings of type {0} was emitted. " "The list of emitted warnings is: {1}.".format( - self.expected_warning, + self.expected_warning, [each.message for each in self])) diff --git a/_pytest/runner.py b/_pytest/runner.py index fd0b549a9ab..5f4093b1d24 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -414,7 +414,7 @@ def _teardown_with_finalization(self, colitem): colitem.teardown() for colitem in self._finalizers: assert colitem is None or colitem in self.stack \ - or isinstance(colitem, tuple) + or isinstance(colitem, tuple) def teardown_all(self): while self.stack: diff --git a/testing/python/approx.py b/testing/python/approx.py index d9bbaa4e0c0..3fac456ffee 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -186,15 +186,15 @@ def test_absolute_tolerance(self): def test_expecting_zero(self): examples = [ - (ne, 1e-6, 0.0), - (ne, -1e-6, 0.0), - (eq, 1e-12, 0.0), - (eq, -1e-12, 0.0), - (ne, 2e-12, 0.0), - (ne, -2e-12, 0.0), - (ne, inf, 0.0), - (ne, nan, 0.0), - ] + (ne, 1e-6, 0.0), + (ne, -1e-6, 0.0), + (eq, 1e-12, 0.0), + (eq, -1e-12, 0.0), + (ne, 2e-12, 0.0), + (ne, -2e-12, 0.0), + (ne, inf, 0.0), + (ne, nan, 0.0), + ] for op, a, x in examples: assert op(a, approx(x, rel=0.0, abs=1e-12)) assert op(a, approx(x, rel=1e-6, abs=1e-12)) diff --git a/testing/python/fixture.py b/testing/python/fixture.py index ff49346c607..de41aaca154 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -2659,18 +2659,16 @@ def test_funcarg_compat(self, testdir): def test_show_fixtures(self, testdir): result = testdir.runpytest("--fixtures") result.stdout.fnmatch_lines([ - "*tmpdir*", - "*temporary directory*", - ] - ) + "*tmpdir*", + "*temporary directory*", + ]) def test_show_fixtures_verbose(self, testdir): result = testdir.runpytest("--fixtures", "-v") result.stdout.fnmatch_lines([ - "*tmpdir*--*tmpdir.py*", - "*temporary directory*", - ] - ) + "*tmpdir*--*tmpdir.py*", + "*temporary directory*", + ]) def test_show_fixtures_testmodule(self, testdir): p = testdir.makepyfile(''' diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 45c354206b6..51c8d642e6c 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -222,7 +222,7 @@ def test_func(): """) result = testdir.runpytest("--collect-only",) result.stdout.fnmatch_lines([ - "", + "", " ", ]) @@ -378,7 +378,7 @@ def teardown_function(function): "*def test_fail():", "*failingfunc*", "*1 failed*1 error*", - ]) + ]) def test_setup_teardown_output_and_test_failure(self, testdir): """ Test for issue #442 """ @@ -403,7 +403,7 @@ def teardown_function(function): "*teardown func*", "*1 failed*", - ]) + ]) class TestTerminalFunctional(object): def test_deselected(self, testdir): diff --git a/tox.ini b/tox.ini index db8f94d070d..573eddac4c4 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 425665cf25dd9a3f20982287338ca8e770531872 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 14/58] Fixed E122 flake8 errors continuation line missing indentation or outdented --- _pytest/config.py | 4 ++-- _pytest/helpconfig.py | 6 +++--- testing/python/fixture.py | 2 +- testing/test_assertrewrite.py | 2 +- testing/test_terminal.py | 4 ++-- tox.ini | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/_pytest/config.py b/_pytest/config.py index dadd5ca9d60..a07174d7271 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -1093,8 +1093,8 @@ def _checkversion(self): if myver < ver: raise pytest.UsageError( "%s:%d: requires pytest-%s, actual pytest-%s'" %( - self.inicfg.config.path, self.inicfg.lineof('minversion'), - minver, pytest.__version__)) + self.inicfg.config.path, self.inicfg.lineof('minversion'), + minver, pytest.__version__)) def parse(self, args, addopts=True): # parse given cmdline arguments into this config object. diff --git a/_pytest/helpconfig.py b/_pytest/helpconfig.py index e3c6b6e9977..240fa67cc0b 100644 --- a/_pytest/helpconfig.py +++ b/_pytest/helpconfig.py @@ -70,9 +70,9 @@ def pytest_cmdline_parse(): debugfile = open(path, 'w') debugfile.write("versions pytest-%s, py-%s, " "python-%s\ncwd=%s\nargs=%s\n\n" %( - pytest.__version__, py.__version__, - ".".join(map(str, sys.version_info)), - os.getcwd(), config._origargs)) + pytest.__version__, py.__version__, + ".".join(map(str, sys.version_info)), + os.getcwd(), config._origargs)) config.trace.root.setwriter(debugfile.write) undo_tracing = config.pluginmanager.enable_tracing() sys.stderr.write("writing pytestdebug information to %s\n" % path) diff --git a/testing/python/fixture.py b/testing/python/fixture.py index de41aaca154..ff6a6915a80 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -2243,7 +2243,7 @@ def test_4(modarg, arg): 'fin:mod1', 'create:mod2', 'test2', 'create:1', 'test3', 'fin:1', 'create:2', 'test3', 'fin:2', 'create:1', 'test4', 'fin:1', 'create:2', 'test4', 'fin:2', - 'fin:mod2'] + 'fin:mod2'] import pprint pprint.pprint(list(zip(l, expected))) assert l == expected diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 8aee520b322..52f97964ed4 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -556,7 +556,7 @@ def test_zipfile(self, testdir): 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") diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 51c8d642e6c..27d46add411 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -77,8 +77,8 @@ def test_func(): ]) else: result.stdout.fnmatch_lines([ - "*test_pass_skip_fail.py .sF" - ]) + "*test_pass_skip_fail.py .sF" + ]) result.stdout.fnmatch_lines([ " def test_func():", "> assert 0", diff --git a/tox.ini b/tox.ini index 573eddac4c4..dec64c85fef 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E122,E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 4b20b9d8d9fe4a027c425c6feeb8d7ed39c86ee3 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 15/58] Fixed E123 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit closing bracket does not match indentation of opening bracket’s line --- testing/python/fixture.py | 2 +- testing/test_runner.py | 10 +++++----- testing/test_terminal.py | 10 +++++----- tox.ini | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/testing/python/fixture.py b/testing/python/fixture.py index ff6a6915a80..9985ee08d5f 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -655,7 +655,7 @@ def test_second(): result = testdir.runpytest(p) result.stdout.fnmatch_lines([ "*1 error*" # XXX the whole module collection fails - ]) + ]) def test_request_subrequest_addfinalizer_exceptions(self, testdir): """ diff --git a/testing/test_runner.py b/testing/test_runner.py index eb7e161a348..1b796917a27 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -262,11 +262,11 @@ def test_method(self): assert reps[2].failed assert reps[2].when == "teardown" assert reps[2].longrepr.reprcrash.message in ( - # python3 error - "TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'", - # python2 error - 'TypeError: teardown_method() takes exactly 4 arguments (2 given)' - ) + # python3 error + "TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'", + # python2 error + 'TypeError: teardown_method() takes exactly 4 arguments (2 given)' + ) def test_failure_in_setup_function_ignores_custom_repr(self, testdir): testdir.makepyfile(conftest=""" diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 27d46add411..f7b9c952f7e 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -78,7 +78,7 @@ def test_func(): else: result.stdout.fnmatch_lines([ "*test_pass_skip_fail.py .sF" - ]) + ]) result.stdout.fnmatch_lines([ " def test_func():", "> assert 0", @@ -378,7 +378,7 @@ def teardown_function(function): "*def test_fail():", "*failingfunc*", "*1 failed*1 error*", - ]) + ]) def test_setup_teardown_output_and_test_failure(self, testdir): """ Test for issue #442 """ @@ -403,7 +403,7 @@ def teardown_function(function): "*teardown func*", "*1 failed*", - ]) + ]) class TestTerminalFunctional(object): def test_deselected(self, testdir): @@ -817,8 +817,8 @@ def test_error_fixture(setup_error_fixture): """) result = testdir.runpytest("--tb=native") result.stdout.fnmatch_lines([ - '*File *test_tbstyle_native_setup_error.py", line *, in setup_error_fixture*' - ]) + '*File *test_tbstyle_native_setup_error.py", line *, in setup_error_fixture*' + ]) def test_terminal_summary(testdir): testdir.makeconftest(""" diff --git a/tox.ini b/tox.ini index dec64c85fef..5af00a12a9b 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E123,E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 051d76a63f6b220e38cc53a54efe4bf800a3dcf3 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 16/58] Fixed E124 flake8 errors closing bracket does not match visual indentation --- _pytest/python.py | 4 ++-- _pytest/skipping.py | 6 +++--- testing/acceptance_test.py | 2 +- testing/code/test_excinfo.py | 2 +- testing/python/metafunc.py | 6 +++--- testing/test_assertrewrite.py | 2 +- testing/test_terminal.py | 2 +- tox.ini | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/_pytest/python.py b/_pytest/python.py index 1720c876213..222f5d91566 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -122,11 +122,11 @@ def pytest_configure(config): "decorated test function, one with arg1=1 and another with arg1=2." "see http://pytest.org/latest/parametrize.html for more info and " "examples." - ) + ) config.addinivalue_line("markers", "usefixtures(fixturename1, fixturename2, ...): mark tests as needing " "all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures " - ) + ) @hookimpl(trylast=True) diff --git a/_pytest/skipping.py b/_pytest/skipping.py index 5af1ca40404..2229beb0775 100644 --- a/_pytest/skipping.py +++ b/_pytest/skipping.py @@ -40,14 +40,14 @@ def nop(*args, **kwargs): "skip(reason=None): skip the given test function with an optional reason. " "Example: skip(reason=\"no way of currently testing this\") skips the " "test." - ) + ) config.addinivalue_line("markers", "skipif(condition): skip the given test function if eval(condition) " "results in a True value. Evaluation happens within the " "module global context. Example: skipif('sys.platform == \"win32\"') " "skips the test if we are on the win32 platform. see " "http://pytest.org/latest/skipping.html" - ) + ) config.addinivalue_line("markers", "xfail(condition, reason=None, run=True, raises=None, strict=False): " "mark the test function as an expected failure if eval(condition) " @@ -56,7 +56,7 @@ def nop(*args, **kwargs): "If only specific exception(s) are expected, you can list them in " "raises, and if the test fails in other ways, it will be reported as " "a true failure. See http://pytest.org/latest/skipping.html" - ) + ) class XFailed(fail.Exception): diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index 9cb2650deb8..3b3023f6c56 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -410,7 +410,7 @@ def test_parameterized_with_bytes_regex(self, testdir): def test_stuff(r): pass """ - ) + ) res = testdir.runpytest(p) res.stdout.fnmatch_lines([ '*1 passed*' diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 0b074d64a7d..7da68e59890 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -934,7 +934,7 @@ def f(): @pytest.mark.parametrize('reproptions', [ {'style': style, 'showlocals': showlocals, 'funcargs': funcargs, 'tbfilter': tbfilter - } for style in ("long", "short", "no") + } for style in ("long", "short", "no") for showlocals in (True, False) for tbfilter in (True, False) for funcargs in (True, False)]) diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 380dbf0e6a1..38cf19a6e00 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -279,7 +279,7 @@ def ids(val): assert result == ["10.0-IndexError()", "20-KeyError()", "three-b2", - ] + ] @pytest.mark.issue351 def test_idmaker_idfn_unique_names(self): @@ -291,11 +291,11 @@ def ids(val): result = idmaker(("a", "b"), [pytest.param(10.0, IndexError()), pytest.param(20, KeyError()), pytest.param("three", [1, 2, 3]), - ], idfn=ids) + ], idfn=ids) assert result == ["a-a0", "a-a1", "a-a2", - ] + ] @pytest.mark.issue351 def test_idmaker_idfn_exception(self): diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 52f97964ed4..7f38b4d167c 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -609,7 +609,7 @@ def test_pyc_vs_pyo(self, testdir, monkeypatch): def test_optimized(): "hello" assert test_optimized.__doc__ is None""" - ) + ) p = py.path.local.make_numbered_dir(prefix="runpytest-", keep=None, rootdir=testdir.tmpdir) tmp = "--basetemp=%s" % p diff --git a/testing/test_terminal.py b/testing/test_terminal.py index f7b9c952f7e..6a099fa3ba8 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -415,7 +415,7 @@ def test_two(): def test_three(): pass """ - ) + ) result = testdir.runpytest("-k", "test_two:", testpath) result.stdout.fnmatch_lines([ "*test_deselected.py ..", diff --git a/tox.ini b/tox.ini index 5af00a12a9b..b347c31166b 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E124,E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 92e2cd9c68d7fbbdf479ba065254dd50724a8d5c Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 17/58] Fixed E125 flake8 errors continuation line with same indent as next logical line --- _pytest/_code/code.py | 4 ++-- _pytest/fixtures.py | 2 +- _pytest/pytester.py | 4 ++-- _pytest/python.py | 2 +- _pytest/skipping.py | 2 +- _pytest/unittest.py | 2 +- tox.ini | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 03b3c3994fc..77baa324714 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -339,8 +339,8 @@ def recursionindex(self): loc = f.f_locals for otherloc in l: if f.is_true(f.eval(co_equal, - __recursioncache_locals_1=loc, - __recursioncache_locals_2=otherloc)): + __recursioncache_locals_1=loc, + __recursioncache_locals_2=otherloc)): return i l.append(entry.frame.f_locals) return None diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 593e80b900f..61069664e00 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -205,7 +205,7 @@ def slice_items(items, ignore, scoped_argkeys_cache): 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) diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 768d922cf90..9b124f57ed2 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -264,7 +264,7 @@ def getreports(self, return [x.report for x in self.getcalls(names)] def matchreport(self, inamepart="", - names="pytest_runtest_logreport pytest_collectreport", when=None): + names="pytest_runtest_logreport pytest_collectreport", when=None): """ return a testreport whose dotted import path matches """ l = [] for rep in self.getreports(names=names): @@ -298,7 +298,7 @@ def listoutcomes(self): skipped = [] failed = [] for rep in self.getreports( - "pytest_collectreport pytest_runtest_logreport"): + "pytest_collectreport pytest_runtest_logreport"): if rep.passed: if getattr(rep, "when", None) == "call": passed.append(rep) diff --git a/_pytest/python.py b/_pytest/python.py index 222f5d91566..27b81247e94 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -737,7 +737,7 @@ def __init__(self, function, fixtureinfo, config, cls=None, module=None): self._arg2fixturedefs = fixtureinfo.name2fixturedefs 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 diff --git a/_pytest/skipping.py b/_pytest/skipping.py index 2229beb0775..6bf62292d4c 100644 --- a/_pytest/skipping.py +++ b/_pytest/skipping.py @@ -243,7 +243,7 @@ def pytest_runtest_makereport(item, call): rep.wasxfail = "reason: " + call.excinfo.value.msg rep.outcome = "skipped" elif evalxfail and not rep.skipped and evalxfail.wasvalid() and \ - evalxfail.istrue(): + evalxfail.istrue(): if call.excinfo: if evalxfail.invalidraise(call.excinfo.value): rep.outcome = "failed" diff --git a/_pytest/unittest.py b/_pytest/unittest.py index 0cf0f1726af..2000c4d0066 100644 --- a/_pytest/unittest.py +++ b/_pytest/unittest.py @@ -210,7 +210,7 @@ def pytest_runtest_protocol(item): check_testcase_implements_trial_reporter() def excstore(self, exc_value=None, exc_type=None, exc_tb=None, - captureVars=None): + captureVars=None): if exc_value is None: self._rawexcinfo = sys.exc_info() else: diff --git a/tox.ini b/tox.ini index b347c31166b..31957cfb1a8 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E125,E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From e855a79dd4d3976c3432f08c4b5f57333dcb3917 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 18/58] Fixed E126 flake8 errors continuation line over-indented for hanging indent --- _pytest/config.py | 12 ++++---- _pytest/deprecated.py | 2 +- _pytest/fixtures.py | 10 +++---- _pytest/junitxml.py | 8 ++--- _pytest/monkeypatch.py | 6 ++-- _pytest/pytester.py | 4 +-- _pytest/python.py | 4 +-- _pytest/runner.py | 8 ++--- testing/code/test_source.py | 2 +- testing/python/approx.py | 56 +++++++++++++++++------------------ testing/test_assertion.py | 2 +- testing/test_mark.py | 8 ++--- testing/test_pluginmanager.py | 2 +- testing/test_resultlog.py | 2 +- tox.ini | 2 +- 15 files changed, 64 insertions(+), 64 deletions(-) diff --git a/_pytest/config.py b/_pytest/config.py index a07174d7271..d70ea450726 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -102,7 +102,7 @@ def directory_arg(path, optname): _preinit = [] default_plugins = ( - "mark main terminal runner python fixtures debugging unittest capture skipping " + "mark main terminal runner python fixtures debugging unittest capture skipping " "tmpdir monkeypatch recwarn pastebin helpconfig nose assertion " "junitxml resultlog doctest cacheprovider freeze_support " "setuponly setupplan warnings").split() @@ -161,7 +161,7 @@ def _prepareconfig(args=None, plugins=None): if warning: config.warn('C1', warning) return pluginmanager.hook.pytest_cmdline_parse( - pluginmanager=pluginmanager, args=args) + pluginmanager=pluginmanager, args=args) except BaseException: config._ensure_unconfigure() raise @@ -235,7 +235,7 @@ def parse_hookimpl_opts(self, plugin, name): def parse_hookspec_opts(self, module_or_class, name): opts = super(PytestPluginManager, self).parse_hookspec_opts( - module_or_class, name) + module_or_class, name) if opts is None: method = getattr(module_or_class, name) if name.startswith("pytest_"): @@ -258,7 +258,7 @@ def register(self, plugin, name=None): ret = super(PytestPluginManager, self).register(plugin, name) if ret: self.hook.pytest_plugin_registered.call_historic( - kwargs=dict(plugin=plugin, manager=self)) + kwargs=dict(plugin=plugin, manager=self)) if isinstance(plugin, types.ModuleType): self.consider_module(plugin) @@ -1099,10 +1099,10 @@ def _checkversion(self): def parse(self, args, addopts=True): # parse given cmdline arguments into this config object. assert not hasattr(self, 'args'), ( - "can only parse cmdline args at most once per Config object") + "can only parse cmdline args at most once per Config object") self._origargs = args self.hook.pytest_addhooks.call_historic( - kwargs=dict(pluginmanager=self.pluginmanager)) + kwargs=dict(pluginmanager=self.pluginmanager)) self._preparse(args, addopts=addopts) # XXX deprecated hook: self.hook.pytest_cmdline_preparse(config=self, args=args) diff --git a/_pytest/deprecated.py b/_pytest/deprecated.py index e75ff099ee7..a2218b8c062 100644 --- a/_pytest/deprecated.py +++ b/_pytest/deprecated.py @@ -8,7 +8,7 @@ from __future__ import absolute_import, division, print_function MAIN_STR_ARGS = 'passing a string to pytest.main() is deprecated, ' \ - 'pass a list of arguments instead.' + 'pass a list of arguments instead.' YIELD_TESTS = 'yield tests are deprecated, and scheduled to be removed in pytest 4.0' diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 61069664e00..44c4397e6b1 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -172,9 +172,9 @@ def reorder_items_atscope(items, ignore, argkeys_cache, scopenum): 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 @@ -826,7 +826,7 @@ def __init__(self, scope, params, autouse=False, ids=None, name=None): 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 @@ -873,7 +873,7 @@ def fixture(scope="function", params=None, autouse=False, ids=None, name=None): if callable(scope) and params is None and autouse == False: # direct decoration return FixtureFunctionMarker( - "function", params, autouse, name=name)(scope) + "function", params, autouse, name=name)(scope) if params is not None and not isinstance(params, (list, tuple)): params = list(params) return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name) @@ -888,7 +888,7 @@ def yield_fixture(scope="function", params=None, autouse=False, ids=None, name=N if callable(scope) and params is None and not autouse: # direct decoration return FixtureFunctionMarker( - "function", params, autouse, ids=ids, name=name)(scope) + "function", params, autouse, ids=ids, name=name)(scope) else: return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name) diff --git a/_pytest/junitxml.py b/_pytest/junitxml.py index 301633706a9..9d098051cac 100644 --- a/_pytest/junitxml.py +++ b/_pytest/junitxml.py @@ -444,9 +444,9 @@ def _get_global_properties_node(self): """ if self.global_properties: return Junit.properties( - [ - Junit.property(name=name, value=value) - for name, value in self.global_properties - ] + [ + Junit.property(name=name, value=value) + for name, value in self.global_properties + ] ) return '' diff --git a/_pytest/monkeypatch.py b/_pytest/monkeypatch.py index a70b23dda91..39ac7701350 100644 --- a/_pytest/monkeypatch.py +++ b/_pytest/monkeypatch.py @@ -71,9 +71,9 @@ def annotated_getattr(obj, name, ann): obj = getattr(obj, name) except AttributeError: raise AttributeError( - '%r object at %s has no attribute %r' % ( - type(obj).__name__, ann, name - ) + '%r object at %s has no attribute %r' % ( + type(obj).__name__, ann, name + ) ) return obj diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 9b124f57ed2..9a02645859b 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -30,7 +30,7 @@ def pytest_addoption(parser): parser.addoption('--runpytest', default="inprocess", dest="runpytest", choices=("inprocess", "subprocess", ), - help=("run pytest sub runs in tests using an 'inprocess' " + help=("run pytest sub runs in tests using an 'inprocess' " "or 'subprocess' (python -m main) method")) @@ -1036,7 +1036,7 @@ def getdecoded(out): return out.decode("utf-8") except UnicodeDecodeError: return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % ( - py.io.saferepr(out),) + py.io.saferepr(out),) class LineComp: diff --git a/_pytest/python.py b/_pytest/python.py index 27b81247e94..0f49a07f98f 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -792,7 +792,7 @@ def parametrize(self, argnames, argvalues, indirect=False, ids=None, if not parameters: fs, lineno = getfslineno(self.function) reason = "got empty parameter set %r, function %s at %s:%d" % ( - argnames, self.function.__name__, fs, lineno) + argnames, self.function.__name__, fs, lineno) mark = MARK_GEN.skip(reason=reason) parameters.append(ParameterSet( values=(NOTSET,) * len(argnames), @@ -813,7 +813,7 @@ def parametrize(self, argnames, argvalues, indirect=False, ids=None, name = 'fixture' if indirect else 'argument' raise ValueError( "%r uses no %s %r" % ( - self.function, name, arg)) + self.function, name, arg)) if indirect is True: valtypes = dict.fromkeys(argnames, "params") diff --git a/_pytest/runner.py b/_pytest/runner.py index 5f4093b1d24..e15a53757b0 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -135,9 +135,9 @@ def call_and_report(item, when, log=True, **kwds): def check_interactive_exception(call, report): return call.excinfo and not ( - hasattr(report, "wasxfail") or - call.excinfo.errisinstance(skip.Exception) or - call.excinfo.errisinstance(bdb.BdbQuit)) + hasattr(report, "wasxfail") or + call.excinfo.errisinstance(skip.Exception) or + call.excinfo.errisinstance(bdb.BdbQuit)) def call_runtest_hook(item, when, **kwds): hookname = "pytest_runtest_" + when @@ -365,7 +365,7 @@ def location(self): def __repr__(self): return "" % ( - self.nodeid, len(self.result), self.outcome) + self.nodeid, len(self.result), self.outcome) class CollectErrorRepr(TerminalRepr): def __init__(self, msg): diff --git a/testing/code/test_source.py b/testing/code/test_source.py index e456da4094c..6a9b458ec81 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -537,7 +537,7 @@ def test_comment_in_statement(): ''' for line in range(1,3): assert str(getstatement(line, source)) == \ - 'test(foo=1,\n # comment 1\n bar=2)' + 'test(foo=1,\n # comment 1\n bar=2)' def test_single_line_else(): source = getstatement(1, "if False: 2\nelse: 3") diff --git a/testing/python/approx.py b/testing/python/approx.py index 3fac456ffee..6338441ae88 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -43,7 +43,7 @@ def test_operator_overloading(self): def test_exactly_equal(self): examples = [ - (2.0, 2.0), + (2.0, 2.0), (0.1e200, 0.1e200), (1.123e-300, 1.123e-300), (12345, 12345.0), @@ -57,7 +57,7 @@ def test_exactly_equal(self): def test_opposite_sign(self): examples = [ - (eq, 1e-100, -1e-100), + (eq, 1e-100, -1e-100), (ne, 1e100, -1e100), ] for op, a, x in examples: @@ -65,7 +65,7 @@ def test_opposite_sign(self): def test_zero_tolerance(self): within_1e10 = [ - (1.1e-100, 1e-100), + (1.1e-100, 1e-100), (-1.1e-100, -1e-100), ] for a, x in within_1e10: @@ -79,11 +79,11 @@ def test_zero_tolerance(self): def test_negative_tolerance(self): # Negative tolerances are not allowed. illegal_kwargs = [ - dict(rel=-1e100), - dict(abs=-1e100), - dict(rel=1e100, abs=-1e100), - dict(rel=-1e100, abs=1e100), - dict(rel=-1e100, abs=-1e100), + dict(rel=-1e100), + dict(abs=-1e100), + dict(rel=1e100, abs=-1e100), + dict(rel=-1e100, abs=1e100), + dict(rel=-1e100, abs=-1e100), ] for kwargs in illegal_kwargs: with pytest.raises(ValueError): @@ -92,7 +92,7 @@ def test_negative_tolerance(self): def test_inf_tolerance(self): # Everything should be equal if the tolerance is infinite. large_diffs = [ - (1, 1000), + (1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10), @@ -107,8 +107,8 @@ def test_inf_tolerance_expecting_zero(self): # If the relative tolerance is zero but the expected value is infinite, # the actual tolerance is a NaN, which should be an error. illegal_kwargs = [ - dict(rel=inf, abs=0.0), - dict(rel=inf, abs=inf), + dict(rel=inf, abs=0.0), + dict(rel=inf, abs=inf), ] for kwargs in illegal_kwargs: with pytest.raises(ValueError): @@ -116,9 +116,9 @@ def test_inf_tolerance_expecting_zero(self): def test_nan_tolerance(self): illegal_kwargs = [ - dict(rel=nan), - dict(abs=nan), - dict(rel=nan, abs=nan), + dict(rel=nan), + dict(abs=nan), + dict(rel=nan, abs=nan), ] for kwargs in illegal_kwargs: with pytest.raises(ValueError): @@ -135,7 +135,7 @@ def test_default_tolerances(self): # None of the other tests (except the doctests) should be affected by # the choice of defaults. examples = [ - # Relative tolerance used. + # Relative tolerance used. (eq, 1e100 + 1e94, 1e100), (ne, 1e100 + 2e94, 1e100), (eq, 1e0 + 1e-6, 1e0), @@ -166,7 +166,7 @@ def test_custom_tolerances(self): def test_relative_tolerance(self): within_1e8_rel = [ - (1e8 + 1e0, 1e8), + (1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8), ] @@ -176,7 +176,7 @@ def test_relative_tolerance(self): def test_absolute_tolerance(self): within_1e8_abs = [ - (1e8 + 9e-9, 1e8), + (1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8), ] @@ -201,7 +201,7 @@ def test_expecting_zero(self): def test_expecting_inf(self): examples = [ - (eq, inf, inf), + (eq, inf, inf), (eq, -inf, -inf), (ne, inf, -inf), (ne, 0.0, inf), @@ -212,7 +212,7 @@ def test_expecting_inf(self): def test_expecting_nan(self): examples = [ - (nan, nan), + (nan, nan), (-nan, -nan), (nan, -nan), (0.0, nan), @@ -230,7 +230,7 @@ def test_expecting_nan(self): def test_expecting_sequence(self): within_1e8 = [ - (1e8 + 1e0, 1e8), + (1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8), ] @@ -243,7 +243,7 @@ def test_expecting_sequence_wrong_len(self): def test_complex(self): 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.000001 + 1.0j, -1.0 + 1.0j), (1.0 - 1.000001j, 1.0 - 1.0j), @@ -254,7 +254,7 @@ def test_complex(self): def test_int(self): within_1e6 = [ - (1000001, 1000000), + (1000001, 1000000), (-1000001, -1000000), ] for a, x in within_1e6: @@ -263,7 +263,7 @@ def test_int(self): def test_decimal(self): within_1e6 = [ - (Decimal('1.000001'), Decimal('1.0')), + (Decimal('1.000001'), Decimal('1.0')), (Decimal('-1.000001'), Decimal('-1.0')), ] for a, x in within_1e6: @@ -272,7 +272,7 @@ def test_decimal(self): def test_fraction(self): within_1e6 = [ - (1 + Fraction(1, 1000000), Fraction(1)), + (1 + Fraction(1, 1000000), Fraction(1)), (-1 - Fraction(-1, 1000000), Fraction(-1)), ] for a, x in within_1e6: @@ -282,10 +282,10 @@ def test_fraction(self): def test_doctests(self): parser = doctest.DocTestParser() test = parser.get_doctest( - approx.__doc__, - {'approx': approx}, - approx.__name__, - None, None, + approx.__doc__, + {'approx': approx}, + approx.__name__, + None, None, ) runner = MyDocTestRunner() runner.run(test) diff --git a/testing/test_assertion.py b/testing/test_assertion.py index c385f6aa100..cf31f3d9263 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -772,7 +772,7 @@ def test_assertrepr_loaded_per_dir(testdir): b_conftest.write('def pytest_assertrepr_compare(): return ["summary b"]') result = testdir.runpytest() result.stdout.fnmatch_lines([ - '*def test_base():*', + '*def test_base():*', '*E*assert 1 == 2*', '*def test_a():*', '*E*assert summary a*', diff --git a/testing/test_mark.py b/testing/test_mark.py index 0792b04fd44..25ca7f0f104 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -200,7 +200,7 @@ def test_hello(): ]) @pytest.mark.parametrize("spec", [ - ("xyz", ("test_one",)), + ("xyz", ("test_one",)), ("xyz and xyz2", ()), ("xyz2", ("test_two",)), ("xyz or xyz2", ("test_one", "test_two"),) @@ -223,7 +223,7 @@ def test_two(): assert list(passed) == list(passed_result) @pytest.mark.parametrize("spec", [ - ("interface", ("test_interface",)), + ("interface", ("test_interface",)), ("not interface", ("test_nointer",)), ]) def test_mark_option_custom(spec, testdir): @@ -248,7 +248,7 @@ def test_nointer(): assert list(passed) == list(passed_result) @pytest.mark.parametrize("spec", [ - ("interface", ("test_interface",)), + ("interface", ("test_interface",)), ("not interface", ("test_nointer", "test_pass")), ("pass", ("test_pass",)), ("not pass", ("test_interface", "test_nointer")), @@ -271,7 +271,7 @@ def test_pass(): @pytest.mark.parametrize("spec", [ - ("None", ("test_func[None]",)), + ("None", ("test_func[None]",)), ("1.3", ("test_func[1.3]",)), ("2-3", ("test_func[2-3]",)) ]) diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index 1f0f4f602d8..d6cdfdb1f51 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -29,7 +29,7 @@ def pytest_myhook(xyz): config = get_config() pm = config.pluginmanager pm.hook.pytest_addhooks.call_historic( - kwargs=dict(pluginmanager=config.pluginmanager)) + kwargs=dict(pluginmanager=config.pluginmanager)) config.pluginmanager._importconftest(conf) #print(config.pluginmanager.get_plugins()) res = config.hook.pytest_myhook(xyz=10) diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py index fd167c36b22..31df4dd3945 100644 --- a/testing/test_resultlog.py +++ b/testing/test_resultlog.py @@ -6,7 +6,7 @@ import pytest from _pytest.main import Node, Item, FSCollector from _pytest.resultlog import generic_path, ResultLog, \ - pytest_configure, pytest_unconfigure + pytest_configure, pytest_unconfigure def test_generic_path(testdir): diff --git a/tox.ini b/tox.ini index 31957cfb1a8..f2c82ad1874 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E126,E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 57438f3efe487106a5bc779237c5e4e84bd3f4f0 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 19/58] Fixed E127 flake8 errors continuation line over-indented for visual indent --- _pytest/assertion/rewrite.py | 2 +- _pytest/compat.py | 2 +- _pytest/config.py | 2 +- _pytest/doctest.py | 2 +- _pytest/junitxml.py | 4 ++-- _pytest/pytester.py | 2 +- _pytest/python.py | 2 +- testing/code/test_excinfo.py | 2 +- testing/python/integration.py | 2 +- testing/test_collection.py | 2 +- testing/test_parseopt.py | 2 +- tox.ini | 2 +- 12 files changed, 13 insertions(+), 13 deletions(-) diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 6ec54d7e75a..1849d9cba50 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -723,7 +723,7 @@ def visit_Assert(self, assert_): if isinstance(assert_.test, ast.Tuple) and self.config is not None: fslocation = (self.module_path, assert_.lineno) self.config.warn('R1', 'assertion is always true, perhaps ' - 'remove parentheses?', fslocation=fslocation) + 'remove parentheses?', fslocation=fslocation) self.statements = [] self.variables = [] self.variable_counter = itertools.count() diff --git a/_pytest/compat.py b/_pytest/compat.py index 269a23504be..1b2d95ce34d 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -79,7 +79,7 @@ def num_mock_patch_args(function): 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) diff --git a/_pytest/config.py b/_pytest/config.py index d70ea450726..bf51c67f49d 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -304,7 +304,7 @@ def _set_initial_conftests(self, namespace): """ current = py.path.local() self._confcutdir = current.join(namespace.confcutdir, abs=True) \ - if namespace.confcutdir else None + if namespace.confcutdir else None self._noconftest = namespace.noconftest testpaths = namespace.file_or_dir foundanchor = False diff --git a/_pytest/doctest.py b/_pytest/doctest.py index cbd39652e0a..f6d36c3de48 100644 --- a/_pytest/doctest.py +++ b/_pytest/doctest.py @@ -132,7 +132,7 @@ def repr_failure(self, excinfo): else: inner_excinfo = ExceptionInfo(excinfo.value.exc_info) lines += ["UNEXPECTED EXCEPTION: %s" % - repr(inner_excinfo.value)] + repr(inner_excinfo.value)] lines += traceback.format_exception(*excinfo.value.exc_info) return ReprFailDoctest(reprlocation, lines) else: diff --git a/_pytest/junitxml.py b/_pytest/junitxml.py index 9d098051cac..ed3ba2e9a53 100644 --- a/_pytest/junitxml.py +++ b/_pytest/junitxml.py @@ -378,8 +378,8 @@ def pytest_runtest_logreport(self, report): close_report = next( (rep for rep in self.open_reports if (rep.nodeid == report.nodeid and - getattr(rep, "item_index", None) == report_ii and - getattr(rep, "worker_id", None) == report_wid + getattr(rep, "item_index", None) == report_ii and + getattr(rep, "worker_id", None) == report_wid ) ), None) if close_report: diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 9a02645859b..175aaa1dec3 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -31,7 +31,7 @@ def pytest_addoption(parser): parser.addoption('--runpytest', default="inprocess", dest="runpytest", choices=("inprocess", "subprocess", ), help=("run pytest sub runs in tests using an 'inprocess' " - "or 'subprocess' (python -m main) method")) + "or 'subprocess' (python -m main) method")) def pytest_configure(config): diff --git a/_pytest/python.py b/_pytest/python.py index 0f49a07f98f..72084cb4750 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -904,7 +904,7 @@ def _find_parametrized_scope(argnames, arg2fixturedefs, indirect): from _pytest.fixtures import scopes indirect_as_list = isinstance(indirect, (list, tuple)) all_arguments_are_fixtures = indirect is True or \ - indirect_as_list and len(indirect) == argnames + indirect_as_list and len(indirect) == argnames if all_arguments_are_fixtures: fixturedefs = arg2fixturedefs or {} used_scopes = [fixturedef[0].scope for name, fixturedef in fixturedefs.items()] diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 7da68e59890..9e32adf22b5 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -339,7 +339,7 @@ def test_excinfo_no_python_sourcecode(tmpdir): env = jinja2.Environment(loader=loader) template = env.get_template('test.txt') excinfo = pytest.raises(ValueError, - template.render, h=h) + template.render, h=h) for item in excinfo.traceback: print(item) #XXX: for some reason jinja.Template.render is printed in full item.source # shouldnt fail diff --git a/testing/python/integration.py b/testing/python/integration.py index 4f888276b71..c346b93be85 100644 --- a/testing/python/integration.py +++ b/testing/python/integration.py @@ -173,7 +173,7 @@ def test_someting(normpath, abspath, tmpdir): reprec.assertoutcome(passed=2) calls = reprec.getcalls("pytest_runtest_logreport") funcnames = [call.report.location[2] for call in calls - if call.report.when == "call"] + if call.report.when == "call"] assert funcnames == ["T.test_hello", "test_someting"] def test_mock_sorting(self, testdir): diff --git a/testing/test_collection.py b/testing/test_collection.py index a90269789d0..6dcb7eda24a 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -460,7 +460,7 @@ def test_collect_subdir_event_ordering(self, testdir): ("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): diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index 38542783aff..f17519d8dc6 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -188,7 +188,7 @@ def defaultget(option): def test_drop_short_helper(self): parser = py.std.argparse.ArgumentParser(formatter_class=parseopt.DropShorterLongHelpFormatter) parser.add_argument('-t', '--twoword', '--duo', '--two-word', '--two', - help='foo').map_long_option = {'two': 'two-word'} + help='foo').map_long_option = {'two': 'two-word'} # throws error on --deux only! parser.add_argument('-d', '--deuxmots', '--deux-mots', action='store_true', help='foo').map_long_option = {'deux': 'deux-mots'} diff --git a/tox.ini b/tox.ini index f2c82ad1874..6b6d060b73d 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E127,E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From cf97159009723be555aaa724df18f6f38a417bd2 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 20/58] Fixed E128 flake8 errors continuation line under-indented for visual indent --- _pytest/_code/code.py | 8 +++--- _pytest/_code/source.py | 2 +- _pytest/cacheprovider.py | 2 +- _pytest/compat.py | 2 +- _pytest/config.py | 18 ++++++------ _pytest/doctest.py | 30 +++++++++---------- _pytest/fixtures.py | 10 +++---- _pytest/helpconfig.py | 32 ++++++++++----------- _pytest/main.py | 44 ++++++++++++++-------------- _pytest/pastebin.py | 6 ++-- _pytest/pytester.py | 20 ++++++------- _pytest/python.py | 54 +++++++++++++++++------------------ _pytest/resultlog.py | 4 +-- _pytest/runner.py | 12 ++++---- _pytest/skipping.py | 34 +++++++++++----------- _pytest/terminal.py | 36 +++++++++++------------ _pytest/tmpdir.py | 2 +- _pytest/unittest.py | 4 +-- testing/code/test_excinfo.py | 2 +- testing/python/collect.py | 6 ++-- testing/python/metafunc.py | 8 +++--- testing/test_argcomplete.py | 8 +++--- testing/test_assertrewrite.py | 2 +- testing/test_capture.py | 2 +- testing/test_config.py | 2 +- testing/test_doctest.py | 8 +++--- testing/test_parseopt.py | 2 +- testing/test_pluginmanager.py | 2 +- testing/test_terminal.py | 8 +++--- tox.ini | 2 +- 30 files changed, 186 insertions(+), 186 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 77baa324714..49c300b3066 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -339,8 +339,8 @@ def recursionindex(self): loc = f.f_locals for otherloc in l: if f.is_true(f.eval(co_equal, - __recursioncache_locals_1=loc, - __recursioncache_locals_2=otherloc)): + __recursioncache_locals_1=loc, + __recursioncache_locals_2=otherloc)): return i l.append(entry.frame.f_locals) return None @@ -408,7 +408,7 @@ def _getreprcrash(self): return ReprFileLocation(path, lineno+1, exconly) def getrepr(self, showlocals=False, style="long", - abspath=False, tbfilter=True, funcargs=False): + abspath=False, tbfilter=True, funcargs=False): """ return str()able representation of this exception info. showlocals: show locals per traceback entry style: long|short|no|native traceback style @@ -425,7 +425,7 @@ def getrepr(self, showlocals=False, style="long", )), self._getreprcrash()) fmt = FormattedExcinfo(showlocals=showlocals, style=style, - abspath=abspath, tbfilter=tbfilter, funcargs=funcargs) + abspath=abspath, tbfilter=tbfilter, funcargs=funcargs) return fmt.repr_excinfo(self) def __str__(self): diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 93c59cace0e..37c1b5fa9e0 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -199,7 +199,7 @@ def compile(self, filename=None, mode='exec', # def compile_(source, filename=None, mode='exec', flags= - generators.compiler_flag, dont_inherit=0): + generators.compiler_flag, dont_inherit=0): """ compile the given source to a raw code object, and maintain an internal cache which allows later retrieval of the source code for the code object diff --git a/_pytest/cacheprovider.py b/_pytest/cacheprovider.py index 7fc08fff368..de3fa458941 100755 --- a/_pytest/cacheprovider.py +++ b/_pytest/cacheprovider.py @@ -224,7 +224,7 @@ def cacheshow(config, session): val = config.cache.get(key, dummy) if val is dummy: tw.line("%s contains unreadable content, " - "will be ignored" % key) + "will be ignored" % key) else: tw.line("%s contains:" % key) stream = py.io.TextIO() diff --git a/_pytest/compat.py b/_pytest/compat.py index 1b2d95ce34d..38c0f1facc5 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -59,7 +59,7 @@ def iscoroutinefunction(func): which in turns also initializes the "logging" module as side-effect (see issue #8). """ return (getattr(func, '_is_coroutine', False) or - (hasattr(inspect, 'iscoroutinefunction') and inspect.iscoroutinefunction(func))) + (hasattr(inspect, 'iscoroutinefunction') and inspect.iscoroutinefunction(func))) def getlocation(function, curdir): diff --git a/_pytest/config.py b/_pytest/config.py index bf51c67f49d..2c0da564054 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -276,11 +276,11 @@ def pytest_configure(self, config): # XXX now that the pluginmanager exposes hookimpl(tryfirst...) # we should remove tryfirst/trylast as markers config.addinivalue_line("markers", - "tryfirst: mark a hook implementation function such that the " - "plugin machinery will try to call it first/as early as possible.") + "tryfirst: mark a hook implementation function such that the " + "plugin machinery will try to call it first/as early as possible.") config.addinivalue_line("markers", - "trylast: mark a hook implementation function such that the " - "plugin machinery will try to call it last/as late as possible.") + "trylast: mark a hook implementation function such that the " + "plugin machinery will try to call it last/as late as possible.") def _warn(self, message): kwargs = message if isinstance(message, dict) else { @@ -777,7 +777,7 @@ def __init__(self, parser, extra_info=None): extra_info = {} self._parser = parser argparse.ArgumentParser.__init__(self, usage=parser._usage, - add_help=False, formatter_class=DropShorterLongHelpFormatter) + add_help=False, formatter_class=DropShorterLongHelpFormatter) # extra_info is a dict of (param -> value) to display if there's # an usage error to provide more contextual information to the user self.extra_info = extra_info @@ -940,9 +940,9 @@ def notify_exception(self, excinfo, option=None): else: style = "native" excrepr = excinfo.getrepr(funcargs=True, - showlocals=getattr(option, 'showlocals', False), - style=style, - ) + showlocals=getattr(option, 'showlocals', False), + style=style, + ) res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo) if not py.builtin.any(res): @@ -1074,7 +1074,7 @@ def _preparse(self, args, addopts=True): self.known_args_namespace.confcutdir = confcutdir try: self.hook.pytest_load_initial_conftests(early_config=self, - args=args, parser=self._parser) + args=args, parser=self._parser) except ConftestImportFailure: e = sys.exc_info()[1] if ns.help or ns.version: diff --git a/_pytest/doctest.py b/_pytest/doctest.py index f6d36c3de48..4968504e464 100644 --- a/_pytest/doctest.py +++ b/_pytest/doctest.py @@ -24,26 +24,26 @@ def pytest_addoption(parser): parser.addini('doctest_optionflags', 'option flags for doctests', - type="args", default=["ELLIPSIS"]) + type="args", default=["ELLIPSIS"]) parser.addini("doctest_encoding", 'encoding used for doctest files', default="utf-8") group = parser.getgroup("collect") group.addoption("--doctest-modules", - action="store_true", default=False, - help="run doctests in all .py modules", - dest="doctestmodules") + action="store_true", default=False, + help="run doctests in all .py modules", + dest="doctestmodules") group.addoption("--doctest-report", - type=str.lower, default="udiff", - help="choose another output format for diffs on doctest failure", - choices=DOCTEST_REPORT_CHOICES, - dest="doctestreport") + type=str.lower, default="udiff", + help="choose another output format for diffs on doctest failure", + choices=DOCTEST_REPORT_CHOICES, + dest="doctestreport") group.addoption("--doctest-glob", - action="append", default=[], metavar="pat", - help="doctests file matching pattern, default: test*.txt", - dest="doctestglob") + action="append", default=[], metavar="pat", + help="doctests file matching pattern, default: test*.txt", + dest="doctestglob") group.addoption("--doctest-ignore-import-errors", - action="store_true", default=False, - help="ignore doctest ImportErrors", - dest="doctest_ignore_import_errors") + action="store_true", default=False, + help="ignore doctest ImportErrors", + dest="doctest_ignore_import_errors") def pytest_collect_file(path, parent): @@ -128,7 +128,7 @@ def repr_failure(self, excinfo): indent = '...' if excinfo.errisinstance(doctest.DocTestFailure): lines += checker.output_difference(example, - doctestfailure.got, report_choice).split("\n") + doctestfailure.got, report_choice).split("\n") else: inner_excinfo = ExceptionInfo(excinfo.value.exc_info) lines += ["UNEXPECTED EXCEPTION: %s" % diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 44c4397e6b1..c10bde4d959 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -106,9 +106,9 @@ def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): arg2fixturedefs[argname] = [node._name2pseudofixturedef[argname]] else: fixturedef = FixtureDef(fixturemanager, '', argname, - get_direct_param_fixture_func, - arg2scope[argname], - valuelist, False, False) + get_direct_param_fixture_func, + arg2scope[argname], + valuelist, False, False) arg2fixturedefs[argname] = [fixturedef] if node is not None: node._name2pseudofixturedef[argname] = fixturedef @@ -528,7 +528,7 @@ def _check_scope(self, argname, invoking_scope, requested_scope): "fixture %r with a %r scoped request object, " "involved factories\n%s" % ( (requested_scope, argname, invoking_scope, "\n".join(lines))), - pytrace=False) + pytrace=False) def _factorytraceback(self): lines = [] @@ -699,7 +699,7 @@ def teardown(): pass else: fail_fixturefunc(fixturefunc, - "yield_fixture function has more than one 'yield'") + "yield_fixture function has more than one 'yield'") request.addfinalizer(teardown) else: diff --git a/_pytest/helpconfig.py b/_pytest/helpconfig.py index 240fa67cc0b..05d9838035c 100644 --- a/_pytest/helpconfig.py +++ b/_pytest/helpconfig.py @@ -41,20 +41,20 @@ def __call__(self, parser, namespace, values, option_string=None): def pytest_addoption(parser): group = parser.getgroup('debugconfig') group.addoption('--version', action="store_true", - help="display pytest lib version and import information.") + help="display pytest lib version and import information.") group._addoption("-h", "--help", action=HelpAction, dest="help", - help="show help message and configuration info") + help="show help message and configuration info") group._addoption('-p', action="append", dest="plugins", default = [], - metavar="name", - help="early-load given plugin (multi-allowed). " - "To avoid loading of plugins, use the `no:` prefix, e.g. " - "`no:doctest`.") + metavar="name", + help="early-load given plugin (multi-allowed). " + "To avoid loading of plugins, use the `no:` prefix, e.g. " + "`no:doctest`.") group.addoption('--traceconfig', '--trace-config', - action="store_true", default=False, - help="trace considerations of conftest.py files."), + action="store_true", default=False, + help="trace considerations of conftest.py files."), group.addoption('--debug', - action="store_true", dest="debug", default=False, - help="store internal tracing debug information in 'pytestdebug.log'.") + action="store_true", dest="debug", default=False, + help="store internal tracing debug information in 'pytestdebug.log'.") group._addoption( '-o', '--override-ini', nargs='*', dest="override_ini", action="append", @@ -69,10 +69,10 @@ def pytest_cmdline_parse(): path = os.path.abspath("pytestdebug.log") debugfile = open(path, 'w') debugfile.write("versions pytest-%s, py-%s, " - "python-%s\ncwd=%s\nargs=%s\n\n" %( - pytest.__version__, py.__version__, - ".".join(map(str, sys.version_info)), - os.getcwd(), config._origargs)) + "python-%s\ncwd=%s\nargs=%s\n\n" %( + pytest.__version__, py.__version__, + ".".join(map(str, sys.version_info)), + os.getcwd(), config._origargs)) config.trace.root.setwriter(debugfile.write) undo_tracing = config.pluginmanager.enable_tracing() sys.stderr.write("writing pytestdebug information to %s\n" % path) @@ -90,7 +90,7 @@ def pytest_cmdline_main(config): if config.option.version: p = py.path.local(pytest.__file__) sys.stderr.write("This is pytest version %s, imported from %s\n" % - (pytest.__version__, p)) + (pytest.__version__, p)) plugininfo = getpluginversioninfo(config) if plugininfo: for line in plugininfo: @@ -161,7 +161,7 @@ def pytest_report_header(config): lines = [] if config.option.debug or config.option.traceconfig: lines.append("using: pytest-%s pylib-%s" % - (pytest.__version__,py.__version__)) + (pytest.__version__,py.__version__)) verinfo = getpluginversioninfo(config) if verinfo: diff --git a/_pytest/main.py b/_pytest/main.py index 2cc15598f6f..712965a639d 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -29,9 +29,9 @@ def pytest_addoption(parser): parser.addini("norecursedirs", "directory patterns to avoid for recursion", - type="args", default=['.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv']) + type="args", default=['.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv']) parser.addini("testpaths", "directories to search for tests when no files or directories are given in the command line.", - type="args", default=[]) + type="args", default=[]) #parser.addini("dirpatterns", # "patterns specifying possible locations of test files", # type="linelist", default=["**/test_*.txt", @@ -39,42 +39,42 @@ def pytest_addoption(parser): #) group = parser.getgroup("general", "running and selection options") group._addoption('-x', '--exitfirst', action="store_const", - dest="maxfail", const=1, - help="exit instantly on first error or failed test."), + dest="maxfail", const=1, + help="exit instantly on first error or failed test."), group._addoption('--maxfail', metavar="num", - action="store", type=int, dest="maxfail", default=0, - help="exit after first num failures or errors.") + action="store", type=int, dest="maxfail", default=0, + help="exit after first num failures or errors.") group._addoption('--strict', action="store_true", - help="marks not registered in configuration file raise errors.") + help="marks not registered in configuration file raise errors.") group._addoption("-c", metavar="file", type=str, dest="inifilename", - help="load configuration from `file` instead of trying to locate one of the implicit configuration files.") + help="load configuration from `file` instead of trying to locate one of the implicit configuration files.") group._addoption("--continue-on-collection-errors", action="store_true", - default=False, dest="continue_on_collection_errors", - help="Force test execution even if collection errors occur.") + default=False, dest="continue_on_collection_errors", + help="Force test execution even if collection errors occur.") group = parser.getgroup("collect", "collection") group.addoption('--collectonly', '--collect-only', action="store_true", - help="only collect tests, don't execute them."), + help="only collect tests, don't execute them."), group.addoption('--pyargs', action="store_true", - help="try to interpret all arguments as python packages.") + help="try to interpret all arguments as python packages.") group.addoption("--ignore", action="append", metavar="path", - help="ignore path during collection (multi-allowed).") + help="ignore path during collection (multi-allowed).") # when changing this to --conf-cut-dir, config.py Conftest.setinitial # needs upgrading as well group.addoption('--confcutdir', dest="confcutdir", default=None, - metavar="dir", type=functools.partial(directory_arg, optname="--confcutdir"), - help="only load conftest.py's relative to specified dir.") + metavar="dir", type=functools.partial(directory_arg, optname="--confcutdir"), + help="only load conftest.py's relative to specified dir.") group.addoption('--noconftest', action="store_true", - dest="noconftest", default=False, - help="Don't load any conftest.py files.") + dest="noconftest", default=False, + help="Don't load any conftest.py files.") group.addoption('--keepduplicates', '--keep-duplicates', action="store_true", - dest="keepduplicates", default=False, - help="Keep duplicate tests.") + dest="keepduplicates", default=False, + help="Keep duplicate tests.") group = parser.getgroup("debugconfig", - "test session debugging and configuration") + "test session debugging and configuration") group.addoption('--basetemp', dest="basetemp", default=None, metavar="dir", - help="base temporary directory for this test run.") + help="base temporary directory for this test run.") @@ -618,7 +618,7 @@ def perform_collect(self, args=None, genitems=True): items = self._perform_collect(args, genitems) self.config.pluginmanager.check_pending() hook.pytest_collection_modifyitems(session=self, - config=self.config, items=items) + config=self.config, items=items) finally: hook.pytest_collection_finish(session=self) self.testscollected = len(items) diff --git a/_pytest/pastebin.py b/_pytest/pastebin.py index 6f3ce8feddd..54590b48c6c 100644 --- a/_pytest/pastebin.py +++ b/_pytest/pastebin.py @@ -9,9 +9,9 @@ def pytest_addoption(parser): group = parser.getgroup("terminal reporting") group._addoption('--pastebin', metavar="mode", - action='store', dest="pastebin", default=None, - choices=['failed', 'all'], - help="send failed|all info to bpaste.net pastebin service.") + action='store', dest="pastebin", default=None, + choices=['failed', 'all'], + help="send failed|all info to bpaste.net pastebin service.") @pytest.hookimpl(trylast=True) diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 175aaa1dec3..d85cb45db60 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -25,13 +25,13 @@ def pytest_addoption(parser): # group = parser.getgroup("pytester", "pytester (self-tests) options") parser.addoption('--lsof', - action="store_true", dest="lsof", default=False, - help=("run FD checks if lsof is available")) + action="store_true", dest="lsof", default=False, + help=("run FD checks if lsof is available")) parser.addoption('--runpytest', default="inprocess", dest="runpytest", - choices=("inprocess", "subprocess", ), - help=("run pytest sub runs in tests using an 'inprocess' " - "or 'subprocess' (python -m main) method")) + choices=("inprocess", "subprocess", ), + help=("run pytest sub runs in tests using an 'inprocess' " + "or 'subprocess' (python -m main) method")) def pytest_configure(config): @@ -62,7 +62,7 @@ def _exec_lsof(self): 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) + 'mem' not in line and "txt" not in line and 'cwd' not in line) open_files = [] @@ -130,7 +130,7 @@ def getexecutable(name, cache={}): if executable: import subprocess popen = subprocess.Popen([str(executable), "--version"], - universal_newlines=True, stderr=subprocess.PIPE) + universal_newlines=True, stderr=subprocess.PIPE) out, err = popen.communicate() if name == "jython": if not err or "2.5" not in err: @@ -264,7 +264,7 @@ def getreports(self, return [x.report for x in self.getcalls(names)] def matchreport(self, inamepart="", - names="pytest_runtest_logreport pytest_collectreport", when=None): + names="pytest_runtest_logreport pytest_collectreport", when=None): """ return a testreport whose dotted import path matches """ l = [] for rep in self.getreports(names=names): @@ -933,7 +933,7 @@ def _run(self, *cmdargs): try: now = time.time() popen = self.popen(cmdargs, stdout=f1, stderr=f2, - close_fds=(sys.platform != "win32")) + close_fds=(sys.platform != "win32")) ret = popen.wait() finally: f1.close() @@ -987,7 +987,7 @@ def runpytest_subprocess(self, *args, **kwargs): """ p = py.path.local.make_numbered_dir(prefix="runpytest-", - keep=None, rootdir=self.tmpdir) + keep=None, rootdir=self.tmpdir) args = ('--basetemp=%s' % p, ) + args #for x in args: # if '--confcutdir' in str(x): diff --git a/_pytest/python.py b/_pytest/python.py index 72084cb4750..9af0a27f0a2 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -62,8 +62,8 @@ def get(self): 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") + action="store_true", dest="showfixtures", default=False, + help="show available fixtures, sorted by plugin appearance") group.addoption( '--fixtures-per-test', action="store_true", @@ -72,20 +72,20 @@ def pytest_addoption(parser): help="show fixtures per test", ) parser.addini("usefixtures", type="args", default=[], - help="list of default fixtures to be used with this project") + help="list of default fixtures to be used with this project") parser.addini("python_files", type="args", - default=['test_*.py', '*_test.py'], - help="glob-style file patterns for Python test module discovery") + default=['test_*.py', '*_test.py'], + help="glob-style file patterns for Python test module discovery") parser.addini("python_classes", type="args", default=["Test",], - help="prefixes or glob names for Python test class discovery") + help="prefixes or glob names for Python test class discovery") parser.addini("python_functions", type="args", default=["test",], - help="prefixes or glob names for Python test function and " - "method discovery") + help="prefixes or glob names for Python test function and " + "method discovery") group.addoption("--import-mode", default="prepend", - choices=["prepend", "append"], dest="importmode", - help="prepend/append to sys.path when importing test modules, " - "default is to prepend.") + choices=["prepend", "append"], dest="importmode", + help="prepend/append to sys.path when importing test modules, " + "default is to prepend.") def pytest_cmdline_main(config): @@ -114,18 +114,18 @@ def pytest_generate_tests(metafunc): def pytest_configure(config): 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 " - "or a list of tuples of values if argnames specifies multiple names. " - "Example: @parametrize('arg1', [1,2]) would lead to two calls of the " - "decorated test function, one with arg1=1 and another with arg1=2." - "see http://pytest.org/latest/parametrize.html for more info and " - "examples." + "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 " + "or a list of tuples of values if argnames specifies multiple names. " + "Example: @parametrize('arg1', [1,2]) would lead to two calls of the " + "decorated test function, one with arg1=1 and another with arg1=2." + "see http://pytest.org/latest/parametrize.html for more info and " + "examples." ) config.addinivalue_line("markers", - "usefixtures(fixturename1, fixturename2, ...): mark tests as needing " - "all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures " + "usefixtures(fixturename1, fixturename2, ...): mark tests as needing " + "all of the specified fixtures. see http://pytest.org/latest/fixture.html#usefixtures " ) @@ -177,8 +177,8 @@ def pytest_pycollect_makeitem(collector, name, obj): # We musn't if it's been wrapped with mock.patch (python 2 only) if not (isfunction(obj) or isfunction(get_real_func(obj))): collector.warn(code="C2", message= - "cannot collect %r because it is not a function." - % name, ) + "cannot collect %r because it is not a function." + % name, ) elif getattr(obj, "__test__", True): if is_generator(obj): res = Generator(name, parent=collector) @@ -496,7 +496,7 @@ def collect(self): return [] 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 [] elif hasnew(self.obj): self.warn("C1", "cannot collect test class %r because it has a " @@ -582,7 +582,7 @@ def _repr_failure_py(self, excinfo, style="long"): if not excinfo.value.pytrace: return py._builtin._totext(excinfo.value) return super(FunctionMixin, self)._repr_failure_py(excinfo, - style=style) + style=style) def repr_failure(self, excinfo, outerr=None): assert outerr is None, "XXX outerr usage is deprecated" @@ -737,7 +737,7 @@ def __init__(self, function, fixtureinfo, config, cls=None, module=None): self._arg2fixturedefs = fixtureinfo.name2fixturedefs 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 @@ -1088,7 +1088,7 @@ def _showfixtures_main(config, session): tw.line(" " + line.strip()) else: tw.line(" %s: no docstring available" %(loc,), - red=True) + red=True) # builtin pytest.raises helper diff --git a/_pytest/resultlog.py b/_pytest/resultlog.py index 3e4b00cf9bb..615575aa0d2 100644 --- a/_pytest/resultlog.py +++ b/_pytest/resultlog.py @@ -9,8 +9,8 @@ def pytest_addoption(parser): group = parser.getgroup("terminal reporting", "resultlog plugin options") group.addoption('--resultlog', '--result-log', action="store", - metavar="path", default=None, - help="DEPRECATED path for machine-readable result log.") + metavar="path", default=None, + help="DEPRECATED path for machine-readable result log.") def pytest_configure(config): resultlog = config.option.resultlog diff --git a/_pytest/runner.py b/_pytest/runner.py index e15a53757b0..6e3ad034627 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -16,8 +16,8 @@ def pytest_addoption(parser): group = parser.getgroup("terminal reporting", "reporting", after="general") group.addoption('--durations', - action="store", type=int, default=None, metavar="N", - help="show N slowest setup/test durations (N=0 for all)."), + action="store", type=int, default=None, metavar="N", + help="show N slowest setup/test durations (N=0 for all)."), def pytest_terminal_summary(terminalreporter): durations = terminalreporter.config.option.durations @@ -42,7 +42,7 @@ def pytest_terminal_summary(terminalreporter): for rep in dlist: nodeid = rep.nodeid.replace("::()::", "::") tr.write_line("%02.2fs %-8s %s" % - (rep.duration, rep.when, nodeid)) + (rep.duration, rep.when, nodeid)) def pytest_sessionstart(session): session._setupstate = SetupState() @@ -72,7 +72,7 @@ def runtestprotocol(item, log=True, nextitem=None): if not item.config.option.setuponly: reports.append(call_and_report(item, "call", log)) reports.append(call_and_report(item, "teardown", log, - nextitem=nextitem)) + nextitem=nextitem)) # after all teardown hooks have been called # want funcargs and request info to go away if hasrequest: @@ -266,7 +266,7 @@ def pytest_runtest_makereport(item, call): longrepr = item.repr_failure(excinfo) else: # exception in setup or teardown longrepr = item._repr_failure_py(excinfo, - style=item.config.option.tbstyle) + style=item.config.option.tbstyle) for rwhen, key, content in item._report_sections: sections.append(("Captured %s %s" %(key, rwhen), content)) return TestReport(item.nodeid, item.location, @@ -344,7 +344,7 @@ def pytest_make_collect_report(collector): errorinfo = CollectErrorRepr(errorinfo) longrepr = errorinfo rep = CollectReport(collector.nodeid, outcome, longrepr, - getattr(call, 'result', None)) + getattr(call, 'result', None)) rep.call = call # see collect_one_node return rep diff --git a/_pytest/skipping.py b/_pytest/skipping.py index 6bf62292d4c..2aafa141835 100644 --- a/_pytest/skipping.py +++ b/_pytest/skipping.py @@ -13,8 +13,8 @@ def pytest_addoption(parser): group = parser.getgroup("general") group.addoption('--runxfail', - action="store_true", dest="runxfail", default=False, - help="run tests even if they are marked xfail") + action="store_true", dest="runxfail", default=False, + help="run tests even if they are marked xfail") parser.addini("xfail_strict", "default for the strict parameter of xfail " "markers when not given explicitly (default: " @@ -37,25 +37,25 @@ def nop(*args, **kwargs): setattr(pytest, "xfail", nop) config.addinivalue_line("markers", - "skip(reason=None): skip the given test function with an optional reason. " - "Example: skip(reason=\"no way of currently testing this\") skips the " - "test." + "skip(reason=None): skip the given test function with an optional reason. " + "Example: skip(reason=\"no way of currently testing this\") skips the " + "test." ) config.addinivalue_line("markers", - "skipif(condition): skip the given test function if eval(condition) " - "results in a True value. Evaluation happens within the " - "module global context. Example: skipif('sys.platform == \"win32\"') " - "skips the test if we are on the win32 platform. see " - "http://pytest.org/latest/skipping.html" + "skipif(condition): skip the given test function if eval(condition) " + "results in a True value. Evaluation happens within the " + "module global context. Example: skipif('sys.platform == \"win32\"') " + "skips the test if we are on the win32 platform. see " + "http://pytest.org/latest/skipping.html" ) config.addinivalue_line("markers", - "xfail(condition, reason=None, run=True, raises=None, strict=False): " - "mark the test function as an expected failure if eval(condition) " - "has a True value. Optionally specify a reason for better reporting " - "and run=False if you don't even want to execute the test function. " - "If only specific exception(s) are expected, you can list them in " - "raises, and if the test fails in other ways, it will be reported as " - "a true failure. See http://pytest.org/latest/skipping.html" + "xfail(condition, reason=None, run=True, raises=None, strict=False): " + "mark the test function as an expected failure if eval(condition) " + "has a True value. Optionally specify a reason for better reporting " + "and run=False if you don't even want to execute the test function. " + "If only specific exception(s) are expected, you can list them in " + "raises, and if the test fails in other ways, it will be reported as " + "a true failure. See http://pytest.org/latest/skipping.html" ) diff --git a/_pytest/terminal.py b/_pytest/terminal.py index 0bf861ebefa..f57f6e46603 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -19,33 +19,33 @@ def pytest_addoption(parser): group = parser.getgroup("terminal reporting", "reporting", after="general") group._addoption('-v', '--verbose', action="count", - dest="verbose", default=0, help="increase verbosity."), + dest="verbose", default=0, help="increase verbosity."), group._addoption('-q', '--quiet', action="count", - dest="quiet", default=0, help="decrease verbosity."), + dest="quiet", default=0, help="decrease verbosity."), group._addoption('-r', - action="store", dest="reportchars", default='', metavar="chars", - help="show extra test summary info as specified by chars (f)ailed, " - "(E)error, (s)skipped, (x)failed, (X)passed, " - "(p)passed, (P)passed with output, (a)all except pP. " - "Warnings are displayed at all times except when " - "--disable-warnings is set") + action="store", dest="reportchars", default='', metavar="chars", + help="show extra test summary info as specified by chars (f)ailed, " + "(E)error, (s)skipped, (x)failed, (X)passed, " + "(p)passed, (P)passed with output, (a)all except pP. " + "Warnings are displayed at all times except when " + "--disable-warnings is set") group._addoption('--disable-warnings', '--disable-pytest-warnings', default=False, dest='disable_warnings', action='store_true', help='disable warnings summary') group._addoption('-l', '--showlocals', - action="store_true", dest="showlocals", default=False, - help="show locals in tracebacks (disabled by default).") + action="store_true", dest="showlocals", default=False, + help="show locals in tracebacks (disabled by default).") group._addoption('--tb', metavar="style", - action="store", dest="tbstyle", default='auto', - choices=['auto', 'long', 'short', 'no', 'line', 'native'], - help="traceback print mode (auto/long/short/line/native/no).") + action="store", dest="tbstyle", default='auto', + choices=['auto', 'long', 'short', 'no', 'line', 'native'], + help="traceback print mode (auto/long/short/line/native/no).") group._addoption('--fulltrace', '--full-trace', - action="store_true", default=False, - help="don't cut any tracebacks (default is to cut).") + action="store_true", default=False, + help="don't cut any tracebacks (default is to cut).") group._addoption('--color', metavar="color", - action="store", dest="color", default='auto', - choices=['yes', 'no', 'auto'], - help="color terminal output (yes/no/auto).") + action="store", dest="color", default='auto', + choices=['yes', 'no', 'auto'], + help="color terminal output (yes/no/auto).") def pytest_configure(config): config.option.verbose -= config.option.quiet diff --git a/_pytest/tmpdir.py b/_pytest/tmpdir.py index 5960140595d..78392e378b3 100644 --- a/_pytest/tmpdir.py +++ b/_pytest/tmpdir.py @@ -38,7 +38,7 @@ def mktemp(self, basename, numbered=True): p = basetemp.mkdir(basename) else: p = py.path.local.make_numbered_dir(prefix=basename, - keep=0, rootdir=basetemp, lock_timeout=None) + keep=0, rootdir=basetemp, lock_timeout=None) self.trace("mktemp", p) return p diff --git a/_pytest/unittest.py b/_pytest/unittest.py index 2000c4d0066..64cb5f5ee18 100644 --- a/_pytest/unittest.py +++ b/_pytest/unittest.py @@ -210,7 +210,7 @@ def pytest_runtest_protocol(item): check_testcase_implements_trial_reporter() def excstore(self, exc_value=None, exc_type=None, exc_tb=None, - captureVars=None): + captureVars=None): if exc_value is None: self._rawexcinfo = sys.exc_info() else: @@ -219,7 +219,7 @@ def excstore(self, exc_value=None, exc_type=None, exc_tb=None, self._rawexcinfo = (exc_type, exc_value, exc_tb) try: Failure__init__(self, exc_value, exc_type, exc_tb, - captureVars=captureVars) + captureVars=captureVars) except TypeError: Failure__init__(self, exc_value, exc_type, exc_tb) diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 9e32adf22b5..7623da319f3 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -298,7 +298,7 @@ def test_excinfo_exconly(): excinfo = pytest.raises(ValueError, h) assert excinfo.exconly().startswith('ValueError') excinfo = pytest.raises(ValueError, - "raise ValueError('hello\\nworld')") + "raise ValueError('hello\\nworld')") msg = excinfo.exconly(tryshort=True) assert msg.startswith('ValueError') assert msg.endswith("world") diff --git a/testing/python/collect.py b/testing/python/collect.py index 236421f1c0d..968e56ff58b 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -419,10 +419,10 @@ def func2(): pass f1 = pytest.Function(name="name", parent=session, config=config, - args=(1,), callobj=func1) + args=(1,), callobj=func1) assert f1 == f1 f2 = pytest.Function(name="name",config=config, - callobj=func2, parent=session) + callobj=func2, parent=session) assert f1 != f2 def test_issue197_parametrize_emptyset(self, testdir): @@ -838,7 +838,7 @@ def test_makeitem_non_underscore(self, testdir, monkeypatch): modcol = testdir.getmodulecol("def _hello(): pass") l = [] monkeypatch.setattr(pytest.Module, 'makeitem', - lambda self, name, obj: l.append(name)) + lambda self, name, obj: l.append(name)) l = modcol.collect() assert '_hello' not in l diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 38cf19a6e00..5d0cf39f142 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -133,11 +133,11 @@ def func(x, y): pass metafunc = self.Metafunc(func) pytest.raises(ValueError, lambda: - metafunc.parametrize("x", [1,2], ids=['basic'])) + metafunc.parametrize("x", [1,2], ids=['basic'])) pytest.raises(ValueError, lambda: - metafunc.parametrize(("x","y"), [("abc", "def"), - ("ghi", "jkl")], ids=["one"])) + metafunc.parametrize(("x","y"), [("abc", "def"), + ("ghi", "jkl")], ids=["one"])) @pytest.mark.issue510 def test_parametrize_empty_list(self): @@ -1114,7 +1114,7 @@ def test_foo(x): @pytest.mark.issue463 @pytest.mark.parametrize('attr', ['parametrise', 'parameterize', - 'parameterise']) + 'parameterise']) def test_parametrize_misspelling(self, testdir, attr): testdir.makepyfile(""" import pytest diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py index 6887c419cfb..61ebbcafe12 100644 --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -51,17 +51,17 @@ def __call__(self, prefix, **kwargs): if self.allowednames: if self.directories: files = _wrapcall(['bash','-c', - "compgen -A directory -- '{p}'".format(p=prefix)]) + "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)]) + "compgen -A file -X '!*.{0}' -- '{p}'".format(x,p=prefix)]) else: completion += _wrapcall(['bash', '-c', - "compgen -A file -- '{p}'".format(p=prefix)]) + "compgen -A file -- '{p}'".format(p=prefix)]) anticomp = _wrapcall(['bash', '-c', - "compgen -A directory -- '{p}'".format(p=prefix)]) + "compgen -A directory -- '{p}'".format(p=prefix)]) completion = list( set(completion) - set(anticomp)) diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 7f38b4d167c..3442e1131ec 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -639,7 +639,7 @@ def test_translate_newlines(self, testdir): assert testdir.runpytest().ret == 0 @pytest.mark.skipif(sys.version_info < (3,3), - reason='packages without __init__.py not supported on python 2') + 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() diff --git a/testing/test_capture.py b/testing/test_capture.py index 8f6f2ccb23d..9ed605d2577 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -72,7 +72,7 @@ def test_getmethod_default_no_fd(self, monkeypatch): @needsosdup @pytest.mark.parametrize("method", - ['no', 'sys', pytest.mark.skipif('not hasattr(os, "dup")', 'fd')]) + ['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 diff --git a/testing/test_config.py b/testing/test_config.py index ddabf6a29f7..5022ac82276 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -149,7 +149,7 @@ def pytest_addoption(parser): def test_config_getvalueorskip(self, testdir): config = testdir.parseconfig() pytest.raises(pytest.skip.Exception, - "config.getvalueorskip('hello')") + "config.getvalueorskip('hello')") verbose = config.getvalueorskip("verbose") assert verbose == config.option.verbose diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 0aa60e8ac72..9f7138ebdde 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -32,14 +32,14 @@ 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') + '--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') + '--doctest-modules') assert len(items) == 1 assert isinstance(items[0], DoctestItem) assert isinstance(items[0].parent, DoctestModule) @@ -52,7 +52,7 @@ def my_func(): """) for p in (path, testdir.tmpdir): items, reprec = testdir.inline_genitems(p, - '--doctest-modules') + '--doctest-modules') assert len(items) == 2 assert isinstance(items[0], DoctestItem) assert isinstance(items[1], DoctestItem) @@ -77,7 +77,7 @@ def another(): """) for p in (path, testdir.tmpdir): items, reprec = testdir.inline_genitems(p, - '--doctest-modules') + '--doctest-modules') assert len(items) == 2 assert isinstance(items[0], DoctestItem) assert isinstance(items[1], DoctestItem) diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index f17519d8dc6..f30770f3591 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -249,7 +249,7 @@ def test_drop_short_help1(self, parser, capsys): group = parser.getgroup("general") group.addoption('--doit', '--func-args', action='store_true', help='foo') group._addoption("-h", "--help", action="store_true", dest="help", - help="show help message and configuration info") + help="show help message and configuration info") parser.parse(['-h']) help = parser.optparser.format_help() assert '-doit, --func-args foo' in help diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index d6cdfdb1f51..6428bf9d903 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -352,7 +352,7 @@ def test_consider_conftest_deps(self, testdir, pytestpm): class TestPytestPluginManagerBootstrapming(object): def test_preparse_args(self, pytestpm): pytest.raises(ImportError, lambda: - pytestpm.consider_preparse(["xyz", "-p", "hello123"])) + pytestpm.consider_preparse(["xyz", "-p", "hello123"])) def test_plugin_prevent_register(self, pytestpm): pytestpm.consider_preparse(["xyz", "-p", "no:abc"]) diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 6a099fa3ba8..dd5311776cc 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -110,7 +110,7 @@ def test_show_runtest_logstart(self, testdir, linecomp): item.config.pluginmanager.register(tr) location = item.reportinfo() tr.config.hook.pytest_runtest_logstart(nodeid=item.nodeid, - location=location, fspath=str(item.fspath)) + location=location, fspath=str(item.fspath)) linecomp.assert_contains_lines([ "*test_show_runtest_logstart.py*" ]) @@ -905,9 +905,9 @@ def pytest_terminal_summary(terminalreporter): ("green", "1 passed, 2 skipped, 3 deselected, 2 xfailed", {"passed": (1,), - "skipped": (1,2), - "deselected": (1,2,3), - "xfailed": (1,2)}), + "skipped": (1,2), + "deselected": (1,2,3), + "xfailed": (1,2)}), ]) def test_summary_stats(exp_line, exp_color, stats_arg): print("Based on stats: %s" % stats_arg) diff --git a/tox.ini b/tox.ini index 6b6d060b73d..fe6ec332af7 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E128,E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 1c935db571b8e5e763360d682d236a0ee5b29dda Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 21/58] Fixed E129 flake8 errors visually indented line with same indent as next logical line --- _pytest/_code/_py2traceback.py | 2 +- _pytest/_code/code.py | 2 +- _pytest/assertion/rewrite.py | 2 +- _pytest/unittest.py | 2 +- tox.ini | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/_pytest/_code/_py2traceback.py b/_pytest/_code/_py2traceback.py index d45ee01fa79..5c4f5ff2215 100644 --- a/_pytest/_code/_py2traceback.py +++ b/_pytest/_code/_py2traceback.py @@ -30,7 +30,7 @@ def format_exception_only(etype, value): # would throw another exception and mask the original problem. if (isinstance(etype, BaseException) or isinstance(etype, types.InstanceType) or - etype is None or type(etype) is str): + etype is None or type(etype) is str): return [_format_final_exc_line(etype, value)] stype = etype.__name__ diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 49c300b3066..29f046e6189 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -289,7 +289,7 @@ def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None): (excludepath is None or not hasattr(codepath, 'relto') or not codepath.relto(excludepath)) and (lineno is None or x.lineno == lineno) and - (firstlineno is None or x.frame.code.firstlineno == firstlineno)): + (firstlineno is None or x.frame.code.firstlineno == firstlineno)): return Traceback(x._rawentry, self._excinfo) return self diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 1849d9cba50..95cc217d48d 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -307,7 +307,7 @@ def _rewrite_test(config, fn): 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[end1 + 1:end2]) is None): if hasattr(state, "_indecode"): # encodings imported us again, so don't rewrite. return None, None diff --git a/_pytest/unittest.py b/_pytest/unittest.py index 64cb5f5ee18..3c473c6bd91 100644 --- a/_pytest/unittest.py +++ b/_pytest/unittest.py @@ -158,7 +158,7 @@ def _handle_skip(self): # analog to pythons Lib/unittest/case.py:run testMethod = getattr(self._testcase, self._testcase._testMethodName) if (getattr(self._testcase.__class__, "__unittest_skip__", False) or - getattr(testMethod, "__unittest_skip__", False)): + getattr(testMethod, "__unittest_skip__", False)): # If the class or method was skipped. skip_why = (getattr(self._testcase.__class__, '__unittest_skip_why__', '') or getattr(testMethod, '__unittest_skip_why__', '')) diff --git a/tox.ini b/tox.ini index fe6ec332af7..2ea36560524 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E129,E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From df54bf0db524a9c8e5b6c2847c56d1589f533087 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:07 +0200 Subject: [PATCH 22/58] Fixed E131 flake8 errors continuation line unaligned for hanging indent --- _pytest/config.py | 6 +-- _pytest/python.py | 2 +- _pytest/recwarn.py | 2 +- testing/code/test_excinfo.py | 6 +-- testing/python/approx.py | 80 ++++++++++++++++++------------------ testing/test_assertion.py | 10 ++--- testing/test_mark.py | 18 ++++---- testing/test_skipping.py | 2 +- testing/test_terminal.py | 2 +- tox.ini | 2 +- 10 files changed, 65 insertions(+), 65 deletions(-) diff --git a/_pytest/config.py b/_pytest/config.py index 2c0da564054..2e42074a768 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -103,9 +103,9 @@ def directory_arg(path, optname): default_plugins = ( "mark main terminal runner python fixtures debugging unittest capture skipping " - "tmpdir monkeypatch recwarn pastebin helpconfig nose assertion " - "junitxml resultlog doctest cacheprovider freeze_support " - "setuponly setupplan warnings").split() + "tmpdir monkeypatch recwarn pastebin helpconfig nose assertion " + "junitxml resultlog doctest cacheprovider freeze_support " + "setuponly setupplan warnings").split() builtin_plugins = set(default_plugins) diff --git a/_pytest/python.py b/_pytest/python.py index 9af0a27f0a2..8dec157c505 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -419,7 +419,7 @@ def _importtestmodule(self): " %s\n" "HINT: remove __pycache__ / .pyc files and/or use a " "unique basename for your test file modules" - % e.args + % e.args ) except ImportError: from _pytest._code.code import ExceptionInfo diff --git a/_pytest/recwarn.py b/_pytest/recwarn.py index cc787455046..b9938752c5d 100644 --- a/_pytest/recwarn.py +++ b/_pytest/recwarn.py @@ -201,4 +201,4 @@ def __exit__(self, *exc_info): fail("DID NOT WARN. No warnings of type {0} was emitted. " "The list of emitted warnings is: {1}.".format( self.expected_warning, - [each.message for each in self])) + [each.message for each in self])) diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 7623da319f3..2783f768561 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -935,9 +935,9 @@ def f(): {'style': style, 'showlocals': showlocals, 'funcargs': funcargs, 'tbfilter': tbfilter } for style in ("long", "short", "no") - for showlocals in (True, False) - for tbfilter in (True, False) - for funcargs in (True, False)]) + for showlocals in (True, False) + for tbfilter in (True, False) + for funcargs in (True, False)]) def test_format_excinfo(self, importasmod, reproptions): mod = importasmod(""" def g(x): diff --git a/testing/python/approx.py b/testing/python/approx.py index 6338441ae88..97669b0760f 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -44,13 +44,13 @@ def test_operator_overloading(self): def test_exactly_equal(self): examples = [ (2.0, 2.0), - (0.1e200, 0.1e200), - (1.123e-300, 1.123e-300), - (12345, 12345.0), - (0.0, -0.0), - (345678, 345678), - (Decimal('1.0001'), Decimal('1.0001')), - (Fraction(1, 3), Fraction(-1, -3)), + (0.1e200, 0.1e200), + (1.123e-300, 1.123e-300), + (12345, 12345.0), + (0.0, -0.0), + (345678, 345678), + (Decimal('1.0001'), Decimal('1.0001')), + (Fraction(1, 3), Fraction(-1, -3)), ] for a, x in examples: assert a == approx(x) @@ -58,7 +58,7 @@ def test_exactly_equal(self): def test_opposite_sign(self): examples = [ (eq, 1e-100, -1e-100), - (ne, 1e100, -1e100), + (ne, 1e100, -1e100), ] for op, a, x in examples: assert op(a, approx(x)) @@ -66,7 +66,7 @@ def test_opposite_sign(self): def test_zero_tolerance(self): within_1e10 = [ (1.1e-100, 1e-100), - (-1.1e-100, -1e-100), + (-1.1e-100, -1e-100), ] for a, x in within_1e10: assert x == approx(x, rel=0.0, abs=0.0) @@ -93,9 +93,9 @@ def test_inf_tolerance(self): # Everything should be equal if the tolerance is infinite. large_diffs = [ (1, 1000), - (1e-50, 1e50), - (-1.0, -1e300), - (0.0, 10), + (1e-50, 1e50), + (-1.0, -1e300), + (0.0, 10), ] for a, x in large_diffs: assert a != approx(x, rel=0.0, abs=0.0) @@ -136,14 +136,14 @@ def test_default_tolerances(self): # the choice of defaults. examples = [ # Relative tolerance used. - (eq, 1e100 + 1e94, 1e100), - (ne, 1e100 + 2e94, 1e100), - (eq, 1e0 + 1e-6, 1e0), - (ne, 1e0 + 2e-6, 1e0), - # Absolute tolerance used. - (eq, 1e-100, + 1e-106), - (eq, 1e-100, + 2e-106), - (eq, 1e-100, 0), + (eq, 1e100 + 1e94, 1e100), + (ne, 1e100 + 2e94, 1e100), + (eq, 1e0 + 1e-6, 1e0), + (ne, 1e0 + 2e-6, 1e0), + # Absolute tolerance used. + (eq, 1e-100, + 1e-106), + (eq, 1e-100, + 2e-106), + (eq, 1e-100, 0), ] for op, a, x in examples: assert op(a, approx(x)) @@ -167,8 +167,8 @@ def test_custom_tolerances(self): def test_relative_tolerance(self): within_1e8_rel = [ (1e8 + 1e0, 1e8), - (1e0 + 1e-8, 1e0), - (1e-8 + 1e-16, 1e-8), + (1e0 + 1e-8, 1e0), + (1e-8 + 1e-16, 1e-8), ] for a, x in within_1e8_rel: assert a == approx(x, rel=5e-8, abs=0.0) @@ -177,8 +177,8 @@ def test_relative_tolerance(self): def test_absolute_tolerance(self): within_1e8_abs = [ (1e8 + 9e-9, 1e8), - (1e0 + 9e-9, 1e0), - (1e-8 + 9e-9, 1e-8), + (1e0 + 9e-9, 1e0), + (1e-8 + 9e-9, 1e-8), ] for a, x in within_1e8_abs: assert a == approx(x, rel=0, abs=5e-8) @@ -202,10 +202,10 @@ def test_expecting_zero(self): def test_expecting_inf(self): examples = [ (eq, inf, inf), - (eq, -inf, -inf), - (ne, inf, -inf), - (ne, 0.0, inf), - (ne, nan, inf), + (eq, -inf, -inf), + (ne, inf, -inf), + (ne, 0.0, inf), + (ne, nan, inf), ] for op, a, x in examples: assert op(a, approx(x)) @@ -213,10 +213,10 @@ def test_expecting_inf(self): def test_expecting_nan(self): examples = [ (nan, nan), - (-nan, -nan), - (nan, -nan), - (0.0, nan), - (inf, nan), + (-nan, -nan), + (nan, -nan), + (0.0, nan), + (inf, nan), ] for a, x in examples: # If there is a relative tolerance and the expected value is NaN, @@ -231,8 +231,8 @@ def test_expecting_nan(self): def test_expecting_sequence(self): within_1e8 = [ (1e8 + 1e0, 1e8), - (1e0 + 1e-8, 1e0), - (1e-8 + 1e-16, 1e-8), + (1e0 + 1e-8, 1e0), + (1e-8 + 1e-16, 1e-8), ] actual, expected = zip(*within_1e8) assert actual == approx(expected, rel=5e-8, abs=0.0) @@ -244,9 +244,9 @@ def test_expecting_sequence_wrong_len(self): def test_complex(self): within_1e6 = [ ( 1.000001 + 1.0j, 1.0 + 1.0j), - (1.0 + 1.000001j, 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.0 - 1.000001j, 1.0 - 1.0j), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) @@ -255,7 +255,7 @@ def test_complex(self): def test_int(self): within_1e6 = [ (1000001, 1000000), - (-1000001, -1000000), + (-1000001, -1000000), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) @@ -264,7 +264,7 @@ def test_int(self): def test_decimal(self): within_1e6 = [ (Decimal('1.000001'), Decimal('1.0')), - (Decimal('-1.000001'), Decimal('-1.0')), + (Decimal('-1.000001'), Decimal('-1.0')), ] for a, x in within_1e6: assert a == approx(x, rel=Decimal('5e-6'), abs=0) @@ -273,7 +273,7 @@ def test_decimal(self): def test_fraction(self): within_1e6 = [ (1 + Fraction(1, 1000000), Fraction(1)), - (-1 - Fraction(-1, 1000000), Fraction(-1)), + (-1 - Fraction(-1, 1000000), Fraction(-1)), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) diff --git a/testing/test_assertion.py b/testing/test_assertion.py index cf31f3d9263..3f6ae394cee 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -773,11 +773,11 @@ def test_assertrepr_loaded_per_dir(testdir): 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*']) + '*E*assert 1 == 2*', + '*def test_a():*', + '*E*assert summary a*', + '*def test_b():*', + '*E*assert summary b*']) def test_assertion_options(testdir): diff --git a/testing/test_mark.py b/testing/test_mark.py index 25ca7f0f104..309e2379ca8 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -201,9 +201,9 @@ def test_hello(): @pytest.mark.parametrize("spec", [ ("xyz", ("test_one",)), - ("xyz and xyz2", ()), - ("xyz2", ("test_two",)), - ("xyz or xyz2", ("test_one", "test_two"),) + ("xyz and xyz2", ()), + ("xyz2", ("test_two",)), + ("xyz or xyz2", ("test_one", "test_two"),) ]) def test_mark_option(spec, testdir): testdir.makepyfile(""" @@ -224,7 +224,7 @@ def test_two(): @pytest.mark.parametrize("spec", [ ("interface", ("test_interface",)), - ("not interface", ("test_nointer",)), + ("not interface", ("test_nointer",)), ]) def test_mark_option_custom(spec, testdir): testdir.makeconftest(""" @@ -249,9 +249,9 @@ def test_nointer(): @pytest.mark.parametrize("spec", [ ("interface", ("test_interface",)), - ("not interface", ("test_nointer", "test_pass")), - ("pass", ("test_pass",)), - ("not pass", ("test_interface", "test_nointer")), + ("not interface", ("test_nointer", "test_pass")), + ("pass", ("test_pass",)), + ("not pass", ("test_interface", "test_nointer")), ]) def test_keyword_option_custom(spec, testdir): testdir.makepyfile(""" @@ -272,8 +272,8 @@ def test_pass(): @pytest.mark.parametrize("spec", [ ("None", ("test_func[None]",)), - ("1.3", ("test_func[1.3]",)), - ("2-3", ("test_func[2-3]",)) + ("1.3", ("test_func[1.3]",)), + ("2-3", ("test_func[2-3]",)) ]) def test_keyword_option_parametrize(spec, testdir): testdir.makepyfile(""" diff --git a/testing/test_skipping.py b/testing/test_skipping.py index 5a6692b3c11..94423da3bf5 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -699,7 +699,7 @@ class TestClass(object): def test_method(self): doskip() """, - conftest = """ + conftest = """ import pytest def doskip(): pytest.skip('test') diff --git a/testing/test_terminal.py b/testing/test_terminal.py index dd5311776cc..048cdc82126 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -223,7 +223,7 @@ def test_func(): result = testdir.runpytest("--collect-only",) result.stdout.fnmatch_lines([ "", - " ", + " ", ]) def test_collectonly_skipped_module(self, testdir): diff --git a/tox.ini b/tox.ini index 2ea36560524..66c52f3b1db 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E131,E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 1ff54ba205925521faf12a9d1838c8893be5dcf0 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 23/58] Fixed E201 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit whitespace after ‘(‘ --- _pytest/_code/source.py | 2 +- testing/python/approx.py | 2 +- testing/python/metafunc.py | 2 +- testing/test_argcomplete.py | 4 ++-- tox.ini | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 37c1b5fa9e0..5c29dac4635 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -86,7 +86,7 @@ def putaround(self, before='', after='', indent=' ' * 4): before = Source(before) after = Source(after) newsource = Source() - lines = [ (indent + line) for line in self.lines] + lines = [(indent + line) for line in self.lines] newsource.lines = before.lines + lines + after.lines return newsource diff --git a/testing/python/approx.py b/testing/python/approx.py index 97669b0760f..853f2fe02ea 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -243,7 +243,7 @@ def test_expecting_sequence_wrong_len(self): def test_complex(self): 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.000001 + 1.0j, -1.0 + 1.0j), (1.0 - 1.000001j, 1.0 - 1.0j), diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 5d0cf39f142..8718f6d5287 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -141,7 +141,7 @@ def func(x, y): pass @pytest.mark.issue510 def test_parametrize_empty_list(self): - def func( y): pass + def func(y): pass metafunc = self.Metafunc(func) metafunc.parametrize("y", []) assert 'skip' in metafunc._calls[0].keywords diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py index 61ebbcafe12..32705e1304f 100644 --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -52,7 +52,7 @@ def __call__(self, prefix, **kwargs): if self.directories: files = _wrapcall(['bash','-c', "compgen -A directory -- '{p}'".format(p=prefix)]) - completion += [ f + '/' for f in files] + 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)]) @@ -63,7 +63,7 @@ def __call__(self, prefix, **kwargs): 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] diff --git a/tox.ini b/tox.ini index 66c52f3b1db..3e74833b022 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E201,E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From ba0a4d0b2e385a5bc65345a3dda81588825c0566 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 24/58] Fixed E202 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit whitespace before ‘)’ --- _pytest/_code/code.py | 2 +- testing/code/test_excinfo.py | 2 +- testing/test_assertion.py | 2 +- tox.ini | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 29f046e6189..54258cc1f38 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -119,7 +119,7 @@ def exec_(self, code, **vars): """ f_locals = self.f_locals.copy() f_locals.update(vars) - py.builtin.exec_(code, self.f_globals, f_locals ) + py.builtin.exec_(code, self.f_globals, f_locals) def repr(self, object): """ return a 'safe' (non-recursive, one-line) string repr for 'object' diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 2783f768561..e5946f61e11 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -113,7 +113,7 @@ def test_traceback_entries(self): def test_traceback_entry_getsource(self): tb = self.excinfo.traceback - s = str(tb[-1].getsource() ) + s = str(tb[-1].getsource()) assert s.startswith("def f():") assert s.endswith("raise ValueError") diff --git a/testing/test_assertion.py b/testing/test_assertion.py index 3f6ae394cee..a74496a655d 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -881,7 +881,7 @@ def test_multitask_job(): ]) -@pytest.mark.skipif("'__pypy__' in sys.builtin_module_names or sys.platform.startswith('java')" ) +@pytest.mark.skipif("'__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") diff --git a/tox.ini b/tox.ini index 3e74833b022..b8d0ece8fef 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E202,E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From ebb6d0650b6722cefba0a640b1f7e5486a6b8ea6 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 25/58] Fixed E203 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit whitespace before ‘:’ --- testing/test_assertrewrite.py | 18 +++++++++--------- tox.ini | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 3442e1131ec..cd16b0a684a 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -118,12 +118,12 @@ def f(): 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 @@ -131,7 +131,7 @@ def f(): 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(): @@ -238,13 +238,13 @@ def x(): def f(): assert x() and x() - assert getmsg(f, {"x" : x}) == """assert (False) + assert getmsg(f, {"x": x}) == """assert (False) + where False = x()""" def f(): assert False or x() - assert getmsg(f, {"x" : x}) == """assert (False or False) + assert getmsg(f, {"x": x}) == """assert (False or False) + where False = x()""" def f(): @@ -255,7 +255,7 @@ def f(): 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 {})" @@ -348,7 +348,7 @@ def test_call(self): def g(a=42, *args, **kwargs): return False - ns = {"g" : g} + ns = {"g": g} def f(): assert g() @@ -389,7 +389,7 @@ def f(): def f(): x = "a" - assert g(**{x : 2}) + assert g(**{x: 2}) assert getmsg(f, ns) == """assert False + where False = g(**{'a': 2})""" @@ -398,7 +398,7 @@ def test_attribute(self): class X(object): g = 3 - ns = {"x" : X} + ns = {"x": X} def f(): assert not x.g # noqa diff --git a/tox.ini b/tox.ini index b8d0ece8fef..e1c2392c6e0 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E203,E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From f640e0cb0481b239d1e3c705d0dbadb2a618ef17 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 26/58] Fixed E221 flake8 errors multiple spaces before operator --- _pytest/fixtures.py | 2 +- _pytest/pytester.py | 2 +- _pytest/warnings.py | 2 +- testing/code/test_excinfo.py | 20 ++++++++++---------- tox.ini | 2 +- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index c10bde4d959..7ff41d7d40a 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -569,7 +569,7 @@ def __init__(self, request, scope, param, param_index, fixturedef): self._fixturedef = fixturedef self.addfinalizer = fixturedef.addfinalizer self._pyfuncitem = request._pyfuncitem - self._fixture_values = request._fixture_values + self._fixture_values = request._fixture_values self._fixture_defs = request._fixture_defs self._arg2fixturedefs = request._arg2fixturedefs self._arg2index = request._arg2index diff --git a/_pytest/pytester.py b/_pytest/pytester.py index d85cb45db60..4fc90e98c73 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -406,7 +406,7 @@ class Testdir: def __init__(self, request, tmpdir_factory): self.request = request - self._mod_collections = WeakKeyDictionary() + self._mod_collections = WeakKeyDictionary() # XXX remove duplication with tmpdir plugin basetmp = tmpdir_factory.ensuretemp("testdir") name = request.function.__name__ diff --git a/_pytest/warnings.py b/_pytest/warnings.py index 4fe28bd315b..915862a9d39 100644 --- a/_pytest/warnings.py +++ b/_pytest/warnings.py @@ -78,7 +78,7 @@ def catch_warnings_for_item(item): if unicode_warning: warnings.warn( "Warning is using unicode non convertible to ascii, " - "converting to a safe representation:\n %s" % msg, + "converting to a safe representation:\n %s" % msg, UnicodeWarning) diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index e5946f61e11..73fd5159570 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -1017,18 +1017,18 @@ def h(): tw = TWMock() r.toterminal(tw) for line in tw.lines: print (line) - assert tw.lines[0] == "" - assert tw.lines[1] == " def f():" - assert tw.lines[2] == " try:" - assert tw.lines[3] == "> g()" - assert tw.lines[4] == "" + assert tw.lines[0] == "" + assert tw.lines[1] == " def f():" + assert tw.lines[2] == " try:" + assert tw.lines[3] == "> g()" + assert tw.lines[4] == "" line = tw.get_write_msg(5) assert line.endswith('mod.py') - assert tw.lines[6] == ':6: ' - assert tw.lines[7] == ("_ ", None) - assert tw.lines[8] == "" - assert tw.lines[9] == " def g():" - assert tw.lines[10] == "> raise ValueError()" + assert tw.lines[6] == ':6: ' + assert tw.lines[7] == ("_ ", None) + assert tw.lines[8] == "" + assert tw.lines[9] == " def g():" + assert tw.lines[10] == "> raise ValueError()" assert tw.lines[11] == "E ValueError" assert tw.lines[12] == "" line = tw.get_write_msg(13) diff --git a/tox.ini b/tox.ini index e1c2392c6e0..3f8e590c67f 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E221,E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 3fabc4d21918a0927a1717e2616862400bde5440 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 27/58] Fixed E222 flake8 errors multiple spaces after operator --- _pytest/_code/code.py | 4 ++-- _pytest/_code/source.py | 2 +- _pytest/config.py | 2 +- _pytest/fixtures.py | 8 ++++---- testing/test_collection.py | 6 +++--- tox.ini | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 54258cc1f38..c964d2beb35 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -582,7 +582,7 @@ def repr_traceback_entry(self, entry, excinfo=None): filelocrepr = ReprFileLocation(path, entry.lineno+1, message) localsrepr = None if not short: - localsrepr = self.repr_locals(entry.locals) + localsrepr = self.repr_locals(entry.locals) return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style) if excinfo: lines.extend(self.get_exconly(excinfo, indent=4)) @@ -854,7 +854,7 @@ def toterminal(self, tw): if len(ns) + len(linesofar) + 2 > tw.fullwidth: if linesofar: tw.line(linesofar) - linesofar = ns + linesofar = ns else: if linesofar: linesofar += ", " + ns diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 5c29dac4635..54aaca2e935 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -87,7 +87,7 @@ def putaround(self, before='', after='', indent=' ' * 4): after = Source(after) newsource = Source() lines = [(indent + line) for line in self.lines] - newsource.lines = before.lines + lines + after.lines + newsource.lines = before.lines + lines + after.lines return newsource def indent(self, indent=' ' * 4): diff --git a/_pytest/config.py b/_pytest/config.py index 2e42074a768..bfc3baa3f31 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -818,7 +818,7 @@ def _format_action_invocation(self, action): action._formatted_action_invocation = orgstr return orgstr return_list = [] - option_map = getattr(action, 'map_long_option', {}) + option_map = getattr(action, 'map_long_option', {}) if option_map is None: option_map = {} short_long = {} diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 7ff41d7d40a..bc9a4832e01 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -105,10 +105,10 @@ def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): 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 diff --git a/testing/test_collection.py b/testing/test_collection.py index 6dcb7eda24a..834eaa300ff 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -347,11 +347,11 @@ def test_parsearg(self, testdir): 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): diff --git a/tox.ini b/tox.ini index 3f8e590c67f..490c273f0b0 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E222,E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 2e8caefcab33942a754ee7ddf7697fe487a4367a Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 28/58] Fixed E225 flake8 errors missing whitespace around operator --- _pytest/_code/code.py | 14 +++++++------- _pytest/assertion/rewrite.py | 2 +- _pytest/compat.py | 2 +- _pytest/config.py | 18 +++++++++--------- _pytest/fixtures.py | 4 ++-- _pytest/helpconfig.py | 6 +++--- _pytest/main.py | 6 +++--- _pytest/pastebin.py | 2 +- _pytest/pytester.py | 6 +++--- _pytest/python.py | 12 ++++++------ _pytest/runner.py | 8 ++++---- testing/acceptance_test.py | 2 +- testing/code/test_source.py | 4 ++-- testing/python/fixture.py | 4 ++-- testing/test_assertion.py | 10 +++++----- testing/test_conftest.py | 6 +++--- testing/test_parseopt.py | 2 +- testing/test_pdb.py | 2 +- testing/test_skipping.py | 2 +- tox.ini | 2 +- 20 files changed, 57 insertions(+), 57 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index c964d2beb35..797e1d293ef 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -26,7 +26,7 @@ def __init__(self, rawcode): self.firstlineno = rawcode.co_firstlineno - 1 self.name = rawcode.co_name except AttributeError: - raise TypeError("not a code object: %r" %(rawcode,)) + raise TypeError("not a code object: %r" % (rawcode,)) self.raw = rawcode def __eq__(self, other): @@ -168,7 +168,7 @@ def relline(self): return self.lineno - self.frame.code.firstlineno def __repr__(self): - return "" %(self.frame.code.path, self.lineno+1) + return "" % (self.frame.code.path, self.lineno+1) @property def statement(self): @@ -249,7 +249,7 @@ def __str__(self): raise except: line = "???" - return " File %r:%d in %s\n %s\n" %(fn, self.lineno+1, name, line) + return " File %r:%d in %s\n %s\n" % (fn, self.lineno+1, name, line) def name(self): return self.frame.code.raw.co_name @@ -548,7 +548,7 @@ def repr_locals(self, locals): str_repr = self._saferepr(value) #if len(str_repr) < 70 or not isinstance(value, # (list, tuple, dict)): - lines.append("%-10s = %s" %(name, str_repr)) + lines.append("%-10s = %s" % (name, str_repr)) #else: # self._line("%-10s =\\" % (name,)) # # XXX @@ -575,7 +575,7 @@ def repr_traceback_entry(self, entry, excinfo=None): s = self.get_source(source, line_index, excinfo, short=short) lines.extend(s) if short: - message = "in %s" %(entry.name) + message = "in %s" % (entry.name) else: message = excinfo and excinfo.typename or "" path = self._makepath(entry.path) @@ -699,7 +699,7 @@ def __unicode__(self): return io.getvalue().strip() def __repr__(self): - return "<%s instance at %0x>" %(self.__class__, id(self)) + return "<%s instance at %0x>" % (self.__class__, id(self)) class ExceptionRepr(TerminalRepr): @@ -850,7 +850,7 @@ def toterminal(self, tw): if self.args: linesofar = "" for name, value in self.args: - ns = "%s = %s" %(name, value) + ns = "%s = %s" % (name, value) if len(ns) + len(linesofar) + 2 > tw.fullwidth: if linesofar: tw.line(linesofar) diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 95cc217d48d..2ffa3c03e04 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -261,7 +261,7 @@ def _write_pyc(state, co, source_stat, pyc): 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. diff --git a/_pytest/compat.py b/_pytest/compat.py index 38c0f1facc5..22cba845099 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -68,7 +68,7 @@ def getlocation(function, curdir): 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) def num_mock_patch_args(function): diff --git a/_pytest/config.py b/_pytest/config.py index bfc3baa3f31..a96e6a0154a 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -60,7 +60,7 @@ def main(args=None, plugins=None): config._ensure_unconfigure() except UsageError as e: for msg in e.args: - sys.stderr.write("ERROR: %s\n" %(msg,)) + sys.stderr.write("ERROR: %s\n" % (msg,)) return 4 class cmdline: # compatibility namespace @@ -382,7 +382,7 @@ def _importconftest(self, conftestpath): if path and path.relto(dirpath) or path == dirpath: assert mod not in mods mods.append(mod) - self.trace("loaded conftestmodule %r" %(mod)) + self.trace("loaded conftestmodule %r" % (mod)) self.consider_conftest(mod) return mod @@ -446,7 +446,7 @@ def import_plugin(self, modname): import pytest if not hasattr(pytest, 'skip') or not isinstance(e, pytest.skip.Exception): raise - self._warn("skipped plugin %r: %s" %((modname, e.msg))) + self._warn("skipped plugin %r: %s" % ((modname, e.msg))) else: mod = sys.modules[importspec] self.register(mod, modname) @@ -549,7 +549,7 @@ def _getparser(self): a = option.attrs() arggroup.add_argument(*n, **a) # bash like autocompletion for dirs (appending '/') - optparser.add_argument(FILE_OR_DIR, nargs='*').completer=filescompleter + optparser.add_argument(FILE_OR_DIR, nargs='*').completer = filescompleter return optparser def parse_setoption(self, args, option, namespace=None): @@ -857,7 +857,7 @@ class CmdOptions(object): def __init__(self, values=()): self.__dict__.update(values) def __repr__(self): - return "" %(self.__dict__,) + return "" % (self.__dict__,) def copy(self): return CmdOptions(self.__dict__) @@ -947,7 +947,7 @@ def notify_exception(self, excinfo, option=None): excinfo=excinfo) if not py.builtin.any(res): for line in str(excrepr).split("\n"): - sys.stderr.write("INTERNALERROR> %s\n" %line) + sys.stderr.write("INTERNALERROR> %s\n" % line) sys.stderr.flush() def cwd_relative_nodeid(self, nodeid): @@ -1092,7 +1092,7 @@ def _checkversion(self): myver = pytest.__version__.split(".") if myver < ver: raise pytest.UsageError( - "%s:%d: requires pytest-%s, actual pytest-%s'" %( + "%s:%d: requires pytest-%s, actual pytest-%s'" % ( self.inicfg.config.path, self.inicfg.lineof('minversion'), minver, pytest.__version__)) @@ -1142,7 +1142,7 @@ def _getini(self, name): try: description, type, default = self._parser._inidict[name] except KeyError: - raise ValueError("unknown configuration value: %r" %(name,)) + raise ValueError("unknown configuration value: %r" % (name,)) value = self._get_override_ini_value(name) if value is None: try: @@ -1219,7 +1219,7 @@ def getoption(self, name, default=notset, skip=False): return default if skip: import pytest - pytest.skip("no %r option found" %(name,)) + pytest.skip("no %r option found" % (name,)) raise ValueError("no option named %r" % (name,)) def getvalue(self, name, path=None): diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index bc9a4832e01..aee55c8fac3 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -553,7 +553,7 @@ def _getscopeitem(self, scope): return node def __repr__(self): - return "" %(self.node) + return "" % (self.node) class SubRequest(FixtureRequest): @@ -649,7 +649,7 @@ def formatrepr(self): if faclist and name not in available: available.append(name) msg = "fixture %r not found" % (self.argname,) - msg += "\n available fixtures: %s" %(", ".join(sorted(available)),) + msg += "\n available fixtures: %s" % (", ".join(sorted(available)),) msg += "\n use 'pytest --fixtures [testpath]' for help on them." return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname) diff --git a/_pytest/helpconfig.py b/_pytest/helpconfig.py index 05d9838035c..72484fda51f 100644 --- a/_pytest/helpconfig.py +++ b/_pytest/helpconfig.py @@ -69,7 +69,7 @@ def pytest_cmdline_parse(): path = os.path.abspath("pytestdebug.log") debugfile = open(path, 'w') debugfile.write("versions pytest-%s, py-%s, " - "python-%s\ncwd=%s\nargs=%s\n\n" %( + "python-%s\ncwd=%s\nargs=%s\n\n" % ( pytest.__version__, py.__version__, ".".join(map(str, sys.version_info)), os.getcwd(), config._origargs)) @@ -117,7 +117,7 @@ def showhelp(config): if type is None: type = "string" spec = "%s (%s)" % (name, type) - line = " %-24s %s" %(spec, help) + line = " %-24s %s" % (spec, help) tw.line(line[:tw.fullwidth]) tw.line() @@ -175,5 +175,5 @@ def pytest_report_header(config): r = plugin.__file__ else: r = repr(plugin) - lines.append(" %-20s: %s" %(name, r)) + lines.append(" %-20s: %s" % (name, r)) return lines diff --git a/_pytest/main.py b/_pytest/main.py index 712965a639d..3e9c10b592a 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -307,8 +307,8 @@ def _getcustomclass(self, name): return cls def __repr__(self): - return "<%s %r>" %(self.__class__.__name__, - getattr(self, 'name', None)) + return "<%s %r>" % (self.__class__.__name__, + getattr(self, 'name', None)) def warn(self, code, message): """ generate a warning with the given code and message for this @@ -429,7 +429,7 @@ def _repr_failure_py(self, excinfo, style=None): return excinfo.value.formatrepr() tbfilter = True if self.config.option.fulltrace: - style="long" + style = "long" else: tb = _pytest._code.Traceback([excinfo.traceback[-1]]) self._prunetraceback(excinfo) diff --git a/_pytest/pastebin.py b/_pytest/pastebin.py index 54590b48c6c..9d689819f09 100644 --- a/_pytest/pastebin.py +++ b/_pytest/pastebin.py @@ -97,4 +97,4 @@ def pytest_terminal_summary(terminalreporter): s = tw.stringio.getvalue() assert len(s) pastebinurl = create_new_paste(s) - tr.write_line("%s --> %s" %(msg, pastebinurl)) + tr.write_line("%s --> %s" % (msg, pastebinurl)) diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 4fc90e98c73..223bdd79b21 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -190,7 +190,7 @@ def __init__(self, name, kwargs): def __repr__(self): d = self.__dict__.copy() del d['_name'] - return "" %(self._name, d) + return "" % (self._name, d) class HookRecorder: @@ -283,7 +283,7 @@ def matchreport(self, inamepart="", "no test reports at all!" % (inamepart,)) if len(l) > 1: raise ValueError( - "found 2 or more testreports matching %r: %s" %(inamepart, l)) + "found 2 or more testreports matching %r: %s" % (inamepart, l)) return l[0] def getfailures(self, @@ -838,7 +838,7 @@ def getitem(self, source, funcname="test_func"): for item in items: if item.name == funcname: return item - assert 0, "%r item not found in module:\n%s\nitems: %s" %( + assert 0, "%r item not found in module:\n%s\nitems: %s" % ( funcname, source, items) def getitems(self, source): diff --git a/_pytest/python.py b/_pytest/python.py index 8dec157c505..cb42c3fe2b5 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -606,13 +606,13 @@ def collect(self): 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)) self.warn('C1', deprecated.YIELD_TESTS) @@ -671,7 +671,7 @@ def copy(self, metafunc): 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: @@ -1072,12 +1072,12 @@ def _showfixtures_main(config, session): 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) @@ -1087,7 +1087,7 @@ def _showfixtures_main(config, session): for line in doc.strip().split("\n"): tw.line(" " + line.strip()) else: - tw.line(" %s: no docstring available" %(loc,), + tw.line(" %s: no docstring available" % (loc,), red=True) diff --git a/_pytest/runner.py b/_pytest/runner.py index 6e3ad034627..d029394caa5 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -268,7 +268,7 @@ def pytest_runtest_makereport(item, call): longrepr = item._repr_failure_py(excinfo, style=item.config.option.tbstyle) for rwhen, key, content in item._report_sections: - sections.append(("Captured %s %s" %(key, rwhen), content)) + sections.append(("Captured %s %s" % (key, rwhen), content)) return TestReport(item.nodeid, item.location, keywords, outcome, longrepr, when, sections, duration) @@ -480,7 +480,7 @@ def __repr__(self): if isinstance(val, bytes): val = py._builtin._totext(val, errors='replace') return val - return "<%s instance>" %(self.__class__.__name__,) + return "<%s instance>" % (self.__class__.__name__,) __str__ = __repr__ class Skipped(OutcomeException): @@ -562,7 +562,7 @@ def importorskip(modname, minversion=None): # Do not raise chained exception here(#1485) should_skip = True if should_skip: - raise Skipped("could not import %r" %(modname,), allow_module_level=True) + raise Skipped("could not import %r" % (modname,), allow_module_level=True) mod = sys.modules[modname] if minversion is None: return mod @@ -575,6 +575,6 @@ def importorskip(modname, minversion=None): "pkg_resources to parse version strings." % (modname,), allow_module_level=True) if verattr is None or pv(verattr) < pv(minversion): - raise Skipped("module %r has __version__ %r, required is: %r" %( + raise Skipped("module %r has __version__ %r, required is: %r" % ( modname, verattr, minversion), allow_module_level=True) return mod diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index 3b3023f6c56..1b160960014 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -131,7 +131,7 @@ def test_not_collectable_arguments(self, testdir): 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): diff --git a/testing/code/test_source.py b/testing/code/test_source.py index 6a9b458ec81..dc48b29c311 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -78,7 +78,7 @@ def test_source_putaround_simple(): x = 42 else: x = 23""") - assert str(source)=="""\ + assert str(source) == """\ try: raise ValueError except ValueError: @@ -291,7 +291,7 @@ def test_compilefuncs_and_path_sanity(self, name): def check(comp, name): co = comp(self.source, name) if not name: - expected = "codegen %s:%d>" %(mypath, mylineno+2+2) + expected = "codegen %s:%d>" % (mypath, mylineno+2+2) else: expected = "codegen %r %s:%d>" % (name, mypath, mylineno+2+2) fn = co.co_filename diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 9985ee08d5f..751be095b8f 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -2565,7 +2565,7 @@ def myscoped(request): assert request.config def test_func(): pass - """ %(scope, ok.split(), error.split())) + """ % (scope, ok.split(), error.split())) reprec = testdir.inline_run("-l") reprec.assertoutcome(passed=1) @@ -2583,7 +2583,7 @@ def arg(request): assert request.config def test_func(arg): pass - """ %(scope, ok.split(), error.split())) + """ % (scope, ok.split(), error.split())) reprec = testdir.inline_run() reprec.assertoutcome(passed=1) diff --git a/testing/test_assertion.py b/testing/test_assertion.py index a74496a655d..e17e7418329 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -619,7 +619,7 @@ def test_truncates_at_8_lines_when_given_list_of_empty_strings(self): assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG assert "Full output truncated" in result[-1] assert "43 lines hidden" in result[-1] - last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG -1] + last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1] assert last_line_before_trunc_msg.endswith("...") def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self): @@ -629,7 +629,7 @@ def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self): assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG assert "Full output truncated" in result[-1] assert "93 lines hidden" in result[-1] - last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG -1] + last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1] assert last_line_before_trunc_msg.endswith("...") def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self): @@ -639,7 +639,7 @@ def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self): assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG assert "Full output truncated" in result[-1] assert "9 lines hidden" in result[-1] - last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG -1] + last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1] assert last_line_before_trunc_msg.endswith("...") def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self): @@ -649,7 +649,7 @@ def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self): assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG assert "Full output truncated" in result[-1] assert "7 lines hidden" in result[-1] - last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG -1] + last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1] assert last_line_before_trunc_msg.endswith("...") def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self): @@ -659,7 +659,7 @@ def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self): assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG assert "Full output truncated" in result[-1] assert "1000 lines hidden" in result[-1] - last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG -1] + last_line_before_trunc_msg = result[- self.LINES_IN_TRUNCATION_MSG - 1] assert last_line_before_trunc_msg.endswith("...") def test_full_output_truncated(self, monkeypatch, testdir): diff --git a/testing/test_conftest.py b/testing/test_conftest.py index ed01c541085..3b01cc3cd24 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -347,10 +347,10 @@ def test_no_conftest(fxtr): def test_parsefactories_relative_node_ids( self, testdir, chdir,testarg, expect_ntests_passed): dirs = self._setup_tree(testdir) - print("pytest run in cwd: %s" %( + print("pytest run in cwd: %s" % ( dirs[chdir].relto(testdir.tmpdir))) - print("pytestarg : %s" %(testarg)) - print("expected pass : %s" %(expect_ntests_passed)) + print("pytestarg : %s" % (testarg)) + print("expected pass : %s" % (expect_ntests_passed)) with dirs[chdir].as_cwd(): reprec = testdir.inline_run(testarg, "-q", "--traceconfig") reprec.assertoutcome(passed=expect_ntests_passed) diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index f30770f3591..6fc46ef24ea 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -273,7 +273,7 @@ def test_argcomplete(testdir, monkeypatch): script = str(testdir.tmpdir.join("test_argcomplete")) pytest_bin = sys.argv[0] if "pytest" not in os.path.basename(pytest_bin): - pytest.skip("need to be run with pytest executable, not %s" %(pytest_bin,)) + pytest.skip("need to be run with pytest executable, not %s" % (pytest_bin,)) with open(str(script), 'w') as fp: # redirect output from argcomplete to stdin and stderr is not trivial diff --git a/testing/test_pdb.py b/testing/test_pdb.py index ec586208269..5429dd5d48e 100644 --- a/testing/test_pdb.py +++ b/testing/test_pdb.py @@ -319,7 +319,7 @@ def test_pdb_used_outside_test(self, testdir): pytest.set_trace() x = 5 """) - child = testdir.spawn("%s %s" %(sys.executable, p1)) + child = testdir.spawn("%s %s" % (sys.executable, p1)) child.expect("x = 5") child.sendeof() self.flush(child) diff --git a/testing/test_skipping.py b/testing/test_skipping.py index 94423da3bf5..afd5df16f55 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -80,7 +80,7 @@ def test_marked_one_arg_twice(self, testdir): %s def test_func(): pass - """ % (lines[i], lines[(i+1) %2])) + """ % (lines[i], lines[(i+1) % 2])) ev = MarkEvaluator(item, 'skipif') assert ev assert ev.istrue() diff --git a/tox.ini b/tox.ini index 490c273f0b0..fd0cc814dc8 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E225,E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 4b22f270a3583c97034ab63a343defbee146666a Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 29/58] Fixed E226 flake8 errors missing whitespace around arithmetic operator --- _pytest/_code/code.py | 16 ++++++++-------- _pytest/_code/source.py | 14 +++++++------- _pytest/assertion/util.py | 10 +++++----- _pytest/compat.py | 2 +- _pytest/config.py | 2 +- _pytest/fixtures.py | 12 ++++++------ _pytest/main.py | 2 +- _pytest/pytester.py | 6 +++--- _pytest/python.py | 2 +- _pytest/runner.py | 2 +- testing/acceptance_test.py | 2 +- testing/code/test_excinfo.py | 10 +++++----- testing/code/test_source.py | 4 ++-- testing/test_assertion.py | 16 ++++++++-------- testing/test_resultlog.py | 2 +- testing/test_runner.py | 2 +- testing/test_runner_xunit.py | 2 +- testing/test_skipping.py | 2 +- tox.ini | 2 +- 19 files changed, 55 insertions(+), 55 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 797e1d293ef..2f5e5607981 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -168,7 +168,7 @@ def relline(self): return self.lineno - self.frame.code.firstlineno def __repr__(self): - return "" % (self.frame.code.path, self.lineno+1) + return "" % (self.frame.code.path, self.lineno + 1) @property def statement(self): @@ -249,7 +249,7 @@ def __str__(self): raise except: line = "???" - return " File %r:%d in %s\n %s\n" % (fn, self.lineno+1, name, line) + return " File %r:%d in %s\n %s\n" % (fn, self.lineno + 1, name, line) def name(self): return self.frame.code.raw.co_name @@ -315,7 +315,7 @@ def getcrashentry(self): """ return last non-hidden traceback entry that lead to the exception of a traceback. """ - for i in range(-1, -len(self)-1, -1): + for i in range(-1, -len(self) - 1, -1): entry = self[i] if not entry.ishidden(): return entry @@ -405,7 +405,7 @@ def _getreprcrash(self): exconly = self.exconly(tryshort=True) entry = self.traceback.getcrashentry() path, lineno = entry.frame.code.raw.co_filename, entry.lineno - return ReprFileLocation(path, lineno+1, exconly) + return ReprFileLocation(path, lineno + 1, exconly) def getrepr(self, showlocals=False, style="long", abspath=False, tbfilter=True, funcargs=False): @@ -469,7 +469,7 @@ def __init__(self, showlocals=False, style="long", abspath=True, tbfilter=True, def _getindent(self, source): # figure out indent for given source try: - s = str(source.getstatement(len(source)-1)) + s = str(source.getstatement(len(source) - 1)) except KeyboardInterrupt: raise except: @@ -513,7 +513,7 @@ def get_source(self, source, line_index=-1, excinfo=None, short=False): for line in source.lines[:line_index]: lines.append(space_prefix + line) lines.append(self.flow_marker + " " + source.lines[line_index]) - for line in source.lines[line_index+1:]: + for line in source.lines[line_index + 1:]: lines.append(space_prefix + line) if excinfo is not None: indent = 4 if short else self._getindent(source) @@ -579,7 +579,7 @@ def repr_traceback_entry(self, entry, excinfo=None): else: message = excinfo and excinfo.typename or "" path = self._makepath(entry.path) - filelocrepr = ReprFileLocation(path, entry.lineno+1, message) + filelocrepr = ReprFileLocation(path, entry.lineno + 1, message) localsrepr = None if not short: localsrepr = self.repr_locals(entry.locals) @@ -758,7 +758,7 @@ def toterminal(self, tw): tw.line("") entry.toterminal(tw) if i < len(self.reprentries) - 1: - next_entry = self.reprentries[i+1] + next_entry = self.reprentries[i + 1] if entry.style == "long" or \ entry.style == "short" and next_entry.style == "long": tw.sep(self.entrysep) diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 54aaca2e935..8b52685332e 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -73,7 +73,7 @@ def strip(self): start, end = 0, len(self) while start < end and not self.lines[start].strip(): start += 1 - while end > start and not self.lines[end-1].strip(): + while end > start and not self.lines[end - 1].strip(): end -= 1 source = Source() source.lines[:] = self.lines[start:end] @@ -95,7 +95,7 @@ def indent(self, indent=' ' * 4): all lines indented by the given indent-string. """ newsource = Source() - newsource.lines = [(indent+line) for line in self.lines] + newsource.lines = [(indent + line) for line in self.lines] return newsource def getstatement(self, lineno, assertion=False): @@ -144,7 +144,7 @@ def isparseable(self, deindent=True): source = str(self) try: #compile(source+'\n', "x", "exec") - syntax_checker(source+'\n') + syntax_checker(source + '\n') except KeyboardInterrupt: raise except Exception: @@ -180,7 +180,7 @@ def compile(self, filename=None, mode='exec', # re-represent syntax errors from parsing python strings msglines = self.lines[:ex.lineno] if ex.offset: - msglines.append(" "*ex.offset + '^') + msglines.append(" " * ex.offset + '^') msglines.append("(code was compiled probably from here: %s)" % filename) newex = SyntaxError('\n'.join(msglines)) newex.offset = ex.offset @@ -274,7 +274,7 @@ def deindent(lines, offset=None): line = line.expandtabs() s = line.lstrip() if s: - offset = len(line)-len(s) + offset = len(line) - len(s) break else: offset = 0 @@ -393,7 +393,7 @@ def getstatementrange_old(lineno, source, assertion=False): raise IndexError("likely a subclass") if "assert" not in line and "raise" not in line: continue - trylines = source.lines[start:lineno+1] + trylines = source.lines[start:lineno + 1] # quick hack to prepare parsing an indented line with # compile_command() (which errors on "return" outside defs) trylines.insert(0, 'def xxx():') @@ -405,7 +405,7 @@ def getstatementrange_old(lineno, source, assertion=False): continue # 2. find the end of the statement - for end in range(lineno+1, len(source)+1): + for end in range(lineno + 1, len(source) + 1): trysource = source[start:end] if trysource.isparseable(): return start, end diff --git a/_pytest/assertion/util.py b/_pytest/assertion/util.py index 06eda8d915d..c2a5ddee01e 100644 --- a/_pytest/assertion/util.py +++ b/_pytest/assertion/util.py @@ -82,7 +82,7 @@ def _format_lines(lines): 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() @@ -91,7 +91,7 @@ def _format_lines(lines): 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 @@ -106,8 +106,8 @@ def _format_lines(lines): def assertrepr_compare(config, op, left, right): """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') % (ecu(left_repr), op, ecu(right_repr)) @@ -285,7 +285,7 @@ def _compare_eq_dict(left, right, verbose=False): 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)] diff --git a/_pytest/compat.py b/_pytest/compat.py index 22cba845099..d89c2922f6e 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -68,7 +68,7 @@ def getlocation(function, curdir): 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) def num_mock_patch_args(function): diff --git a/_pytest/config.py b/_pytest/config.py index a96e6a0154a..9e6a92e1851 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -511,7 +511,7 @@ def getgroup(self, name, description="", after=None): for i, grp in enumerate(self._groups): if grp.name == after: break - self._groups.insert(i+1, group) + self._groups.insert(i + 1, group) return group def addoption(self, *opts, **attrs): diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index aee55c8fac3..f489a87e2a2 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -174,7 +174,7 @@ def reorder_items_atscope(items, ignore, argkeys_cache, scopenum): items_before, items_same, items_other, newignore = \ 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 @@ -631,9 +631,9 @@ def formatrepr(self): lines, _ = inspect.getsourcelines(get_real_func(function)) except (IOError, IndexError, TypeError): error_msg = "file %s, line %s: source code not available" - addline(error_msg % (fspath, lineno+1)) + addline(error_msg % (fspath, lineno + 1)) else: - 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) @@ -675,12 +675,12 @@ def toterminal(self, tw): tw.line('{0} {1}'.format(FormattedExcinfo.flow_marker, line.strip()), red=True) tw.line() - tw.line("%s:%d" % (self.filename, self.firstlineno+1)) + tw.line("%s:%d" % (self.filename, self.firstlineno + 1)) def fail_fixturefunc(fixturefunc, msg): fs, lineno = getfslineno(fixturefunc) - location = "%s:%s" % (fs, lineno+1) + location = "%s:%s" % (fs, lineno + 1) source = _pytest._code.Source(fixturefunc) fail(msg + ":\n\n" + str(source.indent()) + "\n" + location, pytrace=False) @@ -989,7 +989,7 @@ def _getautousenames(self, nodeid): 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) diff --git a/_pytest/main.py b/_pytest/main.py index 3e9c10b592a..74acc409d7a 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -160,7 +160,7 @@ def pytest_runtestloop(session): return True for i, item in enumerate(session.items): - nextitem = session.items[i+1] if i+1 < len(session.items) else None + nextitem = session.items[i + 1] if i + 1 < len(session.items) else None item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) if session.shouldstop: raise session.Interrupted(session.shouldstop) diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 223bdd79b21..bbe95f504fc 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -763,7 +763,7 @@ class reprec: res = RunResult(reprec.ret, out.split("\n"), err.split("\n"), - time.time()-now) + time.time() - now) res.reprec = reprec return res @@ -948,7 +948,7 @@ def _run(self, *cmdargs): f2.close() self._dump_lines(out, sys.stdout) self._dump_lines(err, sys.stderr) - return RunResult(ret, out, err, time.time()-now) + return RunResult(ret, out, err, time.time() - now) def _dump_lines(self, lines, fp): try: @@ -1105,7 +1105,7 @@ def get_lines_after(self, fnline): """ for i, line in enumerate(self.lines): if fnline == line or fnmatch(line, fnline): - return self.lines[i+1:] + return self.lines[i + 1:] raise ValueError("line %r not found in output" % fnline) def _log(self, *args): diff --git a/_pytest/python.py b/_pytest/python.py index cb42c3fe2b5..b12cc926f26 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -947,7 +947,7 @@ def _idval(val, argname, idx, idfn, config=None): return str(val) elif isclass(val) and hasattr(val, '__name__'): return val.__name__ - return str(argname)+str(idx) + return str(argname) + str(idx) def _idvalset(idx, parameterset, argnames, idfn, ids, config=None): diff --git a/_pytest/runner.py b/_pytest/runner.py index d029394caa5..0ef3b30fbc5 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -245,7 +245,7 @@ def fspath(self): def pytest_runtest_makereport(item, call): when = call.when - duration = call.stop-call.start + duration = call.stop - call.start keywords = dict([(x,1) for x in item.keywords]) excinfo = call.excinfo sections = [] diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index 1b160960014..b95e0cc4c15 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -255,7 +255,7 @@ def pytest_collect_file(path, parent): 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*", diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 73fd5159570..96e42de16d4 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -143,7 +143,7 @@ def test_traceback_cut(self): traceback = self.excinfo.traceback newtraceback = traceback.cut(path=path, firstlineno=firstlineno) assert len(newtraceback) == 1 - newtraceback = traceback.cut(path=path, lineno=firstlineno+2) + newtraceback = traceback.cut(path=path, lineno=firstlineno + 2) assert len(newtraceback) == 1 def test_traceback_cut_excludepath(self, testdir): @@ -210,7 +210,7 @@ def test_traceback_only_specific_recursion_errors(self, monkeypatch): def f(n): if n == 0: raise RuntimeError("hello") - f(n-1) + f(n - 1) excinfo = pytest.raises(RuntimeError, f, 100) monkeypatch.delattr(excinfo.traceback.__class__, "recursionindex") @@ -492,7 +492,7 @@ class FakeFrame(object): class FakeTracebackEntry(_pytest._code.Traceback.Entry): def __init__(self, tb, excinfo=None): - self.lineno = 5+3 + self.lineno = 5 + 3 @property def frame(self): @@ -582,12 +582,12 @@ def test_repr_tracebackentry_lines2(self, importasmod): def func1(m, x, y, z): raise ValueError("hello\\nworld") """) - excinfo = pytest.raises(ValueError, mod.func1, "m"*90, 5, 13, "z"*120) + excinfo = pytest.raises(ValueError, mod.func1, "m" * 90, 5, 13, "z" * 120) excinfo.traceback = excinfo.traceback.filter() entry = excinfo.traceback[-1] p = FormattedExcinfo(funcargs=True) reprfuncargs = p.repr_args(entry) - assert reprfuncargs.args[0] == ('m', repr("m"*90)) + assert reprfuncargs.args[0] == ('m', repr("m" * 90)) assert reprfuncargs.args[1] == ('x', '5') assert reprfuncargs.args[2] == ('y', '13') assert reprfuncargs.args[3] == ('z', repr("z" * 120)) diff --git a/testing/code/test_source.py b/testing/code/test_source.py index dc48b29c311..53703fc5725 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -291,9 +291,9 @@ def test_compilefuncs_and_path_sanity(self, name): def check(comp, name): co = comp(self.source, name) if not name: - expected = "codegen %s:%d>" % (mypath, mylineno+2+2) + expected = "codegen %s:%d>" % (mypath, mylineno + 2 + 2) else: - expected = "codegen %r %s:%d>" % (name, mypath, mylineno+2+2) + expected = "codegen %r %s:%d>" % (name, mypath, mylineno + 2 + 2) fn = co.co_filename assert fn.endswith(expected) diff --git a/testing/test_assertion.py b/testing/test_assertion.py index e17e7418329..45152c00c2d 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -303,15 +303,15 @@ def test_text_diff(self): 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' @@ -609,7 +609,7 @@ def test_doesnt_truncate_when_input_is_empty_list(self): def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self): expl = ['a' * 100 for x in range(5)] - result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8*80) + result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80) assert result == expl def test_truncates_at_8_lines_when_given_list_of_empty_strings(self): @@ -624,7 +624,7 @@ def test_truncates_at_8_lines_when_given_list_of_empty_strings(self): def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self): expl = ['a' for x in range(100)] - result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8*80) + result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80) assert result != expl assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG assert "Full output truncated" in result[-1] @@ -634,7 +634,7 @@ def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self): def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self): expl = ['a' * 80 for x in range(16)] - result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8*80) + result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80) assert result != expl assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG assert "Full output truncated" in result[-1] diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py index 31df4dd3945..a8f83d5674b 100644 --- a/testing/test_resultlog.py +++ b/testing/test_resultlog.py @@ -68,7 +68,7 @@ def test_write_log_entry(): entry_lines = entry.splitlines() assert len(entry_lines) == 5 assert entry_lines[0] == 'F name' - assert entry_lines[1:] == [' '+line for line in longrepr.splitlines()] + assert entry_lines[1:] == [' ' + line for line in longrepr.splitlines()] class TestWithFunctionIntegration(object): diff --git a/testing/test_runner.py b/testing/test_runner.py index 1b796917a27..020cc281607 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -395,7 +395,7 @@ def test_callinfo(): assert ci.when == "123" assert ci.result == 0 assert "result" in repr(ci) - ci = runner.CallInfo(lambda: 0/0, '123') + ci = runner.CallInfo(lambda: 0 / 0, '123') assert ci.when == "123" assert not hasattr(ci, 'result') assert ci.excinfo diff --git a/testing/test_runner_xunit.py b/testing/test_runner_xunit.py index 92ba97202f8..676d119ffa1 100644 --- a/testing/test_runner_xunit.py +++ b/testing/test_runner_xunit.py @@ -90,7 +90,7 @@ def test_cleanup(): assert not TestSimpleClassSetup.clslevel assert not TestInheritedClassSetupStillWorks.clslevel """) - reprec.assertoutcome(passed=1+2+1) + reprec.assertoutcome(passed=1 + 2 + 1) def test_class_setup_failure_no_teardown(testdir): reprec = testdir.inline_runsource(""" diff --git a/testing/test_skipping.py b/testing/test_skipping.py index afd5df16f55..606560f4c95 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -80,7 +80,7 @@ def test_marked_one_arg_twice(self, testdir): %s def test_func(): pass - """ % (lines[i], lines[(i+1) % 2])) + """ % (lines[i], lines[(i + 1) % 2])) ev = MarkEvaluator(item, 'skipif') assert ev assert ev.istrue() diff --git a/tox.ini b/tox.ini index fd0cc814dc8..521f19153a3 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E226,E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 617e510b6e4fb2e95a1486c8f30dd1e7583be248 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 30/58] Fixed E231 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit missing whitespace after ‘,’, ‘;’, or ‘:’ --- _pytest/_code/source.py | 4 ++-- _pytest/assertion/rewrite.py | 4 ++-- _pytest/capture.py | 2 +- _pytest/config.py | 2 +- _pytest/fixtures.py | 2 +- _pytest/helpconfig.py | 2 +- _pytest/python.py | 8 +++---- _pytest/runner.py | 2 +- _pytest/terminal.py | 6 ++--- testing/acceptance_test.py | 4 ++-- testing/code/test_excinfo.py | 2 +- testing/code/test_source.py | 10 ++++---- testing/python/approx.py | 2 +- testing/python/collect.py | 8 +++---- testing/python/fixture.py | 18 +++++++------- testing/python/metafunc.py | 44 +++++++++++++++++------------------ testing/test_argcomplete.py | 10 ++++---- testing/test_assertion.py | 4 ++-- testing/test_assertrewrite.py | 2 +- testing/test_capture.py | 2 +- testing/test_collection.py | 6 ++--- testing/test_config.py | 2 +- testing/test_conftest.py | 2 +- testing/test_mark.py | 2 +- testing/test_parseopt.py | 6 ++--- testing/test_pastebin.py | 4 ++-- testing/test_runner.py | 2 +- testing/test_terminal.py | 10 ++++---- tox.ini | 2 +- 29 files changed, 87 insertions(+), 87 deletions(-) diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 8b52685332e..b17d15659f8 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -165,7 +165,7 @@ def compile(self, filename=None, mode='exec', if not filename or py.path.local(filename).check(file=0): if _genframe is None: _genframe = sys._getframe(1) # the caller - fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno + fn, lineno = _genframe.f_code.co_filename, _genframe.f_lineno base = "<%d-codegen " % self._compilecounter self.__class__._compilecounter += 1 if not filename: @@ -337,7 +337,7 @@ def get_statement_startend2(lineno, node): def getstatementrange_ast(lineno, source, assertion=False, astnode=None): if astnode is None: content = str(source) - if sys.version_info < (2,7): + if sys.version_info < (2, 7): content += "\n" try: astnode = compile(content, "source", "exec", 1024) # 1024 for AST diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 2ffa3c03e04..1ae41bd1459 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -36,10 +36,10 @@ REWRITE_NEWLINES = sys.version_info[:2] != (2, 7) and sys.version_info < (3, 2) ASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3 -if sys.version_info >= (3,5): +if sys.version_info >= (3, 5): ast_Call = ast.Call else: - ast_Call = lambda a,b,c: ast.Call(a, b, c, None, None) + ast_Call = lambda a, b, c: ast.Call(a, b, c, None, None) class AssertionRewritingHook(object): diff --git a/_pytest/capture.py b/_pytest/capture.py index 3661f26919e..1231ae8251f 100644 --- a/_pytest/capture.py +++ b/_pytest/capture.py @@ -463,7 +463,7 @@ def close(self): @property def buffer(self): - if sys.version_info >= (3,0): + if sys.version_info >= (3, 0): return self else: raise AttributeError('redirected stdin has no attribute buffer') diff --git a/_pytest/config.py b/_pytest/config.py index 9e6a92e1851..68da9c3423d 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -392,7 +392,7 @@ def _importconftest(self, conftestpath): # def consider_preparse(self, args): - for opt1,opt2 in zip(args, args[1:]): + for opt1, opt2 in zip(args, args[1:]): if opt1 == "-p": self.consider_pluginarg(opt2) diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index f489a87e2a2..12d7bbb83a0 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -174,7 +174,7 @@ def reorder_items_atscope(items, ignore, argkeys_cache, scopenum): items_before, items_same, items_other, newignore = \ 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 diff --git a/_pytest/helpconfig.py b/_pytest/helpconfig.py index 72484fda51f..d5fee5d549a 100644 --- a/_pytest/helpconfig.py +++ b/_pytest/helpconfig.py @@ -161,7 +161,7 @@ def pytest_report_header(config): lines = [] if config.option.debug or config.option.traceconfig: lines.append("using: pytest-%s pylib-%s" % - (pytest.__version__,py.__version__)) + (pytest.__version__, py.__version__)) verinfo = getpluginversioninfo(config) if verinfo: diff --git a/_pytest/python.py b/_pytest/python.py index b12cc926f26..f63d6bbc4b0 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -76,9 +76,9 @@ def pytest_addoption(parser): 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") @@ -357,7 +357,7 @@ def _genfunctions(self, name, funcobj): yield Function(name=subname, parent=self, callspec=callspec, callobj=funcobj, fixtureinfo=fixtureinfo, - keywords={callspec.id:True}, + keywords={callspec.id: True}, originalname=name, ) @@ -687,7 +687,7 @@ def id(self): def setmulti(self, valtypes, argnames, valset, id, keywords, scopenum, param_index): - for arg,val in zip(argnames, valset): + for arg, val in zip(argnames, valset): self._checkargnotcontained(arg) valtype_for_arg = valtypes[arg] getattr(self, valtype_for_arg)[arg] = val diff --git a/_pytest/runner.py b/_pytest/runner.py index 0ef3b30fbc5..21401e92b19 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -246,7 +246,7 @@ def fspath(self): def pytest_runtest_makereport(item, call): when = call.when duration = call.stop - call.start - keywords = dict([(x,1) for x in item.keywords]) + keywords = dict([(x, 1) for x in item.keywords]) excinfo = call.excinfo sections = [] if not call.excinfo: diff --git a/_pytest/terminal.py b/_pytest/terminal.py index f57f6e46603..55e57b97a55 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -240,11 +240,11 @@ def pytest_runtest_logreport(self, report): word, markup = word else: if rep.passed: - markup = {'green':True} + markup = {'green': True} elif rep.failed: - markup = {'red':True} + markup = {'red': True} elif rep.skipped: - markup = {'yellow':True} + markup = {'yellow': True} line = self._locationline(rep.nodeid, *rep.location) if not hasattr(rep, 'node'): self.write_ensure_prefix(line, word, **markup) diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index b95e0cc4c15..9ea200b128e 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -719,12 +719,12 @@ def test_calls_showall(self, testdir): 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) diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 96e42de16d4..2eb340fae92 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -325,7 +325,7 @@ def test_excinfo_no_sourcecode(): except ValueError: excinfo = _pytest._code.ExceptionInfo() s = str(excinfo.traceback[-1]) - if py.std.sys.version_info < (2,5): + if py.std.sys.version_info < (2, 5): assert s == " File '':1 in ?\n ???\n" else: assert s == " File '':1 in \n ???\n" diff --git a/testing/code/test_source.py b/testing/code/test_source.py index 53703fc5725..f12b8a1a1c9 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -109,7 +109,7 @@ def test_source_strip_multiline(): def test_syntaxerror_rerepresentation(): ex = pytest.raises(SyntaxError, _pytest._code.compile, 'xyz xyz') assert ex.value.lineno == 1 - assert ex.value.offset in (4,7) # XXX pypy/jython versus cpython? + assert ex.value.offset in (4, 7) # XXX pypy/jython versus cpython? assert ex.value.text.strip(), 'x x' def test_isparseable(): @@ -262,7 +262,7 @@ def test_some(): def test_getstatementrange_out_of_bounds_py3(self): source = Source("if xxx:\n from .collections import something") r = source.getstatementrange(1) - assert r == (1,2) + assert r == (1, 2) def test_getstatementrange_with_syntaxerror_issue7(self): source = Source(":") @@ -524,9 +524,9 @@ def test_comments(): comment 4 """ ''' - for line in range(2,6): + for line in range(2, 6): assert str(getstatement(line, source)) == ' x = 1' - for line in range(6,10): + for line in range(6, 10): assert str(getstatement(line, source)) == ' assert False' assert str(getstatement(10, source)) == '"""' @@ -535,7 +535,7 @@ def test_comment_in_statement(): # comment 1 bar=2) ''' - for line in range(1,3): + for line in range(1, 3): assert str(getstatement(line, source)) == \ 'test(foo=1,\n # comment 1\n bar=2)' diff --git a/testing/python/approx.py b/testing/python/approx.py index 853f2fe02ea..f849ede160e 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -239,7 +239,7 @@ def test_expecting_sequence(self): def test_expecting_sequence_wrong_len(self): assert [1, 2] != approx([1]) - assert [1, 2] != approx([1,2,3]) + assert [1, 2] != approx([1, 2, 3]) def test_complex(self): within_1e6 = [ diff --git a/testing/python/collect.py b/testing/python/collect.py index 968e56ff58b..eeae5bc1696 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -421,7 +421,7 @@ def func2(): f1 = pytest.Function(name="name", parent=session, config=config, args=(1,), callobj=func1) assert f1 == f1 - f2 = pytest.Function(name="name",config=config, + f2 = pytest.Function(name="name", config=config, callobj=func2, parent=session) assert f1 != f2 @@ -733,11 +733,11 @@ def test_fail(): assert 0 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_allow_sane_sorting_for_decorators(self, testdir): diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 751be095b8f..8d1d67959aa 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -25,7 +25,7 @@ def f(self, arg1, arg2="hello"): pass assert fixtures.getfuncargnames(A().f) == ('arg1',) - if sys.version_info < (3,0): + if sys.version_info < (3, 0): assert fixtures.getfuncargnames(A.f) == ('arg1',) class TestFillFixtures(object): @@ -817,7 +817,7 @@ def test_1(arg): class TestRequestMarking(object): def test_applymarker(self, testdir): - item1,item2 = testdir.getitems(""" + item1, item2 = testdir.getitems(""" import pytest @pytest.fixture @@ -1297,7 +1297,7 @@ def test_2(arg2): reprec = testdir.inline_run("-v") reprec.assertoutcome(passed=4) l = reprec.getcalls("pytest_runtest_call")[0].item.module.l - assert l == [1,2, 10,20] + assert l == [1, 2, 10, 20] class TestFixtureManagerParseFactories(object): @@ -1706,7 +1706,7 @@ def test_2(self): pass """) confcut = "--confcutdir={0}".format(testdir.tmpdir) - reprec = testdir.inline_run("-v","-s", confcut) + reprec = testdir.inline_run("-v", "-s", confcut) reprec.assertoutcome(passed=8) config = reprec.getcalls("pytest_unconfigure")[0].config l = config.pluginmanager._getconftestmodules(p)[0].l @@ -1776,8 +1776,8 @@ def test_hello(arg1): reprec.assertoutcome(passed=1) @pytest.mark.issue226 - @pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00","p01"]) - @pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10","p11"]) + @pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00", "p01"]) + @pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10", "p11"]) def test_ordering_dependencies_torndown_first(self, testdir, param1, param2): testdir.makepyfile(""" import pytest @@ -2108,7 +2108,7 @@ def test_2(arg): reprec = testdir.inline_run("-v") reprec.assertoutcome(passed=4) l = reprec.getcalls("pytest_runtest_call")[0].item.module.l - assert l == [1,1,2,2] + assert l == [1, 1, 2, 2] def test_module_parametrized_ordering(self, testdir): testdir.makeconftest(""" @@ -2351,7 +2351,7 @@ def test_fix(fix): """) reprec = testdir.inline_run("-s") l = reprec.getcalls("pytest_runtest_call")[0].item.module.l - assert l == [1,2] + assert l == [1, 2] def test_parametrize_separated_lifecycle(self, testdir): testdir.makepyfile(""" @@ -2544,7 +2544,7 @@ def test_foo(fix): class TestRequestScopeAccess(object): - pytestmark = pytest.mark.parametrize(("scope", "ok", "error"),[ + pytestmark = pytest.mark.parametrize(("scope", "ok", "error"), [ ["session", "", "fspath class function module"], ["module", "module fspath", "cls function"], ["class", "module fspath cls", "function"], diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 8718f6d5287..c97dfcdccfa 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -96,12 +96,12 @@ class obj(object): pass def test_parametrize_error(self): def func(x, y): pass metafunc = self.Metafunc(func) - metafunc.parametrize("x", [1,2]) - pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5,6])) - pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5,6])) - metafunc.parametrize("y", [1,2]) - pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5,6])) - pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5,6])) + metafunc.parametrize("x", [1, 2]) + pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5, 6])) + pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5, 6])) + metafunc.parametrize("y", [1, 2]) + pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6])) + pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6])) def test_parametrize_bad_scope(self, testdir): def func(x): pass @@ -115,7 +115,7 @@ def test_parametrize_and_id(self): def func(x, y): pass metafunc = self.Metafunc(func) - metafunc.parametrize("x", [1,2], ids=['basic', 'advanced']) + metafunc.parametrize("x", [1, 2], ids=['basic', 'advanced']) metafunc.parametrize("y", ["abc", "def"]) ids = [x.id for x in metafunc._calls] assert ids == ["basic-abc", "basic-def", "advanced-abc", "advanced-def"] @@ -133,11 +133,11 @@ def func(x, y): pass metafunc = self.Metafunc(func) pytest.raises(ValueError, lambda: - metafunc.parametrize("x", [1,2], ids=['basic'])) + metafunc.parametrize("x", [1, 2], ids=['basic'])) pytest.raises(ValueError, lambda: - metafunc.parametrize(("x","y"), [("abc", "def"), - ("ghi", "jkl")], ids=["one"])) + metafunc.parametrize(("x", "y"), [("abc", "def"), + ("ghi", "jkl")], ids=["one"])) @pytest.mark.issue510 def test_parametrize_empty_list(self): @@ -371,7 +371,7 @@ def test_idmaker_with_paramset_id(self): def test_idmaker_with_ids_unique_names(self): from _pytest.python import idmaker - result = idmaker(("a"), map(pytest.param, [1,2,3,4,5]), + result = idmaker(("a"), map(pytest.param, [1, 2, 3, 4, 5]), ids=["a", "a", "b", "c", "b"]) assert result == ["a0", "a1", "b0", "c", "b1"] @@ -379,7 +379,7 @@ def test_addcall_and_parametrize(self): def func(x, y): pass metafunc = self.Metafunc(func) metafunc.addcall({'x': 1}) - metafunc.parametrize('y', [2,3]) + metafunc.parametrize('y', [2, 3]) assert len(metafunc._calls) == 2 assert metafunc._calls[0].funcargs == {'x': 1, 'y': 2} assert metafunc._calls[1].funcargs == {'x': 1, 'y': 3} @@ -391,12 +391,12 @@ def test_parametrize_indirect(self): def func(x, y): pass metafunc = self.Metafunc(func) metafunc.parametrize('x', [1], indirect=True) - metafunc.parametrize('y', [2,3], indirect=True) + metafunc.parametrize('y', [2, 3], indirect=True) assert len(metafunc._calls) == 2 assert metafunc._calls[0].funcargs == {} assert metafunc._calls[1].funcargs == {} - assert metafunc._calls[0].params == dict(x=1,y=2) - assert metafunc._calls[1].params == dict(x=1,y=3) + assert metafunc._calls[0].params == dict(x=1, y=2) + assert metafunc._calls[1].params == dict(x=1, y=3) @pytest.mark.issue714 def test_parametrize_indirect_list(self): @@ -554,12 +554,12 @@ def func(x, y): pass metafunc = self.Metafunc(func) metafunc.addcall(param="123") metafunc.parametrize('x', [1], indirect=True) - metafunc.parametrize('y', [2,3], indirect=True) + metafunc.parametrize('y', [2, 3], indirect=True) assert len(metafunc._calls) == 2 assert metafunc._calls[0].funcargs == {} assert metafunc._calls[1].funcargs == {} - assert metafunc._calls[0].params == dict(x=1,y=2) - assert metafunc._calls[1].params == dict(x=1,y=3) + assert metafunc._calls[0].params == dict(x=1, y=2) + assert metafunc._calls[1].params == dict(x=1, y=3) def test_parametrize_functional(self, testdir): testdir.makepyfile(""" @@ -584,7 +584,7 @@ def test_simple(x,y): def test_parametrize_onearg(self): metafunc = self.Metafunc(lambda x: None) - metafunc.parametrize("x", [1,2]) + metafunc.parametrize("x", [1, 2]) assert len(metafunc._calls) == 2 assert metafunc._calls[0].funcargs == dict(x=1) assert metafunc._calls[0].id == "1" @@ -593,15 +593,15 @@ def test_parametrize_onearg(self): def test_parametrize_onearg_indirect(self): metafunc = self.Metafunc(lambda x: None) - metafunc.parametrize("x", [1,2], indirect=True) + metafunc.parametrize("x", [1, 2], indirect=True) assert metafunc._calls[0].params == dict(x=1) assert metafunc._calls[0].id == "1" assert metafunc._calls[1].params == dict(x=2) assert metafunc._calls[1].id == "2" def test_parametrize_twoargs(self): - metafunc = self.Metafunc(lambda x,y: None) - metafunc.parametrize(("x", "y"), [(1,2), (3,4)]) + metafunc = self.Metafunc(lambda x, y: None) + metafunc.parametrize(("x", "y"), [(1, 2), (3, 4)]) assert len(metafunc._calls) == 2 assert metafunc._calls[0].funcargs == dict(x=1, y=2) assert metafunc._calls[0].id == "1-2" diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py index 32705e1304f..0c11b1bc928 100644 --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -19,8 +19,8 @@ def equal_with_bash(prefix, ffc, fc, out=None): # 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.') process = py.std.subprocess.Popen( @@ -38,7 +38,7 @@ def _wrapcall(*args, **kargs): 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,12 +50,12 @@ def __call__(self, prefix, **kwargs): completion = [] if self.allowednames: if self.directories: - files = _wrapcall(['bash','-c', + 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)]) + "compgen -A file -X '!*.{0}' -- '{p}'".format(x, p=prefix)]) else: completion += _wrapcall(['bash', '-c', "compgen -A file -- '{p}'".format(p=prefix)]) diff --git a/testing/test_assertion.py b/testing/test_assertion.py index 45152c00c2d..08600654575 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -437,9 +437,9 @@ def insert(self, item, index): 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): diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index cd16b0a684a..73beaf02aac 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -638,7 +638,7 @@ def test_translate_newlines(self, testdir): testdir.tmpdir.join("test_newlines.py").write(b, "wb") assert testdir.runpytest().ret == 0 - @pytest.mark.skipif(sys.version_info < (3,3), + @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') diff --git a/testing/test_capture.py b/testing/test_capture.py index 9ed605d2577..cb9431141ce 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -112,7 +112,7 @@ def test_init_capturing(self): @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'" diff --git a/testing/test_collection.py b/testing/test_collection.py index 834eaa300ff..ce5e9990843 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -42,11 +42,11 @@ def test_fail(): assert 0 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): diff --git a/testing/test_config.py b/testing/test_config.py index 5022ac82276..463c2edd73b 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -666,7 +666,7 @@ def test_with_ini(self, tmpdir, name): rootdir, inifile, inicfg = determine_setup(None, args) assert rootdir == tmpdir assert inifile == inifile - rootdir, inifile, inicfg = determine_setup(None, [b,a]) + rootdir, inifile, inicfg = determine_setup(None, [b, a]) assert rootdir == tmpdir assert inifile == inifile diff --git a/testing/test_conftest.py b/testing/test_conftest.py index 3b01cc3cd24..7fdddb0d5de 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -345,7 +345,7 @@ def test_no_conftest(fxtr): ]) @pytest.mark.issue616 def test_parsefactories_relative_node_ids( - self, testdir, chdir,testarg, expect_ntests_passed): + self, testdir, chdir, testarg, expect_ntests_passed): dirs = self._setup_tree(testdir) print("pytest run in cwd: %s" % ( dirs[chdir].relto(testdir.tmpdir))) diff --git a/testing/test_mark.py b/testing/test_mark.py index 309e2379ca8..7a437b4a3b5 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -8,7 +8,7 @@ class TestMark(object): def test_markinfo_repr(self): from _pytest.mark import MarkInfo, Mark - m = MarkInfo(Mark("hello", (1,2), {})) + m = MarkInfo(Mark("hello", (1, 2), {})) repr(m) @pytest.mark.parametrize('attr', ['mark', 'param']) diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index 6fc46ef24ea..ccc951d66ec 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -284,7 +284,7 @@ def test_argcomplete(testdir, monkeypatch): # to handle a keyword argument env that replaces os.environ in popen or # extends the copy, advantage: could not forget to restore monkeypatch.setenv('_ARGCOMPLETE', "1") - monkeypatch.setenv('_ARGCOMPLETE_IFS',"\x0b") + monkeypatch.setenv('_ARGCOMPLETE_IFS', "\x0b") monkeypatch.setenv('COMP_WORDBREAKS', ' \\t\\n"\\\'><=;|&(:') arg = '--fu' @@ -297,12 +297,12 @@ def test_argcomplete(testdir, monkeypatch): elif not result.stdout.str(): pytest.skip("bash provided no output, argcomplete not available?") else: - if py.std.sys.version_info < (2,7): + if py.std.sys.version_info < (2, 7): result.stdout.lines = result.stdout.lines[0].split('\x0b') result.stdout.fnmatch_lines(["--funcargs", "--fulltrace"]) else: result.stdout.fnmatch_lines(["--funcargs", "--fulltrace"]) - if py.std.sys.version_info < (2,7): + if py.std.sys.version_info < (2, 7): return os.mkdir('test_argcomplete.d') arg = 'test_argc' diff --git a/testing/test_pastebin.py b/testing/test_pastebin.py index f7716f8fd28..d8610ea180a 100644 --- a/testing/test_pastebin.py +++ b/testing/test_pastebin.py @@ -26,7 +26,7 @@ def test_skip(): assert len(pastebinlist) == 1 s = pastebinlist[0] assert s.find("def test_fail") != -1 - assert reprec.countoutcomes() == [1,1,1] + assert reprec.countoutcomes() == [1, 1, 1] def test_all(self, testdir, pastebinlist): from _pytest.pytester import LineMatcher @@ -40,7 +40,7 @@ def test_skip(): pytest.skip("") """) reprec = testdir.inline_run(testpath, "--pastebin=all", '-v') - assert reprec.countoutcomes() == [1,1,1] + assert reprec.countoutcomes() == [1, 1, 1] assert len(pastebinlist) == 1 contents = pastebinlist[0].decode('utf-8') matcher = LineMatcher(contents.splitlines()) diff --git a/testing/test_runner.py b/testing/test_runner.py index 020cc281607..efaab1993c4 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -227,7 +227,7 @@ def teardown_function(func): assert reps[2].when == "teardown" assert reps[2].failed assert len(reps) == 6 - for i in range(3,5): + for i in range(3, 5): assert reps[i].nodeid.endswith("test_func") assert reps[i].passed assert reps[5].when == "teardown" diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 048cdc82126..a03d54af45e 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -872,7 +872,7 @@ def pytest_terminal_summary(terminalreporter): ("yellow", "1 passed, 1 warnings", {"warnings": (1,), "passed": (1,)}), - ("green", "5 passed", {"passed": (1,2,3,4,5)}), + ("green", "5 passed", {"passed": (1, 2, 3, 4, 5)}), # "Boring" statuses. These have no effect on the color of the summary @@ -901,13 +901,13 @@ def pytest_terminal_summary(terminalreporter): # A couple more complex combinations ("red", "1 failed, 2 passed, 3 xfailed", - {"passed": (1,2), "failed": (1,), "xfailed": (1,2,3)}), + {"passed": (1, 2), "failed": (1,), "xfailed": (1, 2, 3)}), ("green", "1 passed, 2 skipped, 3 deselected, 2 xfailed", {"passed": (1,), - "skipped": (1,2), - "deselected": (1,2,3), - "xfailed": (1,2)}), + "skipped": (1, 2), + "deselected": (1, 2, 3), + "xfailed": (1, 2)}), ]) def test_summary_stats(exp_line, exp_color, stats_arg): print("Based on stats: %s" % stats_arg) diff --git a/tox.ini b/tox.ini index 521f19153a3..473ac3fd78d 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E231,E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 4c24947785f9dd758038742d66376db5942cf76e Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 31/58] Fixed E241 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit multiple spaces after ‘,’ --- _pytest/pytester.py | 8 ++++---- testing/test_conftest.py | 32 ++++++++++++++++---------------- testing/test_doctest.py | 6 +++--- tox.ini | 2 +- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/_pytest/pytester.py b/_pytest/pytester.py index bbe95f504fc..3c3a0d3b701 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -821,7 +821,7 @@ def parseconfigure(self, *args): self.request.addfinalizer(config._ensure_unconfigure) return config - def getitem(self, source, funcname="test_func"): + def getitem(self, source, funcname="test_func"): """Return the test item for a test function. This writes the source to a python file and runs pytest's @@ -841,7 +841,7 @@ def getitem(self, source, funcname="test_func"): assert 0, "%r item not found in module:\n%s\nitems: %s" % ( funcname, source, items) - def getitems(self, source): + def getitems(self, source): """Return all test items collected from the module. This writes the source to a python file and runs pytest's @@ -852,7 +852,7 @@ def getitems(self, source): modcol = self.getmodulecol(source) return self.genitems([modcol]) - def getmodulecol(self, source, configargs=(), withinit=False): + def getmodulecol(self, source, configargs=(), withinit=False): """Return the module collection node for ``source``. This writes ``source`` to a file using :py:meth:`makepyfile` @@ -1066,7 +1066,7 @@ class LineMatcher: """ - def __init__(self, lines): + def __init__(self, lines): self.lines = lines self._log_output = [] diff --git a/testing/test_conftest.py b/testing/test_conftest.py index 7fdddb0d5de..dd696fe5b06 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -320,28 +320,28 @@ def test_no_conftest(fxtr): # "snc" stands for "subdir no [i.e. without] conftest.py" @pytest.mark.parametrize("chdir,testarg,expect_ntests_passed", [ # Effective target: package/.. - ("runner", "..", 3), - ("package", "..", 3), - ("swc", "../..", 3), - ("snc", "../..", 3), + ("runner", "..", 3), + ("package", "..", 3), + ("swc", "../..", 3), + ("snc", "../..", 3), # Effective target: package - ("runner", "../package", 3), - ("package", ".", 3), - ("swc", "..", 3), - ("snc", "..", 3), + ("runner", "../package", 3), + ("package", ".", 3), + ("swc", "..", 3), + ("snc", "..", 3), # Effective target: package/swc - ("runner", "../package/swc", 1), - ("package", "./swc", 1), - ("swc", ".", 1), - ("snc", "../swc", 1), + ("runner", "../package/swc", 1), + ("package", "./swc", 1), + ("swc", ".", 1), + ("snc", "../swc", 1), # Effective target: package/snc - ("runner", "../package/snc", 1), - ("package", "./snc", 1), - ("swc", "../snc", 1), - ("snc", ".", 1), + ("runner", "../package/snc", 1), + ("package", "./snc", 1), + ("swc", "../snc", 1), + ("snc", ".", 1), ]) @pytest.mark.issue616 def test_parsefactories_relative_node_ids( diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 9f7138ebdde..ec3f8ba7ae1 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -135,9 +135,9 @@ def test_multiple_patterns(self, testdir): @pytest.mark.parametrize( ' test_string, encoding', [ - (u'foo', 'ascii'), - (u'öäü', 'latin1'), - (u'öäü', 'utf-8') + (u'foo', 'ascii'), + (u'öäü', 'latin1'), + (u'öäü', 'utf-8') ] ) def test_encoding(self, testdir, test_string, encoding): diff --git a/tox.ini b/tox.ini index 473ac3fd78d..3969897e77c 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E241,E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From b226454582f8fbf083e31cc54e67c52e36176e53 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:08 +0200 Subject: [PATCH 32/58] Fixed E251 flake8 errors unexpected spaces around keyword / parameter equals --- _pytest/_code/source.py | 3 +-- _pytest/helpconfig.py | 2 +- _pytest/pytester.py | 2 +- _pytest/python.py | 3 +-- testing/test_config.py | 2 +- testing/test_parseopt.py | 2 +- testing/test_resultlog.py | 8 ++++---- testing/test_skipping.py | 2 +- testing/test_terminal.py | 2 +- tox.ini | 2 +- 10 files changed, 13 insertions(+), 15 deletions(-) diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index b17d15659f8..f86d96c9c54 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -198,8 +198,7 @@ def compile(self, filename=None, mode='exec', # public API shortcut functions # -def compile_(source, filename=None, mode='exec', flags= - generators.compiler_flag, dont_inherit=0): +def compile_(source, filename=None, mode='exec', flags=generators.compiler_flag, dont_inherit=0): """ compile the given source to a raw code object, and maintain an internal cache which allows later retrieval of the source code for the code object diff --git a/_pytest/helpconfig.py b/_pytest/helpconfig.py index d5fee5d549a..320eb4ab6c4 100644 --- a/_pytest/helpconfig.py +++ b/_pytest/helpconfig.py @@ -44,7 +44,7 @@ def pytest_addoption(parser): help="display pytest lib version and import information.") group._addoption("-h", "--help", action=HelpAction, dest="help", help="show help message and configuration info") - group._addoption('-p', action="append", dest="plugins", default = [], + group._addoption('-p', action="append", dest="plugins", default=[], metavar="name", help="early-load given plugin (multi-allowed). " "To avoid loading of plugins, use the `no:` prefix, e.g. " diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 3c3a0d3b701..46a273dbb2e 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -871,7 +871,7 @@ def getmodulecol(self, source, configargs=(), withinit=False): kw = {self.request.function.__name__: Source(source).strip()} path = self.makepyfile(**kw) if withinit: - self.makepyfile(__init__ = "#") + self.makepyfile(__init__="#") self.config = config = self.parseconfigure(path, *configargs) node = self.getnode(config, path) diff --git a/_pytest/python.py b/_pytest/python.py index f63d6bbc4b0..56ad8ea3e26 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -176,8 +176,7 @@ def pytest_pycollect_makeitem(collector, name, obj): # or a funtools.wrapped. # We musn't if it's been wrapped with mock.patch (python 2 only) if not (isfunction(obj) or isfunction(get_real_func(obj))): - collector.warn(code="C2", message= - "cannot collect %r because it is not a function." + collector.warn(code="C2", message="cannot collect %r because it is not a function." % name, ) elif getattr(obj, "__test__", True): if is_generator(obj): diff --git a/testing/test_config.py b/testing/test_config.py index 463c2edd73b..283155e6c08 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -99,7 +99,7 @@ def pytest_addoption(parser): [pytest] custom = 0 """) - testdir.makefile(".cfg", custom = """ + testdir.makefile(".cfg", custom=""" [pytest] custom = 1 """) diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index ccc951d66ec..3e3919a3884 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -238,7 +238,7 @@ def test_drop_short_3(self, parser): assert args.file_or_dir == ['abcd'] def test_drop_short_help0(self, parser, capsys): - parser.addoption('--func-args', '--doit', help = 'foo', + parser.addoption('--func-args', '--doit', help='foo', action='store_true') parser.parse([]) help = parser.optparser.format_help() diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py index a8f83d5674b..7bbaa458cd9 100644 --- a/testing/test_resultlog.py +++ b/testing/test_resultlog.py @@ -16,8 +16,8 @@ def test_generic_path(testdir): p1 = Node('a', config=config, session=session) #assert p1.fspath is None p2 = Node('B', parent=p1) - p3 = Node('()', parent = p2) - item = Item('c', parent = p3) + p3 = Node('()', parent=p2) + item = Item('c', parent=p3) res = generic_path(item) assert res == 'a.B().c' @@ -25,9 +25,9 @@ def test_generic_path(testdir): p0 = FSCollector('proj/test', config=config, session=session) p1 = FSCollector('proj/test/a', parent=p0) p2 = Node('B', parent=p1) - p3 = Node('()', parent = p2) + p3 = Node('()', parent=p2) p4 = Node('c', parent=p3) - item = Item('[1]', parent = p4) + item = Item('[1]', parent=p4) res = generic_path(item) assert res == 'test/a:B().c[1]' diff --git a/testing/test_skipping.py b/testing/test_skipping.py index 606560f4c95..7e101f88ca0 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -699,7 +699,7 @@ class TestClass(object): def test_method(self): doskip() """, - conftest = """ + conftest=""" import pytest def doskip(): pytest.skip('test') diff --git a/testing/test_terminal.py b/testing/test_terminal.py index a03d54af45e..66e909fe1e1 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -38,7 +38,7 @@ def pytest_generate_tests(metafunc): metafunc.addcall(id="verbose", funcargs={'option': Option(verbose=True)}) metafunc.addcall(id="quiet", - funcargs={'option': Option(verbose= -1)}) + funcargs={'option': Option(verbose=-1)}) metafunc.addcall(id="fulltrace", funcargs={'option': Option(fulltrace=True)}) diff --git a/tox.ini b/tox.ini index 3969897e77c..68302e315cc 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E251,E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 8f3eb6dfc7d5e9ceca694ccf2c4906bbea969faf Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 33/58] Fixed E261 flake8 errors at least two spaces before inline comment --- _pytest/_argcomplete.py | 2 +- _pytest/_code/source.py | 8 ++++---- _pytest/assertion/rewrite.py | 8 ++++---- _pytest/capture.py | 2 +- _pytest/config.py | 8 ++++---- _pytest/fixtures.py | 4 ++-- _pytest/main.py | 6 +++--- _pytest/mark.py | 2 +- _pytest/pytester.py | 8 ++++---- _pytest/python.py | 2 +- _pytest/resultlog.py | 4 ++-- _pytest/runner.py | 4 ++-- _pytest/terminal.py | 6 +++--- testing/acceptance_test.py | 6 +++--- testing/code/test_excinfo.py | 12 ++++++------ testing/code/test_source.py | 4 ++-- testing/python/collect.py | 4 ++-- testing/python/fixture.py | 2 +- testing/python/integration.py | 4 ++-- testing/test_assertion.py | 2 +- testing/test_assertrewrite.py | 2 +- testing/test_pdb.py | 8 ++++---- testing/test_resultlog.py | 2 +- testing/test_runner.py | 4 ++-- testing/test_session.py | 4 ++-- testing/test_skipping.py | 2 +- testing/test_terminal.py | 2 +- tox.ini | 2 +- 28 files changed, 62 insertions(+), 62 deletions(-) diff --git a/_pytest/_argcomplete.py b/_pytest/_argcomplete.py index 8c93e4c92ce..e865855910c 100644 --- a/_pytest/_argcomplete.py +++ b/_pytest/_argcomplete.py @@ -69,7 +69,7 @@ def __init__(self, directories=True): def __call__(self, prefix, **kwargs): """only called on non option completions""" - if os.path.sep in prefix[1:]: # + if os.path.sep in prefix[1:]: prefix_dir = len(os.path.dirname(prefix) + os.path.sep) else: prefix_dir = 0 diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index f86d96c9c54..e4c18eb3440 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -164,7 +164,7 @@ def compile(self, filename=None, mode='exec', """ if not filename or py.path.local(filename).check(file=0): if _genframe is None: - _genframe = sys._getframe(1) # the caller + _genframe = sys._getframe(1) # the caller fn, lineno = _genframe.f_code.co_filename, _genframe.f_lineno base = "<%d-codegen " % self._compilecounter self.__class__._compilecounter += 1 @@ -207,7 +207,7 @@ def compile_(source, filename=None, mode='exec', flags=generators.compiler_flag, if _ast is not None and isinstance(source, _ast.AST): # XXX should Source support having AST? return cpy_compile(source, filename, mode, flags, dont_inherit) - _genframe = sys._getframe(1) # the caller + _genframe = sys._getframe(1) # the caller s = Source(source) co = s.compile(filename, mode, flags, _genframe=_genframe) return co @@ -292,11 +292,11 @@ def readline_generator(lines): try: for _, _, (sline, _), (eline, _), _ in tokenize.generate_tokens(lambda: next(it)): if sline > len(lines): - break # End of input reached + break # End of input reached if sline > len(newlines): line = lines[sline - 1].expandtabs() if line.lstrip() and line[:offset].isspace(): - line = line[offset:] # Deindent + line = line[offset:] # Deindent newlines.append(line) for i in range(sline, eline): diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 1ae41bd1459..bce04398b2e 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -410,7 +410,7 @@ def _saferepr(obj): return repr.replace(t("\n"), t("\\n")) -from _pytest.assertion.util import format_explanation as _format_explanation # noqa +from _pytest.assertion.util import format_explanation as _format_explanation # noqa def _format_assertmsg(obj): """Format the custom assertion message given. @@ -483,7 +483,7 @@ def _call_reprcompare(ops, results, expls, each_obj): ast.Mult: "*", ast.Div: "/", ast.FloorDiv: "//", - ast.Mod: "%%", # escaped for string formatting + ast.Mod: "%%", # escaped for string formatting ast.Eq: "==", ast.NotEq: "!=", ast.Lt: "<", @@ -787,7 +787,7 @@ def visit_BoolOp(self, boolop): 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, [])) # noqa self.on_failure = fail_inner self.push_format_context() res, expl = self.visit(v) @@ -839,7 +839,7 @@ def visit_Call_35(self, call): new_kwargs.append(ast.keyword(keyword.arg, res)) if keyword.arg: arg_expls.append(keyword.arg + "=" + expl) - else: ## **args have `arg` keywords with an .arg of None + else: # **args have `arg` keywords with an .arg of None arg_expls.append("**" + expl) expl = "%s(%s)" % (func_expl, ', '.join(arg_expls)) diff --git a/_pytest/capture.py b/_pytest/capture.py index 1231ae8251f..1bcb97e9bb0 100644 --- a/_pytest/capture.py +++ b/_pytest/capture.py @@ -393,7 +393,7 @@ def resume(self): def writeorg(self, data): """ write to original file descriptor. """ if py.builtin._istext(data): - data = data.encode("utf8") # XXX use encoding of original stream + data = data.encode("utf8") # XXX use encoding of original stream os.write(self.targetfd_save, data) diff --git a/_pytest/config.py b/_pytest/config.py index 68da9c3423d..b63fc250693 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -315,7 +315,7 @@ def _set_initial_conftests(self, namespace): if i != -1: path = path[:i] anchor = current.join(path, abs=1) - if exists(anchor): # we found some file object + if exists(anchor): # we found some file object self._try_load_conftest(anchor) foundanchor = True if not foundanchor: @@ -807,7 +807,7 @@ class DropShorterLongHelpFormatter(argparse.HelpFormatter): """ def _format_action_invocation(self, action): orgstr = argparse.HelpFormatter._format_action_invocation(self, action) - if orgstr and orgstr[0] != '-': # only optional arguments + if orgstr and orgstr[0] != '-': # only optional arguments return orgstr res = getattr(action, '_formatted_action_invocation', None) if res: @@ -836,7 +836,7 @@ def _format_action_invocation(self, action): short_long[shortened] = xxoption # now short_long has been filled out to the longest with dashes # **and** we keep the right option ordering from add_argument - for option in options: # + for option in options: if len(option) == 2 or option[2] == ' ': return_list.append(option) if option[2:] == short_long.get(option.replace('-', '')): @@ -1125,7 +1125,7 @@ def addinivalue_line(self, name, line): the first line in its value. """ x = self.getini(name) assert isinstance(x, list) - x.append(line) # modifies the cached list inline + x.append(line) # modifies the cached list inline def getini(self, name): """ return configuration value from an :ref:`ini file `. If the diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 12d7bbb83a0..893043d8982 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -69,7 +69,7 @@ def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): # 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 = {} @@ -397,7 +397,7 @@ def cached_setup(self, setup, teardown=None, scope="module", extrakey=None): :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: diff --git a/_pytest/main.py b/_pytest/main.py index 74acc409d7a..86c5bc5b1cd 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -88,7 +88,7 @@ def pytest_namespace(): def pytest_configure(config): - __import__('pytest').config = config # compatibiltiy + __import__('pytest').config = config # compatibiltiy def wrap_session(config, doit): @@ -488,7 +488,7 @@ def _prunetraceback(self, excinfo): class FSCollector(Collector): def __init__(self, fspath, parent=None, config=None, session=None): - fspath = py.path.local(fspath) # xxx only for test_resultlog.py? + fspath = py.path.local(fspath) # xxx only for test_resultlog.py? name = fspath.basename if parent is not None: rel = fspath.relto(parent.fspath) @@ -561,7 +561,7 @@ class NoMatch(Exception): class Interrupted(KeyboardInterrupt): """ signals an interrupted test run. """ - __module__ = 'builtins' # for py3 + __module__ = 'builtins' # for py3 class Session(FSCollector): Interrupted = Interrupted diff --git a/_pytest/mark.py b/_pytest/mark.py index 8b40a4f6e4f..ce48dd0f116 100644 --- a/_pytest/mark.py +++ b/_pytest/mark.py @@ -313,7 +313,7 @@ def __init__(self, mark): @property def markname(self): - return self.name # for backward-compat (2.4.1 had this attr) + return self.name # for backward-compat (2.4.1 had this attr) def __eq__(self, other): return self.mark == other.mark diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 46a273dbb2e..bf139aa4c98 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -136,7 +136,7 @@ def getexecutable(name, cache={}): 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 elif popen.returncode != 0: # Handle pyenv's 127. executable = None @@ -420,7 +420,7 @@ def __init__(self, request, tmpdir_factory): self.plugins = [] self._savesyspath = (list(sys.path), list(sys.meta_path)) self._savemodulekeys = set(sys.modules) - self.chdir() # always chdir + self.chdir() # always chdir self.request.addfinalizer(self.finalize) method = self.request.config.getoption("--runpytest") if method == "inprocess": @@ -495,7 +495,7 @@ def my_totext(s, encoding="utf-8"): source_unicode = "\n".join([my_totext(line) for line in source.lines]) source = py.builtin._totext(source_unicode) - content = source.strip().encode(encoding) # + "\n" + content = source.strip().encode(encoding) # + "\n" #content = content.rstrip() + "\n" p.write(content, "wb") if ret is None: @@ -960,7 +960,7 @@ def _dump_lines(self, lines, fp): def _getpytestargs(self): # we cannot use "(sys.executable,script)" # because on windows the script is e.g. a pytest.exe - return (sys.executable, _pytest_fullpath,) # noqa + return (sys.executable, _pytest_fullpath,) # noqa def runpython(self, script): """Run a python script using sys.executable as interpreter. diff --git a/_pytest/python.py b/_pytest/python.py index 56ad8ea3e26..a7c7a9f3560 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -1574,7 +1574,7 @@ def function(self): 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) diff --git a/_pytest/resultlog.py b/_pytest/resultlog.py index 615575aa0d2..93523038adc 100644 --- a/_pytest/resultlog.py +++ b/_pytest/resultlog.py @@ -19,7 +19,7 @@ def pytest_configure(config): dirname = os.path.dirname(os.path.abspath(resultlog)) if not os.path.isdir(dirname): os.makedirs(dirname) - logfile = open(resultlog, 'w', 1) # line buffered + logfile = open(resultlog, 'w', 1) # line buffered config._resultlog = ResultLog(config, logfile) config.pluginmanager.register(config._resultlog) @@ -59,7 +59,7 @@ def generic_path(item): class ResultLog(object): def __init__(self, config, logfile): self.config = config - self.logfile = logfile # preferably line buffered + self.logfile = logfile # preferably line buffered def write_log_entry(self, testpath, lettercode, longrepr): print("%s %s" % (lettercode, testpath), file=self.logfile) diff --git a/_pytest/runner.py b/_pytest/runner.py index 21401e92b19..9d1f53a5748 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -264,7 +264,7 @@ def pytest_runtest_makereport(item, call): outcome = "failed" if call.when == "call": longrepr = item.repr_failure(excinfo) - else: # exception in setup or teardown + else: # exception in setup or teardown longrepr = item._repr_failure_py(excinfo, style=item.config.option.tbstyle) for rwhen, key, content in item._report_sections: @@ -548,7 +548,7 @@ def importorskip(modname, minversion=None): """ import warnings __tracebackhide__ = True - compile(modname, '', 'eval') # to catch syntaxerrors + compile(modname, '', 'eval') # to catch syntaxerrors should_skip = False with warnings.catch_warnings(): diff --git a/_pytest/terminal.py b/_pytest/terminal.py index 55e57b97a55..52003c5fd8a 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -371,7 +371,7 @@ def _printcollecteditems(self, items): stack = [] indent = "" for item in items: - needed_collectors = item.listchain()[1:] # strip root node + needed_collectors = item.listchain()[1:] # strip root node while stack: if stack == needed_collectors[:len(stack)]: break @@ -446,7 +446,7 @@ def _getfailureheadline(self, rep): fspath, lineno, domain = rep.location return domain else: - return "test session" # XXX? + return "test session" # XXX? def _getcrashline(self, rep): try: @@ -589,7 +589,7 @@ def build_summary_stats_line(stats): unknown_key_seen = False for key in stats.keys(): if key not in keys: - if key: # setup/teardown reports have an empty key, ignore them + if key: # setup/teardown reports have an empty key, ignore them keys.append(key) unknown_key_seen = True parts = [] diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index 9ea200b128e..e1a2956a37d 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -74,7 +74,7 @@ def pytest_unconfigure(): 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", @@ -310,7 +310,7 @@ def pytest_configure(): 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*", @@ -719,7 +719,7 @@ def test_calls_showall(self, testdir): 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 diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 2eb340fae92..a042e14bdcd 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -101,8 +101,8 @@ def setup_method(self, method): def test_traceback_entries(self): tb = self.excinfo.traceback entries = list(tb) - assert len(tb) == 4 # maybe fragile test - assert len(entries) == 4 # maybe fragile test + assert len(tb) == 4 # maybe fragile test + assert len(entries) == 4 # maybe fragile test names = ['f', 'g', 'h'] for entry in entries: try: @@ -311,9 +311,9 @@ def test_excinfo_repr(): def test_excinfo_str(): excinfo = pytest.raises(ValueError, h) s = str(excinfo) - assert s.startswith(__file__[:-9]) # pyc file and $py.class + assert s.startswith(__file__[:-9]) # pyc file and $py.class assert s.endswith("ValueError") - assert len(s.split(":")) >= 3 # on windows it's 4 + assert len(s.split(":")) >= 3 # on windows it's 4 def test_excinfo_errisinstance(): excinfo = pytest.raises(ValueError, h) @@ -341,8 +341,8 @@ def test_excinfo_no_python_sourcecode(tmpdir): excinfo = pytest.raises(ValueError, template.render, h=h) for item in excinfo.traceback: - print(item) #XXX: for some reason jinja.Template.render is printed in full - item.source # shouldnt fail + print(item) # XXX: for some reason jinja.Template.render is printed in full + item.source # shouldnt fail if item.path.basename == 'test.txt': assert str(item.source) == '{{ h()}}:' diff --git a/testing/code/test_source.py b/testing/code/test_source.py index f12b8a1a1c9..c9ce421477c 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -109,7 +109,7 @@ def test_source_strip_multiline(): def test_syntaxerror_rerepresentation(): ex = pytest.raises(SyntaxError, _pytest._code.compile, 'xyz xyz') assert ex.value.lineno == 1 - assert ex.value.offset in (4, 7) # XXX pypy/jython versus cpython? + assert ex.value.offset in (4, 7) # XXX pypy/jython versus cpython? assert ex.value.text.strip(), 'x x' def test_isparseable(): @@ -451,7 +451,7 @@ def f(x): fspath, lineno = getfslineno(f) assert fspath.basename == "test_source.py" - assert lineno == _pytest._code.getrawcode(f).co_firstlineno - 1 # see findsource + assert lineno == _pytest._code.getrawcode(f).co_firstlineno - 1 # see findsource class A(object): pass diff --git a/testing/python/collect.py b/testing/python/collect.py index eeae5bc1696..9e9753bf002 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -923,13 +923,13 @@ def hello(request): out = result.stdout.str() assert "xyz" in out assert "conftest.py:5: ValueError" in out - numentries = out.count("_ _ _") # separator for traceback entries + numentries = out.count("_ _ _") # separator for traceback entries assert numentries == 0 result = testdir.runpytest("--fulltrace", p) out = result.stdout.str() assert "conftest.py:5: ValueError" in out - numentries = out.count("_ _ _ _") # separator for traceback entries + numentries = out.count("_ _ _ _") # separator for traceback entries assert numentries > 3 def test_traceback_error_during_import(self, testdir): diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 8d1d67959aa..33fa4ba967f 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -44,7 +44,7 @@ def xyzsomething(request): def test_func(some): pass """) - result = testdir.runpytest() # "--collect-only") + result = testdir.runpytest() # "--collect-only") assert result.ret != 0 result.stdout.fnmatch_lines([ "*def test_func(some)*", diff --git a/testing/python/integration.py b/testing/python/integration.py index c346b93be85..6acc3de7ca2 100644 --- a/testing/python/integration.py +++ b/testing/python/integration.py @@ -4,7 +4,7 @@ class TestOEJSKITSpecials(object): - def test_funcarg_non_pycollectobj(self, testdir): # rough jstests usage + def test_funcarg_non_pycollectobj(self, testdir): # rough jstests usage testdir.makeconftest(""" import pytest def pytest_pycollect_makeitem(collector, name, obj): @@ -30,7 +30,7 @@ class MyClass(object): pytest._fillfuncargs(clscol) assert clscol.funcargs['arg1'] == 42 - def test_autouse_fixture(self, testdir): # rough jstests usage + def test_autouse_fixture(self, testdir): # rough jstests usage testdir.makeconftest(""" import pytest def pytest_pycollect_makeitem(collector, name, obj): diff --git a/testing/test_assertion.py b/testing/test_assertion.py index 08600654575..c6af5c1cc9d 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -831,7 +831,7 @@ def test_onefails(): "*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 *====", diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 73beaf02aac..66af5414e85 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -401,7 +401,7 @@ class X(object): 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""" diff --git a/testing/test_pdb.py b/testing/test_pdb.py index 5429dd5d48e..2445c807cb0 100644 --- a/testing/test_pdb.py +++ b/testing/test_pdb.py @@ -10,7 +10,7 @@ def runpdb_and_get_report(testdir, source): p = testdir.makepyfile(source) result = testdir.runpytest_inprocess("--pdb", p) reports = result.reprec.getreports("pytest_runtest_logreport") - assert len(reports) == 3, reports # setup/call/teardown + assert len(reports) == 3, reports # setup/call/teardown return reports[1] @@ -216,7 +216,7 @@ def test_1(): rest = child.read().decode("utf-8") assert "1 failed" in rest assert "def test_1" in rest - assert "hello17" in rest # out is captured + assert "hello17" in rest # out is captured self.flush(child) def test_pdb_set_trace_interception(self, testdir): @@ -309,8 +309,8 @@ def test_1(): rest = child.read().decode("utf8") assert "1 failed" in rest assert "def test_1" in rest - assert "hello17" in rest # out is captured - assert "hello18" in rest # out is captured + assert "hello17" in rest # out is captured + assert "hello18" in rest # out is captured self.flush(child) def test_pdb_used_outside_test(self, testdir): diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py index 7bbaa458cd9..c5416fa0309 100644 --- a/testing/test_resultlog.py +++ b/testing/test_resultlog.py @@ -144,7 +144,7 @@ def test_internal_exception(self, style): assert entry_lines[0].startswith('! ') if style != "native": - assert os.path.basename(__file__)[:-9] in entry_lines[0] #.pyc/class + assert os.path.basename(__file__)[:-9] in entry_lines[0] # .pyc/class assert entry_lines[-1][0] == ' ' assert 'ValueError' in entry diff --git a/testing/test_runner.py b/testing/test_runner.py index efaab1993c4..5fb96d008fa 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -31,7 +31,7 @@ def test_setup_fails_and_failure_is_cached(self, testdir): def setup_module(mod): raise ValueError(42) def test_func(): pass - """) # noqa + """) # noqa ss = runner.SetupState() pytest.raises(ValueError, lambda: ss.prepare(item)) pytest.raises(ValueError, lambda: ss.prepare(item)) @@ -131,7 +131,7 @@ def test_func(): #assert rep.skipped.location.lineno == 3 #assert rep.skipped.location.lineno == 3 assert len(reports) == 2 - assert reports[1].passed # teardown + assert reports[1].passed # teardown def test_failure_in_setup_function(self, testdir): reports = testdir.runitem(""" diff --git a/testing/test_session.py b/testing/test_session.py index d08f7b3e25f..1cb0bb285f6 100644 --- a/testing/test_session.py +++ b/testing/test_session.py @@ -117,7 +117,7 @@ def test_implicit_bad_repr1(self): passed, skipped, failed = reprec.listoutcomes() assert len(failed) == 1 out = failed[0].longrepr.reprcrash.message - assert out.find("""[Exception("Ha Ha fooled you, I'm a broken repr().") raised in repr()]""") != -1 #' + assert out.find("""[Exception("Ha Ha fooled you, I'm a broken repr().") raised in repr()]""") != -1 # ' def test_skip_file_by_conftest(self, testdir): testdir.makepyfile(conftest=""" @@ -186,7 +186,7 @@ class TestY(TestX): started = reprec.getcalls("pytest_collectstart") finished = reprec.getreports("pytest_collectreport") assert len(started) == len(finished) - assert len(started) == 7 # XXX extra TopCollector + assert len(started) == 7 # XXX extra TopCollector colfail = [x for x in finished if x.failed] assert len(colfail) == 1 diff --git a/testing/test_skipping.py b/testing/test_skipping.py index 7e101f88ca0..cfd1af684e6 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -589,7 +589,7 @@ def test_skipif_conditional(self, testdir): @pytest.mark.skipif("hasattr(os, 'sep')") def test_func(): pass - """) # noqa + """) # noqa x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item)) assert x.value.msg == "condition: hasattr(os, 'sep')" diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 66e909fe1e1..5f554f7f6c3 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -318,7 +318,7 @@ def test_repr_python_version(monkeypatch): py.std.sys.version_info = x = (2, 3) assert repr_pythonversion() == str(x) finally: - monkeypatch.undo() # do this early as pytest can get confused + monkeypatch.undo() # do this early as pytest can get confused class TestFixtureReporting(object): def test_setup_fixture_error(self, testdir): diff --git a/tox.ini b/tox.ini index 68302e315cc..768439fe81c 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E261,E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From eae8b41b07013744774909beeb7bcf7ef40c6961 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 34/58] Fixed E262 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit inline comment should start with ‘# ‘ --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 768439fe81c..558a678a4fc 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E262,E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 195a81652239142f715d8d765b83429240e19c70 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 35/58] Fixed E265 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit block comment should start with ‘# ‘ --- _pytest/_code/code.py | 12 +++++----- _pytest/_code/source.py | 2 +- _pytest/cacheprovider.py | 2 +- _pytest/capture.py | 2 +- _pytest/compat.py | 2 +- _pytest/config.py | 4 ++-- _pytest/main.py | 4 ++-- _pytest/nose.py | 4 ++-- _pytest/pytester.py | 10 ++++---- _pytest/python.py | 6 ++--- _pytest/runner.py | 2 +- _pytest/skipping.py | 6 ++--- _pytest/terminal.py | 8 +++---- _pytest/tmpdir.py | 2 +- testing/acceptance_test.py | 6 ++--- testing/code/test_excinfo.py | 10 ++++---- testing/code/test_source.py | 14 +++++------ testing/python/fixture.py | 2 +- testing/test_assertion.py | 2 +- testing/test_capture.py | 2 +- testing/test_collection.py | 6 ++--- testing/test_conftest.py | 2 +- testing/test_doctest.py | 2 +- testing/test_helpconfig.py | 2 +- testing/test_pdb.py | 4 ++-- testing/test_pluginmanager.py | 6 ++--- testing/test_resultlog.py | 2 +- testing/test_runner.py | 44 +++++++++++++++++------------------ testing/test_session.py | 10 ++++---- testing/test_skipping.py | 6 ++--- testing/test_terminal.py | 6 ++--- tox.ini | 2 +- 32 files changed, 97 insertions(+), 97 deletions(-) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 2f5e5607981..92d7d5b0c0f 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -330,9 +330,9 @@ def recursionindex(self): # id for the code.raw is needed to work around # the strange metaprogramming in the decorator lib from pypi # which generates code objects that have hash/value equality - #XXX needs a test + # XXX needs a test key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno - #print "checking for recursion at", key + # print "checking for recursion at", key l = cache.setdefault(key, []) if l: f = entry.frame @@ -546,10 +546,10 @@ def repr_locals(self, locals): # _repr() function, which is only reprlib.Repr in # disguise, so is very configurable. str_repr = self._saferepr(value) - #if len(str_repr) < 70 or not isinstance(value, + # if len(str_repr) < 70 or not isinstance(value, # (list, tuple, dict)): lines.append("%-10s = %s" % (name, str_repr)) - #else: + # else: # self._line("%-10s =\\" % (name,)) # # XXX # py.std.pprint.pprint(value, stream=self.excinfowriter) @@ -797,7 +797,7 @@ def toterminal(self, tw): for line in self.lines: red = line.startswith("E ") tw.line(line, bold=True, red=red) - #tw.line("") + # tw.line("") return if self.reprfuncargs: self.reprfuncargs.toterminal(tw) @@ -805,7 +805,7 @@ def toterminal(self, tw): red = line.startswith("E ") tw.line(line, bold=True, red=red) if self.reprlocals: - #tw.sep(self.localssep, "Locals") + # tw.sep(self.localssep, "Locals") tw.line("") self.reprlocals.toterminal(tw) if self.reprfileloc: diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index e4c18eb3440..08b9c414d87 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -143,7 +143,7 @@ def isparseable(self, deindent=True): else: source = str(self) try: - #compile(source+'\n', "x", "exec") + # compile(source+'\n', "x", "exec") syntax_checker(source + '\n') except KeyboardInterrupt: raise diff --git a/_pytest/cacheprovider.py b/_pytest/cacheprovider.py index de3fa458941..4573fd46275 100755 --- a/_pytest/cacheprovider.py +++ b/_pytest/cacheprovider.py @@ -236,7 +236,7 @@ def cacheshow(config, session): if ddir.isdir() and ddir.listdir(): tw.sep("-", "cache directories") for p in sorted(basedir.join("d").visit()): - #if p.check(dir=1): + # if p.check(dir=1): # print("%s/" % p.relto(basedir)) if p.isfile(): key = p.relto(basedir) diff --git a/_pytest/capture.py b/_pytest/capture.py index 1bcb97e9bb0..56e03bba8f1 100644 --- a/_pytest/capture.py +++ b/_pytest/capture.py @@ -134,7 +134,7 @@ def pytest_runtest_call(self, item): self.resumecapture() self.activate_funcargs(item) yield - #self.deactivate_funcargs() called from suspendcapture() + # self.deactivate_funcargs() called from suspendcapture() self.suspendcapture_item(item, "call") @pytest.hookimpl(hookwrapper=True) diff --git a/_pytest/compat.py b/_pytest/compat.py index d89c2922f6e..4fac998e865 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -85,7 +85,7 @@ def num_mock_patch_args(function): def getfuncargnames(function, startindex=None): # XXX merge with main.py's varnames - #assert not isclass(function) + # assert not isclass(function) realfunction = function while hasattr(realfunction, "__wrapped__"): realfunction = realfunction.__wrapped__ diff --git a/_pytest/config.py b/_pytest/config.py index b63fc250693..7285d3d0a1f 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -693,7 +693,7 @@ def attrs(self): if self._attrs.get('help'): a = self._attrs['help'] a = a.replace('%default', '%(default)s') - #a = a.replace('%prog', '%(prog)s') + # a = a.replace('%prog', '%(prog)s') self._attrs['help'] = a return self._attrs @@ -1361,7 +1361,7 @@ def setns(obj, dic): else: setattr(obj, name, value) obj.__all__.append(name) - #if obj != pytest: + # if obj != pytest: # pytest.__all__.append(name) setattr(pytest, name, value) diff --git a/_pytest/main.py b/_pytest/main.py index 86c5bc5b1cd..5460b537e5b 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -32,11 +32,11 @@ def pytest_addoption(parser): type="args", default=['.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv']) parser.addini("testpaths", "directories to search for tests when no files or directories are given in the command line.", type="args", default=[]) - #parser.addini("dirpatterns", + # parser.addini("dirpatterns", # "patterns specifying possible locations of test files", # type="linelist", default=["**/test_*.txt", # "**/test_*.py", "**/*_test.py"] - #) + # ) group = parser.getgroup("general", "running and selection options") group._addoption('-x', '--exitfirst', action="store_const", dest="maxfail", const=1, diff --git a/_pytest/nose.py b/_pytest/nose.py index 9d4fc0b6e15..f21e3967342 100644 --- a/_pytest/nose.py +++ b/_pytest/nose.py @@ -38,14 +38,14 @@ def pytest_runtest_setup(item): if not call_optional(item.obj, 'setup'): # call module level setup if there is no object level one call_optional(item.parent.obj, 'setup') - #XXX this implies we only call teardown when setup worked + # XXX this implies we only call teardown when setup worked item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item) def teardown_nose(item): if is_potential_nosetest(item): if not call_optional(item.obj, 'teardown'): call_optional(item.parent.obj, 'teardown') - #if hasattr(item.parent, '_nosegensetup'): + # if hasattr(item.parent, '_nosegensetup'): # #call_optional(item._nosegensetup, 'teardown') # del item.parent._nosegensetup diff --git a/_pytest/pytester.py b/_pytest/pytester.py index bf139aa4c98..0ea4d6c4453 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -496,7 +496,7 @@ def my_totext(s, encoding="utf-8"): source_unicode = "\n".join([my_totext(line) for line in source.lines]) source = py.builtin._totext(source_unicode) content = source.strip().encode(encoding) # + "\n" - #content = content.rstrip() + "\n" + # content = content.rstrip() + "\n" p.write(content, "wb") if ret is None: ret = p @@ -779,11 +779,11 @@ def _ensure_basetemp(self, args): args = [str(x) for x in args] for x in args: if str(x).startswith('--basetemp'): - #print ("basedtemp exists: %s" %(args,)) + # print("basedtemp exists: %s" %(args,)) break else: args.append("--basetemp=%s" % self.tmpdir.dirpath('basetemp')) - #print ("added basetemp: %s" %(args,)) + # print("added basetemp: %s" %(args,)) return args def parseconfig(self, *args): @@ -989,10 +989,10 @@ def runpytest_subprocess(self, *args, **kwargs): p = py.path.local.make_numbered_dir(prefix="runpytest-", keep=None, rootdir=self.tmpdir) args = ('--basetemp=%s' % p, ) + args - #for x in args: + # for x in args: # if '--confcutdir' in str(x): # break - #else: + # else: # pass # args = ('--confcutdir=.',) + args plugins = [x for x in self.plugins if isinstance(x, str)] diff --git a/_pytest/python.py b/_pytest/python.py index a7c7a9f3560..9b6c5a39b96 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -320,7 +320,7 @@ def collect(self): 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) @@ -563,7 +563,7 @@ def _prunetraceback(self, excinfo): if ntraceback == traceback: ntraceback = ntraceback.cut(path=path) if ntraceback == traceback: - #ntraceback = ntraceback.cut(excludepath=cutdir2) + # ntraceback = ntraceback.cut(excludepath=cutdir2) ntraceback = ntraceback.filter(filter_traceback) if not ntraceback: ntraceback = traceback @@ -1213,7 +1213,7 @@ def raises(expected_exception, *args, **kwargs): 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 = _pytest._code.Source(code).compile() py.builtin.exec_(code, frame.f_globals, loc) diff --git a/_pytest/runner.py b/_pytest/runner.py index 9d1f53a5748..8c101557b7a 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -386,7 +386,7 @@ def addfinalizer(self, finalizer, colitem): """ assert colitem and not isinstance(colitem, tuple) assert py.builtin.callable(finalizer) - #assert colitem in self.stack # some unit tests don't setup stack :/ + # assert colitem in self.stack # some unit tests don't setup stack :/ self._finalizers.setdefault(colitem, []).append(finalizer) def _pop_and_teardown(self): diff --git a/_pytest/skipping.py b/_pytest/skipping.py index 2aafa141835..56b36166044 100644 --- a/_pytest/skipping.py +++ b/_pytest/skipping.py @@ -280,7 +280,7 @@ def pytest_report_teststatus(report): def pytest_terminal_summary(terminalreporter): tr = terminalreporter if not tr.reportchars: - #for name in "xfailed skipped failed xpassed": + # for name in "xfailed skipped failed xpassed": # if not tr.stats.get(name, 0): # tr.write_line("HINT: use '-r' option to see extra " # "summary info about tests") @@ -364,14 +364,14 @@ def show_skipped(terminalreporter, lines): tr = terminalreporter skipped = tr.stats.get('skipped', []) if skipped: - #if not tr.hasopt('skipped'): + # if not tr.hasopt('skipped'): # tr.write_line( # "%d skipped tests, specify -rs for more info" % # len(skipped)) # return fskips = folded_skips(skipped) if fskips: - #tr.write_sep("_", "skipped test summary") + # tr.write_sep("_", "skipped test summary") for num, fspath, lineno, reason in fskips: if reason.startswith("Skipped: "): reason = reason[9:] diff --git a/_pytest/terminal.py b/_pytest/terminal.py index 52003c5fd8a..f0bf996f31c 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -248,7 +248,7 @@ def pytest_runtest_logreport(self, report): line = self._locationline(rep.nodeid, *rep.location) if not hasattr(rep, 'node'): self.write_ensure_prefix(line, word, **markup) - #self._tw.write(word, **markup) + # self._tw.write(word, **markup) else: self.ensure_newline() if hasattr(rep, 'node'): @@ -269,7 +269,7 @@ def pytest_collectreport(self, report): items = [x for x in report.result if isinstance(x, pytest.Item)] self._numcollected += len(items) if self.isatty: - #self.write_fspath_result(report.nodeid, 'E') + # self.write_fspath_result(report.nodeid, 'E') self.report_collect() def report_collect(self, final=False): @@ -347,7 +347,7 @@ def pytest_collection_finish(self, session): return 0 if not self.showheader: return - #for i, testarg in enumerate(self.config.args): + # for i, testarg in enumerate(self.config.args): # self.write_line("test path %d: %s" %(i+1, testarg)) def _printcollecteditems(self, items): @@ -378,7 +378,7 @@ def _printcollecteditems(self, items): stack.pop() for col in needed_collectors[len(stack):]: stack.append(col) - #if col.name == "()": + # if col.name == "()": # continue indent = (len(stack) - 1) * " " self._tw.line("%s%s" % (indent, col)) diff --git a/_pytest/tmpdir.py b/_pytest/tmpdir.py index 78392e378b3..da1b032237a 100644 --- a/_pytest/tmpdir.py +++ b/_pytest/tmpdir.py @@ -25,7 +25,7 @@ def ensuretemp(self, string, dir=1): provides an empty unique-per-test-invocation directory and is guaranteed to be empty. """ - #py.log._apiwarn(">1.1", "use tmpdir function argument") + # py.log._apiwarn(">1.1", "use tmpdir function argument") return self.getbasetemp().ensure(string, dir=dir) def mktemp(self, basename, numbered=True): diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index e1a2956a37d..ea8ef747eb7 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -119,7 +119,7 @@ def test_this(): 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", "ImportError while importing test module*", "*No module named *does_not_work*", ]) @@ -440,8 +440,8 @@ def test_import_star_py_dot_test(self, testdir): #collect #cmdline #Item - #assert collect.Item is Item - #assert collect.Collector is Collector + # assert collect.Item is Item + # assert collect.Collector is Collector main skip xfail diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index a042e14bdcd..b73ef5232b0 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -72,9 +72,9 @@ def f(): l = list(excinfo.traceback) foundlinenumbers = [x.lineno for x in l] assert foundlinenumbers == linenumbers - #for x in info: + # for x in info: # print "%s:%d %s" %(x.path.relto(root), x.lineno, x.statement) - #xxx + # xxx # testchain for getentries test below def f(): @@ -238,7 +238,7 @@ def f(n): assert recindex is None def test_traceback_messy_recursion(self): - #XXX: simplified locally testable version + # XXX: simplified locally testable version decorator = pytest.importorskip('decorator').decorator def log(f, *k, **kw): @@ -331,7 +331,7 @@ def test_excinfo_no_sourcecode(): assert s == " File '':1 in \n ???\n" def test_excinfo_no_python_sourcecode(tmpdir): - #XXX: simplified locally testable version + # XXX: simplified locally testable version tmpdir.join('test.txt').write("{{ h()}}:") jinja2 = pytest.importorskip('jinja2') @@ -575,7 +575,7 @@ def func1(): loc = repr_entry.reprfileloc assert loc.path == mod.__file__ assert loc.lineno == 3 - #assert loc.message == "ValueError: hello" + # assert loc.message == "ValueError: hello" def test_repr_tracebackentry_lines2(self, importasmod): mod = importasmod(""" diff --git a/testing/code/test_source.py b/testing/code/test_source.py index c9ce421477c..a089db054a7 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -181,16 +181,16 @@ def f(): assert 'ValueError' in source2 def test_getstatement(self): - #print str(self.source) + # print str(self.source) ass = str(self.source[1:]) for i in range(1, 4): - #print "trying start in line %r" % self.source[i] + # print "trying start in line %r" % self.source[i] s = self.source.getstatement(i) #x = s.deindent() assert str(s) == ass def test_getstatementrange_triple_quoted(self): - #print str(self.source) + # print str(self.source) source = Source("""hello(''' ''')""") s = source.getstatement(0) @@ -211,12 +211,12 @@ def test_getstatementrange_within_constructs(self): """) assert len(source) == 7 # check all lineno's that could occur in a traceback - #assert source.getstatementrange(0) == (0, 7) - #assert source.getstatementrange(1) == (1, 5) + # assert source.getstatementrange(0) == (0, 7) + # assert source.getstatementrange(1) == (1, 5) assert source.getstatementrange(2) == (2, 3) assert source.getstatementrange(3) == (3, 4) assert source.getstatementrange(4) == (4, 5) - #assert source.getstatementrange(5) == (0, 7) + # assert source.getstatementrange(5) == (0, 7) assert source.getstatementrange(6) == (6, 7) def test_getstatementrange_bug(self): @@ -283,7 +283,7 @@ def test_compile_and_getsource(self): excinfo = pytest.raises(AssertionError, "f(6)") frame = excinfo.traceback[-1].frame stmt = frame.code.fullsource.getstatement(frame.lineno) - #print "block", str(block) + # print "block", str(block) assert str(stmt).strip().startswith('assert') @pytest.mark.parametrize('name', ['', None, 'my']) diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 33fa4ba967f..af8e6a77ac2 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -2373,7 +2373,7 @@ def test_2(arg): l = reprec.getcalls("pytest_runtest_call")[0].item.module.l import pprint pprint.pprint(l) - #assert len(l) == 6 + # assert len(l) == 6 assert l[0] == l[1] == 1 assert l[2] == "fin1" assert l[3] == l[4] == 2 diff --git a/testing/test_assertion.py b/testing/test_assertion.py index c6af5c1cc9d..e5eff7e03b5 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -822,7 +822,7 @@ def test_onefails(): "", "*test_*.py:6: ", "_ _ _ *", - #"", + # "", " def f(x):", "> assert x == g()", "E assert 3 == 2", diff --git a/testing/test_capture.py b/testing/test_capture.py index cb9431141ce..4b495ed2ccd 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -234,7 +234,7 @@ def test_func1(): "setup func1*", "in func1*", "teardown func1*", - #"*1 fixture failure*" + # "*1 fixture failure*" ]) def test_teardown_capturing_final(self, testdir): diff --git a/testing/test_collection.py b/testing/test_collection.py index ce5e9990843..49bfc2a5648 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -362,9 +362,9 @@ def test_collect_topdir(self, testdir): 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 diff --git a/testing/test_conftest.py b/testing/test_conftest.py index dd696fe5b06..e7034179f27 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -43,7 +43,7 @@ def test_immediate_initialiation_and_incremental_are_the_same(self, basedir): 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')) diff --git a/testing/test_doctest.py b/testing/test_doctest.py index ec3f8ba7ae1..dfbab28cca3 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -19,7 +19,7 @@ def test_collect_testtextfile(self, testdir): """) 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], DoctestItem) diff --git a/testing/test_helpconfig.py b/testing/test_helpconfig.py index 41fa953adde..3d216b3bc6c 100644 --- a/testing/test_helpconfig.py +++ b/testing/test_helpconfig.py @@ -5,7 +5,7 @@ def test_version(testdir, pytestconfig): result = testdir.runpytest("--version") assert result.ret == 0 - #p = py.path.local(py.__file__).dirpath() + # p = py.path.local(py.__file__).dirpath() result.stderr.fnmatch_lines([ '*pytest*%s*imported from*' % (pytest.__version__, ) ]) diff --git a/testing/test_pdb.py b/testing/test_pdb.py index 2445c807cb0..b6543b05365 100644 --- a/testing/test_pdb.py +++ b/testing/test_pdb.py @@ -181,7 +181,7 @@ def test_pdb_interaction_on_collection_issue181(self, testdir): xxx """) child = testdir.spawn_pytest("--pdb %s" % p1) - #child.expect(".*import pytest.*") + # child.expect(".*import pytest.*") child.expect("(Pdb)") child.sendeof() child.expect("1 error") @@ -194,7 +194,7 @@ def pytest_runtest_protocol(): """) p1 = testdir.makepyfile("def test_func(): pass") child = testdir.spawn_pytest("--pdb %s" % p1) - #child.expect(".*import pytest.*") + # child.expect(".*import pytest.*") child.expect("(Pdb)") child.sendeof() self.flush(child) diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index 6428bf9d903..d1e1ff2de95 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -31,7 +31,7 @@ def pytest_myhook(xyz): pm.hook.pytest_addhooks.call_historic( kwargs=dict(pluginmanager=config.pluginmanager)) config.pluginmanager._importconftest(conf) - #print(config.pluginmanager.get_plugins()) + # print(config.pluginmanager.get_plugins()) res = config.hook.pytest_myhook(xyz=10) assert res == [11] @@ -232,7 +232,7 @@ def test_register_imported_modules(self): assert mod in l pytest.raises(ValueError, "pm.register(mod)") pytest.raises(ValueError, lambda: pm.register(mod)) - #assert not pm.is_registered(mod2) + # assert not pm.is_registered(mod2) assert pm.get_plugins() == l def test_canonical_import(self, monkeypatch): @@ -259,7 +259,7 @@ def test_consider_module_import_module(self, testdir): mod.pytest_plugins = "pytest_a" aplugin = testdir.makepyfile(pytest_a="#") reprec = testdir.make_hook_recorder(pytestpm) - #syspath.prepend(aplugin.dirpath()) + # syspath.prepend(aplugin.dirpath()) py.std.sys.path.insert(0, str(aplugin.dirpath())) pytestpm.consider_module(mod) call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name) diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py index c5416fa0309..86ae5ab392a 100644 --- a/testing/test_resultlog.py +++ b/testing/test_resultlog.py @@ -14,7 +14,7 @@ def test_generic_path(testdir): config = testdir.parseconfig() session = Session(config) p1 = Node('a', config=config, session=session) - #assert p1.fspath is None + # assert p1.fspath is None p2 = Node('B', parent=p1) p3 = Node('()', parent=p2) item = Item('c', parent=p3) diff --git a/testing/test_runner.py b/testing/test_runner.py index 5fb96d008fa..26e6816cb20 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -94,7 +94,7 @@ def test_func(): assert rep.failed assert rep.when == "call" assert rep.outcome == "failed" - #assert isinstance(rep.longrepr, ReprExceptionInfo) + # assert isinstance(rep.longrepr, ReprExceptionInfo) def test_skipfunction(self, testdir): reports = testdir.runitem(""" @@ -107,12 +107,12 @@ def test_func(): assert not rep.passed assert rep.skipped assert rep.outcome == "skipped" - #assert rep.skipped.when == "call" - #assert rep.skipped.when == "call" - #assert rep.skipped == "%sreason == "hello" - #assert rep.skipped.location.lineno == 3 - #assert rep.skipped.location.path - #assert not rep.skipped.failurerepr + # assert rep.skipped.when == "call" + # assert rep.skipped.when == "call" + # assert rep.skipped == "%sreason == "hello" + # assert rep.skipped.location.lineno == 3 + # assert rep.skipped.location.path + # assert not rep.skipped.failurerepr def test_skip_in_setup_function(self, testdir): reports = testdir.runitem(""" @@ -127,9 +127,9 @@ def test_func(): assert not rep.failed assert not rep.passed assert rep.skipped - #assert rep.skipped.reason == "hello" - #assert rep.skipped.location.lineno == 3 - #assert rep.skipped.location.lineno == 3 + # assert rep.skipped.reason == "hello" + # assert rep.skipped.location.lineno == 3 + # assert rep.skipped.location.lineno == 3 assert len(reports) == 2 assert reports[1].passed # teardown @@ -163,8 +163,8 @@ def test_func(): assert not rep.passed assert rep.failed assert rep.when == "teardown" - #assert rep.longrepr.reprcrash.lineno == 3 - #assert rep.longrepr.reprtraceback.reprentries + # assert rep.longrepr.reprcrash.lineno == 3 + # assert rep.longrepr.reprtraceback.reprentries def test_custom_failure_repr(self, testdir): testdir.makepyfile(conftest=""" @@ -182,10 +182,10 @@ def test_func(): assert not rep.skipped assert not rep.passed assert rep.failed - #assert rep.outcome.when == "call" - #assert rep.failed.where.lineno == 3 - #assert rep.failed.where.path.basename == "test_func.py" - #assert rep.failed.failurerepr == "hello" + # assert rep.outcome.when == "call" + # assert rep.failed.where.lineno == 3 + # assert rep.failed.where.path.basename == "test_func.py" + # assert rep.failed.failurerepr == "hello" def test_teardown_final_returncode(self, testdir): rec = testdir.inline_runsource(""" @@ -287,10 +287,10 @@ def test_func(): assert not rep.skipped assert not rep.passed assert rep.failed - #assert rep.outcome.when == "setup" - #assert rep.outcome.where.lineno == 3 - #assert rep.outcome.where.path.basename == "test_func.py" - #assert instanace(rep.failed.failurerepr, PythonFailureRepr) + # assert rep.outcome.when == "setup" + # assert rep.outcome.where.lineno == 3 + # assert rep.outcome.where.path.basename == "test_func.py" + # assert instanace(rep.failed.failurerepr, PythonFailureRepr) def test_systemexit_does_not_bail_out(self, testdir): try: @@ -540,8 +540,8 @@ def f(): try: sys = importorskip("sys") # noqa assert sys == py.std.sys - #path = pytest.importorskip("os.path") - #assert path == py.std.os.path + # path = pytest.importorskip("os.path") + # assert path == py.std.os.path excinfo = pytest.raises(pytest.skip.Exception, f) path = py.path.local(excinfo.getrepr().reprcrash.path) # check that importorskip reports the actual call diff --git a/testing/test_session.py b/testing/test_session.py index 1cb0bb285f6..53f23df3c1d 100644 --- a/testing/test_session.py +++ b/testing/test_session.py @@ -27,9 +27,9 @@ def test_two(self, someargs): itemstarted = reprec.getcalls("pytest_itemcollected") assert len(itemstarted) == 4 # XXX check for failing funcarg setup - #colreports = reprec.getcalls("pytest_collectreport") - #assert len(colreports) == 4 - #assert colreports[1].report.failed + # colreports = reprec.getcalls("pytest_collectreport") + # assert len(colreports) == 4 + # assert colreports[1].report.failed def test_nested_import_error(self, testdir): tfile = testdir.makepyfile(""" @@ -211,9 +211,9 @@ def test_plugin_specify(testdir): pytest.raises(ImportError, """ testdir.parseconfig("-p", "nqweotexistent") """) - #pytest.raises(ImportError, + # pytest.raises(ImportError, # "config.do_configure(config)" - #) + # ) def test_plugin_already_exists(testdir): config = testdir.parseconfig("-p", "terminal") diff --git a/testing/test_skipping.py b/testing/test_skipping.py index cfd1af684e6..3c92105d699 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -207,9 +207,9 @@ def test_this(): assert 0 """) testdir.runpytest(p, '-v') - #result.stdout.fnmatch_lines([ + # result.stdout.fnmatch_lines([ # "*HINT*use*-r*" - #]) + # ]) def test_xfail_not_run_xfail_reporting(self, testdir): p = testdir.makepyfile(test_one=""" @@ -640,7 +640,7 @@ def test_this(): """) result = testdir.runpytest(p, '-v') result.stdout.fnmatch_lines([ - #"*HINT*use*-r*", + # "*HINT*use*-r*", "*1 skipped*", ]) diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 5f554f7f6c3..f9344ca308a 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -264,13 +264,13 @@ def test_method(self): pass """) result = testdir.runpytest("--collect-only", p) - #assert stderr.startswith("inserting into sys.path") + # assert stderr.startswith("inserting into sys.path") assert result.ret == 0 result.stdout.fnmatch_lines([ "*", "* ", "* ", - #"* ", + # "* ", "* ", ]) @@ -485,7 +485,7 @@ def test_showlocals(): """) result = testdir.runpytest(p1, '-l') result.stdout.fnmatch_lines([ - #"_ _ * Locals *", + # "_ _ * Locals *", "x* = 3", "y* = 'xxxxxx*" ]) diff --git a/tox.ini b/tox.ini index 558a678a4fc..aa525b1fdba 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E265,E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From c9a081d1a3344787bb30f9526036922fd7fcad1d Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 36/58] Fixed E271 flake8 errors multiple spaces after keyword --- _pytest/compat.py | 4 ++-- testing/test_conftest.py | 6 +++--- testing/test_parseopt.py | 2 +- tox.ini | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/_pytest/compat.py b/_pytest/compat.py index 4fac998e865..5c364c18ffc 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -10,7 +10,7 @@ import py -import _pytest +import _pytest @@ -112,7 +112,7 @@ def getfuncargnames(function, startindex=None): -if sys.version_info[:2] == (2, 6): +if sys.version_info[:2] == (2, 6): def isclass(object): """ Return true if the object is a class. Overrides inspect.isclass for python 2.6 because it will return True for objects which always return diff --git a/testing/test_conftest.py b/testing/test_conftest.py index e7034179f27..bbb5bd496e5 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -65,7 +65,7 @@ def test_value_access_with_confmod(self, basedir): 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") @@ -151,10 +151,10 @@ def test_setinitial_conftest_subdirs(testdir, name): conftest = PytestPluginManager() 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): diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index 3e3919a3884..104d66083d8 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -242,7 +242,7 @@ def test_drop_short_help0(self, parser, capsys): action='store_true') parser.parse([]) help = parser.optparser.format_help() - assert '--func-args, --doit foo' in help + assert '--func-args, --doit foo' in help # testing would be more helpful with all help generated def test_drop_short_help1(self, parser, capsys): diff --git a/tox.ini b/tox.ini index aa525b1fdba..75d84f28d00 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E271,E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 4730c6d99d017dacd4a0788c3f2cd2d041bc4968 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 37/58] Fixed E272 flake8 errors multiple spaces before keyword --- testing/test_config.py | 2 +- tox.ini | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/testing/test_config.py b/testing/test_config.py index 283155e6c08..b30675c04d2 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -569,7 +569,7 @@ def pytest_internalerror(self, excrepr): def test_load_initial_conftest_last_ordering(testdir): - from _pytest.config import get_config + from _pytest.config import get_config pm = get_config().pluginmanager class My(object): diff --git a/tox.ini b/tox.ini index 75d84f28d00..c2d29ffc55d 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E272,E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 9bad9b53d8a7399cb2f72f9e5cf399488a065a3d Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 38/58] Fixed E293 flake8 errors --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index c2d29ffc55d..d6c2938e865 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E293,E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 17a21d540bb7d5e8fc2da115b29e6f5c0c966b43 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 39/58] Fixed E301 flake8 errors expected 1 blank line, found 0 --- _pytest/_argcomplete.py | 1 + _pytest/_code/code.py | 2 ++ _pytest/_code/source.py | 1 + _pytest/cacheprovider.py | 1 + _pytest/capture.py | 1 + _pytest/config.py | 5 +++++ _pytest/fixtures.py | 3 +++ _pytest/mark.py | 4 ++++ _pytest/pytester.py | 2 ++ _pytest/python.py | 3 +++ _pytest/runner.py | 7 +++++++ _pytest/terminal.py | 1 + testing/acceptance_test.py | 1 + testing/code/test_excinfo.py | 5 +++++ testing/code/test_source.py | 1 + testing/python/metafunc.py | 1 + testing/test_argcomplete.py | 1 + testing/test_pytester.py | 1 + testing/test_terminal.py | 1 + tox.ini | 2 +- 20 files changed, 43 insertions(+), 1 deletion(-) diff --git a/_pytest/_argcomplete.py b/_pytest/_argcomplete.py index e865855910c..cb93baa60ca 100644 --- a/_pytest/_argcomplete.py +++ b/_pytest/_argcomplete.py @@ -64,6 +64,7 @@ class FastFilesCompleter: 'Fast file completer class' + def __init__(self, directories=True): self.directories = directories diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index 92d7d5b0c0f..e921ceb3bb4 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -18,6 +18,7 @@ class Code(object): """ wrapper around Python code objects """ + def __init__(self, rawcode): if not hasattr(rawcode, "co_filename"): rawcode = getrawcode(rawcode) @@ -260,6 +261,7 @@ class Traceback(list): access to Traceback entries. """ Entry = TracebackEntry + def __init__(self, tb, excinfo=None): """ initialize from given python traceback object and ExceptionInfo """ self._excinfo = excinfo diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 08b9c414d87..bf83814fac5 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -19,6 +19,7 @@ class Source(object): possibly deindenting it. """ _compilecounter = 0 + def __init__(self, *parts, **kwargs): self.lines = lines = [] de = kwargs.get('deindent', True) diff --git a/_pytest/cacheprovider.py b/_pytest/cacheprovider.py index 4573fd46275..31cfb2a294d 100755 --- a/_pytest/cacheprovider.py +++ b/_pytest/cacheprovider.py @@ -89,6 +89,7 @@ def set(self, key, value): class LFPlugin: """ Plugin which implements the --lf (run last-failing) option """ + def __init__(self, config): self.config = config active_keys = 'lf', 'failedfirst' diff --git a/_pytest/capture.py b/_pytest/capture.py index 56e03bba8f1..ea88e08f2a1 100644 --- a/_pytest/capture.py +++ b/_pytest/capture.py @@ -238,6 +238,7 @@ def safe_text_dupfile(f, mode, default_encoding="UTF8"): class EncodedFile(object): errors = "strict" # possibly needed by py3 code (issue555) + def __init__(self, buffer, encoding): self.buffer = buffer self.encoding = encoding diff --git a/_pytest/config.py b/_pytest/config.py index 7285d3d0a1f..2b8ba0b6cb2 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -176,6 +176,7 @@ class PytestPluginManager(PluginManager): ``pytest_plugins`` global variables found in plugins being loaded; * ``conftest.py`` loading during start-up; """ + def __init__(self): super(PytestPluginManager, self).__init__("pytest", implprefix="pytest_") self._conftest_plugins = set() @@ -805,6 +806,7 @@ class DropShorterLongHelpFormatter(argparse.HelpFormatter): - shortcut if there are only two options and one of them is a short one - cache result on action object as this is called at least 2 times """ + def _format_action_invocation(self, action): orgstr = argparse.HelpFormatter._format_action_invocation(self, action) if orgstr and orgstr[0] != '-': # only optional arguments @@ -854,10 +856,13 @@ def _ensure_removed_sysmodule(modname): class CmdOptions(object): """ holds cmdline options as attributes.""" + def __init__(self, values=()): self.__dict__.update(values) + def __repr__(self): return "" % (self.__dict__,) + def copy(self): return CmdOptions(self.__dict__) diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 893043d8982..9da418088e0 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -559,6 +559,7 @@ def __repr__(self): class SubRequest(FixtureRequest): """ a sub request for handling getting a fixture from a test function/fixture. """ + def __init__(self, request, scope, param, param_index, fixturedef): self._parent_request = request self.fixturename = fixturedef.argname @@ -609,6 +610,7 @@ def scope2index(scope, descr, where=None): class FixtureLookupError(LookupError): """ could not return a requested Fixture (missing or invalid). """ + def __init__(self, argname, request, msg=None): self.argname = argname self.request = request @@ -709,6 +711,7 @@ def teardown(): class FixtureDef: """ A container for a factory definition. """ + def __init__(self, fixturemanager, baseid, argname, func, scope, params, unittest=False, ids=None): self._fixturemanager = fixturemanager diff --git a/_pytest/mark.py b/_pytest/mark.py index ce48dd0f116..f9023ec2bcc 100644 --- a/_pytest/mark.py +++ b/_pytest/mark.py @@ -155,6 +155,7 @@ def pytest_collection_modifyitems(items, config): class MarkMapping: """Provides a local mapping for markers where item access resolves to True if the marker is present. """ + def __init__(self, keywords): mymarks = set() for key, value in keywords.items(): @@ -170,6 +171,7 @@ class KeywordMapping: """Provides a local mapping for keywords. Given a list of names, map any substring of one of these names to True. """ + def __init__(self, names): self._names = names @@ -303,6 +305,7 @@ def test_function(): additional keyword or positional arguments. """ + def __init__(self, mark): assert isinstance(mark, Mark), repr(mark) self.mark = mark @@ -366,6 +369,7 @@ def combined_with(self, other): class MarkInfo(object): """ Marking object created by :class:`MarkDecorator` instances. """ + def __init__(self, mark): assert isinstance(mark, Mark), repr(mark) self.combined = mark diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 0ea4d6c4453..ccad16e1892 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -352,6 +352,7 @@ class RunResult: :duration: Duration in seconds. """ + def __init__(self, ret, outlines, errlines, duration): self.ret = ret self.outlines = outlines @@ -581,6 +582,7 @@ def mkpydir(self, name): return p Session = Session + def getnode(self, config, arg): """Return the collection node of a file. diff --git a/_pytest/python.py b/_pytest/python.py index 9b6c5a39b96..5b2224a6bf3 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -490,6 +490,7 @@ def _get_xunit_func(obj, name): class Class(PyCollector): """ Collector for test methods. """ + def collect(self): if not safe_getattr(self.obj, "__test__", True): return [] @@ -715,6 +716,7 @@ class Metafunc(fixtures.FuncargnamesCompatAttr): test configuration or values specified in the class or module where a test function is defined. """ + def __init__(self, function, fixtureinfo, config, cls=None, module=None): #: access to the :class:`_pytest.config.Config` object for the test session self.config = config @@ -1523,6 +1525,7 @@ class Function(FunctionMixin, main.Item, fixtures.FuncargnamesCompatAttr): Python test function. """ _genid = None + def __init__(self, name, parent, args=None, config=None, callspec=None, callobj=NOTSET, keywords=None, session=None, fixtureinfo=None, originalname=None): diff --git a/_pytest/runner.py b/_pytest/runner.py index 8c101557b7a..75e6db900ae 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -148,6 +148,7 @@ class CallInfo: """ Result/Exception info a function invocation. """ #: None or ExceptionInfo object. excinfo = None + def __init__(self, func, when): #: context of invocation: one of "setup", "call", #: "teardown", "memocollect" @@ -277,6 +278,7 @@ class TestReport(BaseReport): """ Basic test report object (also used for setup and teardown calls if they fail). """ + def __init__(self, nodeid, location, keywords, outcome, longrepr, when, sections=(), duration=0, **extra): #: normalized collection node id @@ -318,6 +320,7 @@ def __repr__(self): class TeardownErrorReport(BaseReport): outcome = "failed" when = "teardown" + def __init__(self, longrepr, **extra): self.longrepr = longrepr self.sections = [] @@ -370,11 +373,13 @@ def __repr__(self): class CollectErrorRepr(TerminalRepr): def __init__(self, msg): self.longrepr = msg + def toterminal(self, out): out.line(self.longrepr, red=True) class SetupState(object): """ shared state for setting up/tearing down test items or collectors. """ + def __init__(self): self.stack = [] self._finalizers = {} @@ -469,6 +474,7 @@ class OutcomeException(Exception): """ OutcomeException and its subclass instances indicate and contain info about test and collection outcomes. """ + def __init__(self, msg=None, pytrace=True): Exception.__init__(self, msg) self.msg = msg @@ -500,6 +506,7 @@ class Failed(OutcomeException): class Exit(KeyboardInterrupt): """ raised for immediate program exits (no tracebacks/summaries)""" + def __init__(self, msg="unknown reason"): self.msg = msg KeyboardInterrupt.__init__(self, msg) diff --git a/_pytest/terminal.py b/_pytest/terminal.py index f0bf996f31c..057abdccdbe 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -88,6 +88,7 @@ class WarningReport: """ Simple structure to hold warnings information captured by ``pytest_logwarning``. """ + def __init__(self, code, message, nodeid=None, fslocation=None): """ :param code: unused diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index ea8ef747eb7..4426c068e7f 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -764,6 +764,7 @@ def test_1(): def test_2(): time.sleep(frag) """ + def test_setup_function(self, testdir): testdir.makepyfile(self.source) result = testdir.runpytest("--durations=10") diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index b73ef5232b0..db0f263d3b7 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -33,14 +33,19 @@ class TWMock(object): def __init__(self): self.lines = [] self.is_writing = False + def sep(self, sep, line=None): self.lines.append((sep, line)) + def write(self, msg, **kw): self.lines.append((TWMock.WRITE, msg)) + def line(self, line, **kw): self.lines.append(line) + def markup(self, text, **kw): return text + def get_write_msg(self, idx): flag, msg = self.lines[idx] assert flag == TWMock.WRITE diff --git a/testing/code/test_source.py b/testing/code/test_source.py index a089db054a7..1f251f2a0d1 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -127,6 +127,7 @@ def f(x): def g(x): pass """) + def test_getrange(self): x = self.source[0:2] assert x.isparseable() diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index c97dfcdccfa..8c0bf41d026 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -1251,6 +1251,7 @@ def pytest_generate_tests(metafunc): class TestMarkersWithParametrization(object): pytestmark = pytest.mark.issue308 + def test_simple_mark(self, testdir): s = """ import pytest diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py index 0c11b1bc928..dad73d87022 100644 --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -38,6 +38,7 @@ def _wrapcall(*args, **kargs): class FilesCompleter(object): 'File completer class, optionally takes a list of allowed extensions' + def __init__(self, allowednames=(), directories=True): # Fix if someone passes in a string instead of a list if type(allowednames) is str: diff --git a/testing/test_pytester.py b/testing/test_pytester.py index 932427ad34a..9d0a3ef7096 100644 --- a/testing/test_pytester.py +++ b/testing/test_pytester.py @@ -78,6 +78,7 @@ def make_holder(): class apiclass(object): def pytest_xyz(self, arg): "x" + def pytest_xyz_noarg(self): "x" diff --git a/testing/test_terminal.py b/testing/test_terminal.py index f9344ca308a..a1e480a66eb 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -697,6 +697,7 @@ class TestGenericReporting(object): """ this test class can be subclassed with a different option provider to run e.g. distributed tests. """ + def test_collect_fail(self, testdir, option): testdir.makepyfile("import xyz\n") result = testdir.runpytest(*option.args) diff --git a/tox.ini b/tox.ini index d6c2938e865..e0cb0b80ea8 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E301,E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From b840622819ee9867e92b094a07b371be68a1a43b Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 40/58] Fixed E302 flake8 errors expected 2 blank lines, found 0 --- _pytest/_argcomplete.py | 1 + _pytest/_code/_py2traceback.py | 3 ++ _pytest/_code/code.py | 11 +++++++ _pytest/_code/source.py | 2 ++ _pytest/assertion/rewrite.py | 7 +++++ _pytest/capture.py | 3 ++ _pytest/compat.py | 1 + _pytest/config.py | 8 +++++ _pytest/debugging.py | 1 + _pytest/doctest.py | 2 ++ _pytest/fixtures.py | 5 ++++ _pytest/helpconfig.py | 4 +++ _pytest/hookspec.py | 45 ++++++++++++++++++++++++++++ _pytest/main.py | 8 +++++ _pytest/mark.py | 1 + _pytest/nose.py | 1 + _pytest/pytester.py | 8 +++++ _pytest/python.py | 8 +++++ _pytest/resultlog.py | 5 ++++ _pytest/runner.py | 27 ++++++++++++++++- _pytest/skipping.py | 5 ++++ _pytest/terminal.py | 6 ++++ testing/code/test_code.py | 8 +++++ testing/code/test_excinfo.py | 20 +++++++++++++ testing/code/test_source.py | 37 +++++++++++++++++++++++ testing/freeze/tests/test_trivial.py | 1 + testing/python/collect.py | 3 ++ testing/python/fixture.py | 8 +++++ testing/python/integration.py | 2 ++ testing/test_argcomplete.py | 5 ++++ testing/test_assertion.py | 17 +++++++++++ testing/test_assertrewrite.py | 2 ++ testing/test_cache.py | 1 + testing/test_capture.py | 5 ++++ testing/test_collection.py | 6 ++++ testing/test_config.py | 7 +++++ testing/test_conftest.py | 15 ++++++++++ testing/test_helpconfig.py | 7 +++++ testing/test_junitxml.py | 3 ++ testing/test_mark.py | 7 +++++ testing/test_monkeypatch.py | 1 + testing/test_nose.py | 10 +++++++ testing/test_parseopt.py | 2 ++ testing/test_pastebin.py | 1 + testing/test_pluginmanager.py | 2 ++ testing/test_pytester.py | 3 ++ testing/test_resultlog.py | 2 ++ testing/test_runner.py | 15 ++++++++++ testing/test_runner_xunit.py | 12 ++++++++ testing/test_session.py | 5 ++++ testing/test_skipping.py | 12 ++++++++ testing/test_terminal.py | 13 ++++++++ testing/test_tmpdir.py | 5 ++++ testing/test_unittest.py | 23 ++++++++++++++ testing/test_warnings.py | 1 + tox.ini | 2 +- 56 files changed, 423 insertions(+), 2 deletions(-) diff --git a/_pytest/_argcomplete.py b/_pytest/_argcomplete.py index cb93baa60ca..8fec0effe7c 100644 --- a/_pytest/_argcomplete.py +++ b/_pytest/_argcomplete.py @@ -62,6 +62,7 @@ import os from glob import glob + class FastFilesCompleter: 'Fast file completer class' diff --git a/_pytest/_code/_py2traceback.py b/_pytest/_code/_py2traceback.py index 5c4f5ff2215..5aacf0a428d 100644 --- a/_pytest/_code/_py2traceback.py +++ b/_pytest/_code/_py2traceback.py @@ -5,6 +5,7 @@ from __future__ import absolute_import, division, print_function import types + def format_exception_only(etype, value): """Format the exception part of a traceback. @@ -62,6 +63,7 @@ def format_exception_only(etype, value): lines.append(_format_final_exc_line(stype, value)) return lines + def _format_final_exc_line(etype, value): """Return a list of a single line -- normal case for format_exception_only""" valuestr = _some_str(value) @@ -71,6 +73,7 @@ def _format_final_exc_line(etype, value): line = "%s: %s\n" % (etype, valuestr) return line + def _some_str(value): try: return unicode(value) diff --git a/_pytest/_code/code.py b/_pytest/_code/code.py index e921ceb3bb4..5750211f22e 100644 --- a/_pytest/_code/code.py +++ b/_pytest/_code/code.py @@ -83,6 +83,7 @@ def getargs(self, var=False): argcount += raw.co_flags & CO_VARKEYWORDS return raw.co_varnames[:argcount] + class Frame(object): """Wrapper around a Python frame holding f_locals and f_globals in which expressions can be evaluated.""" @@ -144,6 +145,7 @@ def getargs(self, var=False): pass # this can occur when using Psyco return retval + class TracebackEntry(object): """ a single entry in a traceback """ @@ -256,6 +258,7 @@ def name(self): return self.frame.code.raw.co_name name = property(name, None, None, "co_name of underlaying code") + class Traceback(list): """ Traceback objects encapsulate and offer higher level access to Traceback entries. @@ -351,6 +354,7 @@ def recursionindex(self): co_equal = compile('__recursioncache_locals_1 == __recursioncache_locals_2', '?', 'eval') + class ExceptionInfo(object): """ wraps sys.exc_info() objects and offers help for navigating the traceback. @@ -745,6 +749,7 @@ def toterminal(self, tw): self.reprtraceback.toterminal(tw) super(ReprExceptionInfo, self).toterminal(tw) + class ReprTraceback(TerminalRepr): entrysep = "_ " @@ -768,12 +773,14 @@ def toterminal(self, tw): if self.extraline: tw.line(self.extraline) + class ReprTracebackNative(ReprTraceback): def __init__(self, tblines): self.style = "native" self.reprentries = [ReprEntryNative(tblines)] self.extraline = None + class ReprEntryNative(TerminalRepr): style = "native" @@ -783,6 +790,7 @@ def __init__(self, tblines): def toterminal(self, tw): tw.write("".join(self.lines)) + class ReprEntry(TerminalRepr): localssep = "_ " @@ -820,6 +828,7 @@ def __str__(self): self.reprlocals, self.reprfileloc) + class ReprFileLocation(TerminalRepr): def __init__(self, path, lineno, message): self.path = str(path) @@ -836,6 +845,7 @@ def toterminal(self, tw): tw.write(self.path, bold=True, red=True) tw.line(":%s: %s" % (self.lineno, msg)) + class ReprLocals(TerminalRepr): def __init__(self, lines): self.lines = lines @@ -844,6 +854,7 @@ def toterminal(self, tw): for line in self.lines: tw.line(line) + class ReprFuncArgs(TerminalRepr): def __init__(self, args): self.args = args diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index bf83814fac5..fb00db1a6c8 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -199,6 +199,7 @@ def compile(self, filename=None, mode='exec', # public API shortcut functions # + def compile_(source, filename=None, mode='exec', flags=generators.compiler_flag, dont_inherit=0): """ compile the given source to a raw code object, and maintain an internal cache which allows later @@ -245,6 +246,7 @@ def getfslineno(obj): # helper functions # + def findsource(obj): try: sourcelines, lineno = py.std.inspect.findsource(obj) diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index bce04398b2e..48f5d43887a 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -283,6 +283,7 @@ def _write_pyc(state, co, source_stat, pyc): cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+") BOM_UTF8 = '\xef\xbb\xbf' + def _rewrite_test(config, fn): """Try to read and rewrite *fn* and return the code object.""" state = config._assertstate @@ -340,6 +341,7 @@ def _rewrite_test(config, fn): 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"): @@ -353,6 +355,7 @@ def _make_rewritten_pyc(state, source_stat, pyc, co): 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. @@ -412,6 +415,7 @@ def _saferepr(obj): from _pytest.assertion.util import format_explanation as _format_explanation # noqa + def _format_assertmsg(obj): """Format the custom assertion message given. @@ -439,9 +443,11 @@ def _format_assertmsg(obj): 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): @@ -450,6 +456,7 @@ def _format_boolop(explanations, is_or): 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: diff --git a/_pytest/capture.py b/_pytest/capture.py index ea88e08f2a1..481bc25499e 100644 --- a/_pytest/capture.py +++ b/_pytest/capture.py @@ -171,6 +171,7 @@ def capsys(request): request.node._capfuncarg = c = CaptureFixture(SysCapture, request) return c + @pytest.fixture def capfd(request): """Enable capturing of writes to file descriptors 1 and 2 and make @@ -319,9 +320,11 @@ def readouterr(self): return (self.out.snap() if self.out is not None else "", self.err.snap() if self.err is not None else "") + class NoCapture: __init__ = start = done = suspend = resume = lambda *args: None + class FDCapture: """ Capture IO to/from a given os-level filedescriptor. """ diff --git a/_pytest/compat.py b/_pytest/compat.py index 5c364c18ffc..bebcc71f94d 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -297,6 +297,7 @@ def __init__(self): def getvalue(self): return self.buffer.getvalue().decode('UTF-8') + class FuncargnamesCompatAttr(object): """ helper class so that Metafunc, Function and FixtureRequest don't need to each define the "funcargnames" compatibility attribute. diff --git a/_pytest/config.py b/_pytest/config.py index 2b8ba0b6cb2..7d299b30fdc 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -63,6 +63,7 @@ def main(args=None, plugins=None): sys.stderr.write("ERROR: %s\n" % (msg,)) return 4 + class cmdline: # compatibility namespace main = staticmethod(main) @@ -116,6 +117,7 @@ def _preloadplugins(): assert not _preinit _preinit.append(get_config()) + def get_config(): if _preinit: return _preinit.pop(0) @@ -126,6 +128,7 @@ def get_config(): pluginmanager.import_plugin(spec) return config + def get_plugin_manager(): """ Obtain a new instance of the @@ -137,6 +140,7 @@ def get_plugin_manager(): """ return get_config().pluginmanager + def _prepareconfig(args=None, plugins=None): warning = None if args is None: @@ -854,6 +858,7 @@ def _ensure_removed_sysmodule(modname): except KeyError: pass + class CmdOptions(object): """ holds cmdline options as attributes.""" @@ -866,6 +871,7 @@ def __repr__(self): def copy(self): return CmdOptions(self.__dict__) + class Notset: def __repr__(self): return "" @@ -1235,12 +1241,14 @@ def getvalueorskip(self, name, path=None): """ (deprecated, use getoption(skip=True)) """ return self.getoption(name, skip=True) + def exists(path, ignore=EnvironmentError): try: return path.check() except ignore: return False + def getcfg(args, warnfunc=None): """ Search the list of arguments for a valid ini-file for pytest, diff --git a/_pytest/debugging.py b/_pytest/debugging.py index 73a0a2ef585..1d69cd0ad30 100644 --- a/_pytest/debugging.py +++ b/_pytest/debugging.py @@ -40,6 +40,7 @@ def fin(): pytestPDB._pdb_cls = pdb_cls config._cleanup.append(fin) + class pytestPDB: """ Pseudo PDB that defers to the real pdb. """ _pluginmanager = None diff --git a/_pytest/doctest.py b/_pytest/doctest.py index 4968504e464..88174cc729b 100644 --- a/_pytest/doctest.py +++ b/_pytest/doctest.py @@ -22,6 +22,7 @@ DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE, ) + def pytest_addoption(parser): parser.addini('doctest_optionflags', 'option flags for doctests', type="args", default=["ELLIPSIS"]) @@ -163,6 +164,7 @@ def get_optionflags(parent): flag_acc |= flag_lookup_table[flag] return flag_acc + class DoctestTextfile(pytest.Module): obj = None diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 9da418088e0..67cf7e39eb4 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -19,6 +19,7 @@ from _pytest.runner import fail from _pytest.compat import FuncargnamesCompatAttr + def pytest_sessionstart(session): import _pytest.python scopename2class.update({ @@ -38,6 +39,7 @@ def pytest_sessionstart(session): 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__ @@ -166,6 +168,7 @@ def reorder_items(items): 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 @@ -241,6 +244,7 @@ def fillfixtures(function): def get_direct_param_fixture_func(request): return request.param + class FuncFixtureInfo: def __init__(self, argnames, names_closure, name2fixturedefs): self.argnames = argnames @@ -786,6 +790,7 @@ def __repr__(self): return ("" % (self.argname, self.scope, self.baseid)) + def pytest_fixture_setup(fixturedef, request): """ Execution of fixture setup. """ kwargs = {} diff --git a/_pytest/helpconfig.py b/_pytest/helpconfig.py index 320eb4ab6c4..5be1caa1dad 100644 --- a/_pytest/helpconfig.py +++ b/_pytest/helpconfig.py @@ -86,6 +86,7 @@ def unset_tracing(): config.add_cleanup(unset_tracing) + def pytest_cmdline_main(config): if config.option.version: p = py.path.local(pytest.__file__) @@ -102,6 +103,7 @@ def pytest_cmdline_main(config): config._ensure_unconfigure() return 0 + def showhelp(config): reporter = config.pluginmanager.get_plugin('terminalreporter') tw = reporter._tw @@ -146,6 +148,7 @@ def showhelp(config): ('pytest_plugins', 'list of plugin names to load'), ] + def getpluginversioninfo(config): lines = [] plugininfo = config.pluginmanager.list_plugin_distinfo() @@ -157,6 +160,7 @@ def getpluginversioninfo(config): lines.append(" " + content) return lines + def pytest_report_header(config): lines = [] if config.option.debug or config.option.traceconfig: diff --git a/_pytest/hookspec.py b/_pytest/hookspec.py index f12aa87ccdb..43667d701c2 100644 --- a/_pytest/hookspec.py +++ b/_pytest/hookspec.py @@ -8,6 +8,7 @@ # Initialization hooks called for every plugin # ------------------------------------------------------------------------- + @hookspec(historic=True) def pytest_addhooks(pluginmanager): """called at plugin registration time to allow adding new hooks via a call to @@ -23,6 +24,7 @@ def pytest_namespace(): time. """ + @hookspec(historic=True) def pytest_plugin_registered(plugin, manager): """ a new pytest plugin got registered. """ @@ -58,6 +60,7 @@ def pytest_addoption(parser): via (deprecated) ``pytest.config``. """ + @hookspec(historic=True) def pytest_configure(config): """ @@ -79,15 +82,18 @@ def pytest_configure(config): # discoverable conftest.py local plugins. # ------------------------------------------------------------------------- + @hookspec(firstresult=True) def pytest_cmdline_parse(pluginmanager, args): """return initialized config object, parsing the specified args. Stops at first non-None result, see :ref:`firstresult` """ + def pytest_cmdline_preparse(config, args): """(deprecated) modify command line arguments before option parsing. """ + @hookspec(firstresult=True) def pytest_cmdline_main(config): """ called for performing the main command line action. The default @@ -95,6 +101,7 @@ def pytest_cmdline_main(config): Stops at first non-None result, see :ref:`firstresult` """ + def pytest_load_initial_conftests(early_config, parser, args): """ implements the loading of initial conftest files ahead of command line option parsing. """ @@ -110,13 +117,16 @@ def pytest_collection(session): Stops at first non-None result, see :ref:`firstresult` """ + def pytest_collection_modifyitems(session, config, items): """ called after collection has been performed, may filter or re-order the items in-place.""" + def pytest_collection_finish(session): """ called after collection has been performed and modified. """ + @hookspec(firstresult=True) def pytest_ignore_collect(path, config): """ return True to prevent considering this path for collection. @@ -126,29 +136,37 @@ def pytest_ignore_collect(path, config): Stops at first non-None result, see :ref:`firstresult` """ + @hookspec(firstresult=True) def pytest_collect_directory(path, parent): """ called before traversing a directory for collection files. Stops at first non-None result, see :ref:`firstresult` """ + def pytest_collect_file(path, parent): """ return collection Node or None for the given path. Any new node needs to have the specified ``parent`` as a parent.""" # logging hooks for collection + + def pytest_collectstart(collector): """ collector starts collecting. """ + def pytest_itemcollected(item): """ we just collected a test item. """ + def pytest_collectreport(report): """ collector finished collecting. """ + def pytest_deselected(items): """ called for test items deselected by keyword. """ + @hookspec(firstresult=True) def pytest_make_collect_report(collector): """ perform ``collector.collect()`` and return a CollectReport. @@ -159,6 +177,7 @@ def pytest_make_collect_report(collector): # Python test function related hooks # ------------------------------------------------------------------------- + @hookspec(firstresult=True) def pytest_pycollect_makemodule(path, parent): """ return a Module collector or None for the given path. @@ -168,21 +187,25 @@ def pytest_pycollect_makemodule(path, parent): Stops at first non-None result, see :ref:`firstresult` """ + @hookspec(firstresult=True) def pytest_pycollect_makeitem(collector, name, obj): """ return custom item/collector for a python object in a module, or None. Stops at first non-None result, see :ref:`firstresult` """ + @hookspec(firstresult=True) def pytest_pyfunc_call(pyfuncitem): """ call underlying test function. Stops at first non-None result, see :ref:`firstresult` """ + def pytest_generate_tests(metafunc): """ generate (multiple) parametrized calls to a test function.""" + @hookspec(firstresult=True) def pytest_make_parametrize_id(config, val, argname): """Return a user-friendly string representation of the given ``val`` that will be used @@ -195,6 +218,7 @@ def pytest_make_parametrize_id(config, val, argname): # generic runtest related hooks # ------------------------------------------------------------------------- + @hookspec(firstresult=True) def pytest_runtestloop(session): """ called for performing the main runtest loop @@ -202,9 +226,11 @@ def pytest_runtestloop(session): Stops at first non-None result, see :ref:`firstresult` """ + def pytest_itemstart(item, node): """ (deprecated, use pytest_runtest_logstart). """ + @hookspec(firstresult=True) def pytest_runtest_protocol(item, nextitem): """ implements the runtest_setup/call/teardown protocol for @@ -222,15 +248,19 @@ def pytest_runtest_protocol(item, nextitem): Stops at first non-None result, see :ref:`firstresult` """ + def pytest_runtest_logstart(nodeid, location): """ signal the start of running a single test item. """ + def pytest_runtest_setup(item): """ called before ``pytest_runtest_call(item)``. """ + def pytest_runtest_call(item): """ called to execute the test ``item``. """ + def pytest_runtest_teardown(item, nextitem): """ called after ``pytest_runtest_call``. @@ -240,6 +270,7 @@ def pytest_runtest_teardown(item, nextitem): so that nextitem only needs to call setup-functions. """ + @hookspec(firstresult=True) def pytest_runtest_makereport(item, call): """ return a :py:class:`_pytest.runner.TestReport` object @@ -248,6 +279,7 @@ def pytest_runtest_makereport(item, call): Stops at first non-None result, see :ref:`firstresult` """ + def pytest_runtest_logreport(report): """ process a test setup/call/teardown report relating to the respective phase of executing a test. """ @@ -256,12 +288,14 @@ def pytest_runtest_logreport(report): # Fixture related hooks # ------------------------------------------------------------------------- + @hookspec(firstresult=True) def pytest_fixture_setup(fixturedef, request): """ performs fixture setup execution. Stops at first non-None result, see :ref:`firstresult` """ + def pytest_fixture_post_finalizer(fixturedef): """ called after fixture teardown, but before the cache is cleared so the fixture result cache ``fixturedef.cached_result`` can @@ -271,12 +305,15 @@ def pytest_fixture_post_finalizer(fixturedef): # test session related hooks # ------------------------------------------------------------------------- + def pytest_sessionstart(session): """ before session.main() is called. """ + def pytest_sessionfinish(session, exitstatus): """ whole test run finishes. """ + def pytest_unconfigure(config): """ called before test process is exited. """ @@ -298,6 +335,7 @@ def pytest_assertrepr_compare(config, op, left, right): # hooks for influencing reporting (invoked from _pytest_terminal) # ------------------------------------------------------------------------- + def pytest_report_header(config, startdir): """ return a string to be displayed as header info for terminal reporting. @@ -308,12 +346,14 @@ def pytest_report_header(config, startdir): :ref:`discovers plugins during startup `. """ + @hookspec(firstresult=True) def pytest_report_teststatus(report): """ return result-category, shortletter and verbose word for reporting. Stops at first non-None result, see :ref:`firstresult` """ + def pytest_terminal_summary(terminalreporter, exitstatus): """ add additional section in terminal summary reporting. """ @@ -328,6 +368,7 @@ def pytest_logwarning(message, code, nodeid, fslocation): # doctest hooks # ------------------------------------------------------------------------- + @hookspec(firstresult=True) def pytest_doctest_prepare_content(content): """ return processed content for a given doctest @@ -338,12 +379,15 @@ def pytest_doctest_prepare_content(content): # error handling and internal debugging hooks # ------------------------------------------------------------------------- + def pytest_internalerror(excrepr, excinfo): """ called for internal errors. """ + def pytest_keyboard_interrupt(excinfo): """ called for keyboard interrupt. """ + def pytest_exception_interact(node, call, report): """called when an exception was raised which can potentially be interactively handled. @@ -352,6 +396,7 @@ def pytest_exception_interact(node, call, report): that is not an internal exception like ``skip.Exception``. """ + def pytest_enter_pdb(config): """ called upon pdb.set_trace(), can be used by plugins to take special action just before the python debugger enters in interactive mode. diff --git a/_pytest/main.py b/_pytest/main.py index 5460b537e5b..b9850b8b687 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -200,6 +200,7 @@ def __getattr__(self, name): self.__dict__[name] = x return x + class _CompatProperty(object): def __init__(self, name): self.name = name @@ -457,6 +458,7 @@ def _repr_failure_py(self, excinfo, style=None): repr_failure = _repr_failure_py + class Collector(Node): """ Collector instances create children through collect() and thus iteratively build a tree. @@ -486,6 +488,7 @@ def _prunetraceback(self, excinfo): ntraceback = ntraceback.cut(excludepath=tracebackcutdir) excinfo.traceback = ntraceback.filter() + class FSCollector(Collector): def __init__(self, fspath, parent=None, config=None, session=None): fspath = py.path.local(fspath) # xxx only for test_resultlog.py? @@ -504,9 +507,11 @@ def _makeid(self): relpath = relpath.replace(os.sep, "/") return relpath + class File(FSCollector): """ base class for collecting tests from a file. """ + class Item(Node): """ a basic test invocation item. Note that for a single function there might be multiple test invocation items. @@ -556,13 +561,16 @@ def location(self): self._location = location return location + class NoMatch(Exception): """ raised if matching cannot locate a matching names. """ + class Interrupted(KeyboardInterrupt): """ signals an interrupted test run. """ __module__ = 'builtins' # for py3 + class Session(FSCollector): Interrupted = Interrupted diff --git a/_pytest/mark.py b/_pytest/mark.py index f9023ec2bcc..88642a000fc 100644 --- a/_pytest/mark.py +++ b/_pytest/mark.py @@ -272,6 +272,7 @@ def istestfunc(func): return hasattr(func, "__call__") and \ getattr(func, "__name__", "") != "" + class MarkDecorator: """ A decorator for test functions and test classes. When applied it will create :class:`MarkInfo` objects which may be diff --git a/_pytest/nose.py b/_pytest/nose.py index f21e3967342..d246c5603d2 100644 --- a/_pytest/nose.py +++ b/_pytest/nose.py @@ -41,6 +41,7 @@ def pytest_runtest_setup(item): # XXX this implies we only call teardown when setup worked item.session._setupstate.addfinalizer((lambda: teardown_nose(item)), item) + def teardown_nose(item): if is_potential_nosetest(item): if not call_optional(item.obj, 'teardown'): diff --git a/_pytest/pytester.py b/_pytest/pytester.py index ccad16e1892..12473231d2a 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -122,6 +122,7 @@ def pytest_runtest_protocol(self, item): 'python3.5': r'C:\Python35\python.exe', } + def getexecutable(name, cache={}): try: return cache[name] @@ -143,6 +144,7 @@ def getexecutable(name, cache={}): cache[name] = executable return executable + @pytest.fixture(params=['python2.6', 'python2.7', 'python3.3', "python3.4", 'pypy', 'pypy3']) def anypython(request): @@ -159,6 +161,8 @@ def anypython(request): return executable # used at least by pytest-xdist plugin + + @pytest.fixture def _pytest(request): """ Return a helper which offers a gethookrecorder(hook) @@ -167,6 +171,7 @@ def _pytest(request): """ return PytestArg(request) + class PytestArg: def __init__(self, request): self.request = request @@ -337,6 +342,8 @@ def testdir(request, tmpdir_factory): rex_outcome = re.compile(r"(\d+) ([\w-]+)") + + class RunResult: """The result of running a command. @@ -1033,6 +1040,7 @@ def spawn(self, cmd, expect_timeout=10.0): child.timeout = expect_timeout return child + def getdecoded(out): try: return out.decode("utf-8") diff --git a/_pytest/python.py b/_pytest/python.py index 5b2224a6bf3..39dd5394a0b 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -112,6 +112,7 @@ def pytest_generate_tests(metafunc): for marker in markers: metafunc.parametrize(*marker.args, **marker.kwargs) + def pytest_configure(config): config.addinivalue_line("markers", "parametrize(argnames, argvalues): call a test function multiple " @@ -155,9 +156,11 @@ def pytest_collect_file(path, parent): ihook = parent.session.gethookproxy(path) return ihook.pytest_pycollect_makemodule(path=path, parent=parent) + def pytest_pycollect_makemodule(path, parent): return Module(path, parent) + @hookimpl(hookwrapper=True) def pytest_pycollect_makeitem(collector, name, obj): outcome = yield @@ -185,6 +188,7 @@ def pytest_pycollect_makeitem(collector, name, obj): res = list(collector._genfunctions(name, obj)) outcome.force_result(res) + def pytest_make_parametrize_id(config, val, argname=None): return None @@ -195,6 +199,7 @@ class PyobjContext(object): cls = pyobj_property("Class") instance = pyobj_property("Instance") + class PyobjMixin(PyobjContext): def obj(): def fget(self): @@ -252,6 +257,7 @@ def reportinfo(self): assert isinstance(lineno, int) return fspath, lineno, modpath + class PyCollector(PyobjMixin, main.Collector): def funcnamefilter(self, name): @@ -517,6 +523,7 @@ def setup(self): fin_class = getattr(fin_class, '__func__', fin_class) self.addfinalizer(lambda: fin_class(self.obj)) + class Instance(PyCollector): def _getobj(self): return self.parent.obj() @@ -529,6 +536,7 @@ def newinstance(self): self.obj = self._getobj() return self.obj + class FunctionMixin(PyobjMixin): """ mixin for the code common to Function and Generator. """ diff --git a/_pytest/resultlog.py b/_pytest/resultlog.py index 93523038adc..9f9c2d1f653 100644 --- a/_pytest/resultlog.py +++ b/_pytest/resultlog.py @@ -6,12 +6,14 @@ import py import os + def pytest_addoption(parser): group = parser.getgroup("terminal reporting", "resultlog plugin options") group.addoption('--resultlog', '--result-log', action="store", metavar="path", default=None, help="DEPRECATED path for machine-readable result log.") + def pytest_configure(config): resultlog = config.option.resultlog # prevent opening resultlog on slave nodes (xdist) @@ -26,6 +28,7 @@ def pytest_configure(config): from _pytest.deprecated import RESULT_LOG config.warn('C1', RESULT_LOG) + def pytest_unconfigure(config): resultlog = getattr(config, '_resultlog', None) if resultlog: @@ -33,6 +36,7 @@ def pytest_unconfigure(config): del config._resultlog config.pluginmanager.unregister(resultlog) + def generic_path(item): chain = item.listchain() gpath = [chain[0].name] @@ -56,6 +60,7 @@ def generic_path(item): fspath = newfspath return ''.join(gpath) + class ResultLog(object): def __init__(self, config, logfile): self.config = config diff --git a/_pytest/runner.py b/_pytest/runner.py index 75e6db900ae..d9d26636137 100644 --- a/_pytest/runner.py +++ b/_pytest/runner.py @@ -9,7 +9,6 @@ from _pytest._code.code import TerminalRepr, ExceptionInfo - # # pytest plugin hooks @@ -19,6 +18,7 @@ def pytest_addoption(parser): action="store", type=int, default=None, metavar="N", help="show N slowest setup/test durations (N=0 for all)."), + def pytest_terminal_summary(terminalreporter): durations = terminalreporter.config.option.durations if durations is None: @@ -44,15 +44,20 @@ def pytest_terminal_summary(terminalreporter): tr.write_line("%02.2fs %-8s %s" % (rep.duration, rep.when, nodeid)) + def pytest_sessionstart(session): session._setupstate = SetupState() + + def pytest_sessionfinish(session): session._setupstate.teardown_all() + class NodeInfo: def __init__(self, location): self.location = location + def pytest_runtest_protocol(item, nextitem): item.ihook.pytest_runtest_logstart( nodeid=item.nodeid, location=item.location, @@ -60,6 +65,7 @@ def pytest_runtest_protocol(item, nextitem): runtestprotocol(item, nextitem=nextitem) return True + def runtestprotocol(item, log=True, nextitem=None): hasrequest = hasattr(item, "_request") if hasrequest and not item._request: @@ -80,6 +86,7 @@ def runtestprotocol(item, log=True, nextitem=None): item.funcargs = None return reports + def show_test_item(item): """Show test function, parameters and the fixtures of the test item.""" tw = item.config.get_terminal_writer() @@ -90,9 +97,11 @@ def show_test_item(item): if used_fixtures: tw.write(' (fixtures used: {0})'.format(', '.join(used_fixtures))) + def pytest_runtest_setup(item): item.session._setupstate.prepare(item) + def pytest_runtest_call(item): try: item.runtest() @@ -106,9 +115,11 @@ def pytest_runtest_call(item): del tb # Get rid of it in this namespace raise + def pytest_runtest_teardown(item, nextitem): item.session._setupstate.teardown_exact(item, nextitem) + def pytest_report_teststatus(report): if report.when in ("setup", "teardown"): if report.failed: @@ -133,17 +144,20 @@ def call_and_report(item, when, log=True, **kwds): hook.pytest_exception_interact(node=item, call=call, report=report) return report + def check_interactive_exception(call, report): return call.excinfo and not ( hasattr(report, "wasxfail") or call.excinfo.errisinstance(skip.Exception) or call.excinfo.errisinstance(bdb.BdbQuit)) + def call_runtest_hook(item, when, **kwds): hookname = "pytest_runtest_" + when ihook = getattr(item.ihook, hookname) return CallInfo(lambda: ihook(item=item, **kwds), when=when) + class CallInfo: """ Result/Exception info a function invocation. """ #: None or ExceptionInfo object. @@ -170,6 +184,7 @@ def __repr__(self): status = "result: %r" % (self.result,) return "" % (self.when, status) + def getslaveinfoline(node): try: return node._slaveinfocache @@ -180,6 +195,7 @@ def getslaveinfoline(node): d['id'], d['sysplatform'], ver, d['executable']) return s + class BaseReport(object): def __init__(self, **kw): @@ -244,6 +260,7 @@ def capstderr(self): def fspath(self): return self.nodeid.split("::")[0] + def pytest_runtest_makereport(item, call): when = call.when duration = call.stop - call.start @@ -274,6 +291,7 @@ def pytest_runtest_makereport(item, call): keywords, outcome, longrepr, when, sections, duration) + class TestReport(BaseReport): """ Basic test report object (also used for setup and teardown calls if they fail). @@ -317,6 +335,7 @@ def __repr__(self): return "" % ( self.nodeid, self.when, self.outcome) + class TeardownErrorReport(BaseReport): outcome = "failed" when = "teardown" @@ -326,6 +345,7 @@ def __init__(self, longrepr, **extra): self.sections = [] self.__dict__.update(extra) + def pytest_make_collect_report(collector): call = CallInfo( lambda: list(collector.collect()), @@ -370,6 +390,7 @@ def __repr__(self): return "" % ( self.nodeid, len(self.result), self.outcome) + class CollectErrorRepr(TerminalRepr): def __init__(self, msg): self.longrepr = msg @@ -377,6 +398,7 @@ def __init__(self, msg): def toterminal(self, out): out.line(self.longrepr, red=True) + class SetupState(object): """ shared state for setting up/tearing down test items or collectors. """ @@ -456,6 +478,7 @@ def prepare(self, colitem): col._prepare_exc = sys.exc_info() raise + def collect_one_node(collector): ihook = collector.ihook ihook.pytest_collectstart(collector=collector) @@ -489,6 +512,7 @@ def __repr__(self): return "<%s instance>" % (self.__class__.__name__,) __str__ = __repr__ + class Skipped(OutcomeException): # XXX hackish: on 3k we fake to live in the builtins # in order to have Skipped exception printing shorter/nicer @@ -513,6 +537,7 @@ def __init__(self, msg="unknown reason"): # exposed helper methods + def exit(msg): """ exit testing process as if KeyboardInterrupt was triggered. """ __tracebackhide__ = True diff --git a/_pytest/skipping.py b/_pytest/skipping.py index 56b36166044..61965009242 100644 --- a/_pytest/skipping.py +++ b/_pytest/skipping.py @@ -10,6 +10,7 @@ from _pytest.mark import MarkInfo, MarkDecorator from _pytest.runner import fail, skip + def pytest_addoption(parser): group = parser.getgroup("general") group.addoption('--runxfail', @@ -269,6 +270,8 @@ def pytest_runtest_makereport(item, call): rep.longrepr = filename, line, reason # called by terminalreporter progress reporting + + def pytest_report_teststatus(report): if hasattr(report, "wasxfail"): if report.skipped: @@ -277,6 +280,8 @@ def pytest_report_teststatus(report): return "xpassed", "X", ("XPASS", {'yellow': True}) # called by the terminalreporter instance/plugin + + def pytest_terminal_summary(terminalreporter): tr = terminalreporter if not tr.reportchars: diff --git a/_pytest/terminal.py b/_pytest/terminal.py index 057abdccdbe..fdf9090429f 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -47,6 +47,7 @@ def pytest_addoption(parser): choices=['yes', 'no', 'auto'], help="color terminal output (yes/no/auto).") + def pytest_configure(config): config.option.verbose -= config.option.quiet reporter = TerminalReporter(config, sys.stdout) @@ -57,6 +58,7 @@ def mywriter(tags, args): reporter.write_line("[traceconfig] " + msg) config.trace.root.setprocessor("pytest:config", mywriter) + def getreportopt(config): reportopts = "" reportchars = config.option.reportchars @@ -72,6 +74,7 @@ def getreportopt(config): reportopts = 'fEsxXw' return reportopts + def pytest_report_teststatus(report): if report.passed: letter = "." @@ -568,6 +571,7 @@ def summary_deselected(self): self.write_sep("=", "%d tests deselected" % ( len(self.stats['deselected'])), bold=True) + def repr_pythonversion(v=None): if v is None: v = sys.version_info @@ -576,6 +580,7 @@ def repr_pythonversion(v=None): except (TypeError, ValueError): return str(v) + def flatten(l): for x in l: if isinstance(x, (list, tuple)): @@ -584,6 +589,7 @@ def flatten(l): else: yield x + def build_summary_stats_line(stats): keys = ("failed passed skipped deselected " "xfailed xpassed warnings error").split() diff --git a/testing/code/test_code.py b/testing/code/test_code.py index 479a2e7cc9f..acf1ffc91c1 100644 --- a/testing/code/test_code.py +++ b/testing/code/test_code.py @@ -12,6 +12,7 @@ def test_ne(): code2 = _pytest._code.Code(compile('foo = "baz"', '', 'exec')) assert code2 != code1 + def test_code_gives_back_name_for_not_existing_file(): name = 'abc-123' co_code = compile("pass\n", name, 'exec') @@ -20,6 +21,7 @@ def test_code_gives_back_name_for_not_existing_file(): assert str(code.path) == name assert code.fullsource is None + def test_code_with_class(): class A(object): pass @@ -30,11 +32,13 @@ class A(object): def x(): pass + def test_code_fullsource(): code = _pytest._code.Code(x) full = code.fullsource assert 'test_code_fullsource()' in str(full) + def test_code_source(): code = _pytest._code.Code(x) src = code.source() @@ -42,6 +46,7 @@ def test_code_source(): pass""" assert str(src) == expected + def test_frame_getsourcelineno_myself(): def func(): return sys._getframe(0) @@ -50,6 +55,7 @@ def func(): source, lineno = f.code.fullsource, f.lineno assert source[lineno].startswith(" return sys._getframe(0)") + def test_getstatement_empty_fullsource(): def func(): return sys._getframe(0) @@ -62,6 +68,7 @@ def func(): finally: f.code.__class__.fullsource = prop + def test_code_from_func(): co = _pytest._code.Code(test_frame_getsourcelineno_myself) assert co.firstlineno @@ -92,6 +99,7 @@ def f(): if sys.version_info[0] < 3: unicode(excinfo) + def test_code_getargs(): def f1(x): pass diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index db0f263d3b7..48ef6e7e8d6 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -27,6 +27,7 @@ import pytest pytest_version_info = tuple(map(int, pytest.__version__.split(".")[:3])) + class TWMock(object): WRITE = object() @@ -53,6 +54,7 @@ def get_write_msg(self, idx): fullwidth = 80 + def test_excinfo_simple(): try: raise ValueError @@ -60,6 +62,7 @@ def test_excinfo_simple(): info = _pytest._code.ExceptionInfo() assert info.type == ValueError + def test_excinfo_getstatement(): def g(): raise ValueError @@ -82,20 +85,27 @@ def f(): # xxx # testchain for getentries test below + + def f(): # raise ValueError # + + def g(): # __tracebackhide__ = True f() # + + def h(): # g() # + class TestTraceback_f_g_h(object): def setup_method(self, method): try: @@ -299,6 +309,7 @@ def f(): assert entry.lineno == co.firstlineno + 2 assert entry.frame.code.name == 'g' + def test_excinfo_exconly(): excinfo = pytest.raises(ValueError, h) assert excinfo.exconly().startswith('ValueError') @@ -308,11 +319,13 @@ def test_excinfo_exconly(): assert msg.startswith('ValueError') assert msg.endswith("world") + def test_excinfo_repr(): excinfo = pytest.raises(ValueError, h) s = repr(excinfo) assert s == "" + def test_excinfo_str(): excinfo = pytest.raises(ValueError, h) s = str(excinfo) @@ -320,10 +333,12 @@ def test_excinfo_str(): assert s.endswith("ValueError") assert len(s.split(":")) >= 3 # on windows it's 4 + def test_excinfo_errisinstance(): excinfo = pytest.raises(ValueError, h) assert excinfo.errisinstance(ValueError) + def test_excinfo_no_sourcecode(): try: exec ("raise ValueError()") @@ -335,6 +350,7 @@ def test_excinfo_no_sourcecode(): else: assert s == " File '':1 in \n ???\n" + def test_excinfo_no_python_sourcecode(tmpdir): # XXX: simplified locally testable version tmpdir.join('test.txt').write("{{ h()}}:") @@ -363,6 +379,7 @@ def test_entrysource_Queue_example(): s = str(source).strip() assert s.startswith("def get") + def test_codepath_Queue_example(): try: queue.Queue().get(timeout=0.001) @@ -374,11 +391,13 @@ def test_codepath_Queue_example(): assert path.basename.lower() == "queue.py" assert path.check() + def test_match_succeeds(): with pytest.raises(ZeroDivisionError) as excinfo: 0 // 0 excinfo.match(r'.*zero.*') + def test_match_raises_error(testdir): testdir.makepyfile(""" import pytest @@ -393,6 +412,7 @@ def test_division_zero(): "*AssertionError*Pattern*[123]*not found*", ]) + class TestFormattedExcinfo(object): @pytest.fixture diff --git a/testing/code/test_source.py b/testing/code/test_source.py index 1f251f2a0d1..e9732d7f3f1 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -17,6 +17,7 @@ failsonjython = pytest.mark.xfail("sys.platform.startswith('java')") + def test_source_str_function(): x = Source("3") assert str(x) == "3" @@ -34,6 +35,7 @@ def test_source_str_function(): """, rstrip=True) assert str(x) == "\n3" + def test_unicode(): try: unicode @@ -45,10 +47,12 @@ def test_unicode(): val = eval(co) assert isinstance(val, unicode) + def test_source_from_function(): source = _pytest._code.Source(test_source_str_function) assert str(source).startswith('def test_source_str_function():') + def test_source_from_method(): class TestClass(object): def test_method(self): @@ -57,11 +61,13 @@ def test_method(self): assert source.lines == ["def test_method(self):", " pass"] + def test_source_from_lines(): lines = ["a \n", "b\n", "c"] source = _pytest._code.Source(lines) assert source.lines == ['a ', 'b', 'c'] + def test_source_from_inner_function(): def f(): pass @@ -70,6 +76,7 @@ def f(): source = _pytest._code.Source(f) assert str(source).startswith('def f():') + def test_source_putaround_simple(): source = Source("raise ValueError") source = source.putaround( @@ -86,6 +93,7 @@ def test_source_putaround_simple(): else: x = 23""" + def test_source_putaround(): source = Source() source = source.putaround(""" @@ -94,24 +102,28 @@ def test_source_putaround(): """) assert str(source).strip() == "if 1:\n x=1" + def test_source_strips(): source = Source("") assert source == Source() assert str(source) == '' assert source.strip() == source + def test_source_strip_multiline(): source = Source() source.lines = ["", " hello", " "] source2 = source.strip() assert source2.lines == [" hello"] + def test_syntaxerror_rerepresentation(): ex = pytest.raises(SyntaxError, _pytest._code.compile, 'xyz xyz') assert ex.value.lineno == 1 assert ex.value.offset in (4, 7) # XXX pypy/jython versus cpython? assert ex.value.text.strip(), 'x x' + def test_isparseable(): assert Source("hello").isparseable() assert Source("if 1:\n pass").isparseable() @@ -120,6 +132,7 @@ def test_isparseable(): assert not Source(" \nif 1:\npass").isparseable() assert not Source(chr(0)).isparseable() + class TestAccesses(object): source = Source("""\ def f(x): @@ -145,6 +158,7 @@ def test_iter(self): l = [x for x in self.source] assert len(l) == 4 + class TestSourceParsingAndCompiling(object): source = Source("""\ def f(x): @@ -308,6 +322,7 @@ def check(comp, name): def test_offsetless_synerr(self): pytest.raises(SyntaxError, _pytest._code.compile, "lambda a,a: 0", mode='eval') + def test_getstartingblock_singleline(): class A(object): def __init__(self, *args): @@ -319,6 +334,7 @@ def __init__(self, *args): l = [i for i in x.source.lines if i.strip()] assert len(l) == 1 + def test_getstartingblock_multiline(): class A(object): def __init__(self, *args): @@ -333,6 +349,7 @@ def __init__(self, *args): l = [i for i in x.source.lines if i.strip()] assert len(l) == 4 + def test_getline_finally(): def c(): pass excinfo = pytest.raises(TypeError, """ @@ -346,6 +363,7 @@ def c(): pass source = excinfo.traceback[-1].statement assert str(source).strip() == 'c(1)' + def test_getfuncsource_dynamic(): source = """ def f(): @@ -387,6 +405,7 @@ def g(): lines = deindent(source.splitlines()) assert lines == ['', 'def f():', ' def g():', ' pass', ' '] + @pytest.mark.xfail("sys.version_info[:3] < (2,7,0)") def test_source_of_class_at_eof_without_newline(tmpdir): # this test fails because the implicit inspect.getsource(A) below @@ -406,6 +425,7 @@ def method(self): def x(): pass + def test_getsource_fallback(): from _pytest._code.source import getsource expected = """def x(): @@ -413,6 +433,7 @@ def test_getsource_fallback(): src = getsource(x) assert src == expected + def test_idem_compile_and_getsource(): from _pytest._code.source import getsource expected = "def x(): pass" @@ -420,12 +441,14 @@ def test_idem_compile_and_getsource(): src = getsource(co) assert src == expected + def test_findsource_fallback(): from _pytest._code.source import findsource src, lineno = findsource(x) assert 'test_findsource_simple' in str(src) assert src[lineno] == ' def x():' + def test_findsource(): from _pytest._code.source import findsource co = _pytest._code.compile("""if 1: @@ -470,6 +493,7 @@ class B(object): B.__name__ = "B2" assert getfslineno(B)[1] == -1 + def test_code_of_object_instance_with_call(): class A(object): pass @@ -494,10 +518,12 @@ def getstatement(lineno, source): ast, start, end = getstatementrange_ast(lineno, source) return source[start:end] + def test_oneline(): source = getstatement(0, "raise ValueError") assert str(source) == "raise ValueError" + def test_comment_and_no_newline_at_end(): from _pytest._code.source import getstatementrange_ast source = Source(['def test_basic_complex():', @@ -506,10 +532,12 @@ def test_comment_and_no_newline_at_end(): ast, start, end = getstatementrange_ast(1, source) assert end == 2 + def test_oneline_and_comment(): source = getstatement(0, "raise ValueError\n#hello") assert str(source) == "raise ValueError" + @pytest.mark.xfail(hasattr(sys, "pypy_version_info"), reason='does not work on pypy') def test_comments(): @@ -531,6 +559,7 @@ def test_comments(): assert str(getstatement(line, source)) == ' assert False' assert str(getstatement(10, source)) == '"""' + def test_comment_in_statement(): source = '''test(foo=1, # comment 1 @@ -540,14 +569,17 @@ def test_comment_in_statement(): assert str(getstatement(line, source)) == \ 'test(foo=1,\n # comment 1\n bar=2)' + def test_single_line_else(): source = getstatement(1, "if False: 2\nelse: 3") assert str(source) == "else: 3" + def test_single_line_finally(): source = getstatement(1, "try: 1\nfinally: 3") assert str(source) == "finally: 3" + def test_issue55(): source = ('def round_trip(dinp):\n assert 1 == dinp\n' 'def test_rt():\n round_trip("""\n""")\n') @@ -564,6 +596,7 @@ def XXXtest_multiline(): """) assert str(source) == "raise ValueError(\n 23\n)" + class TestTry(object): pytestmark = astonly source = """\ @@ -591,6 +624,7 @@ def test_else(self): source = getstatement(5, self.source) assert str(source) == " raise KeyError()" + class TestTryFinally(object): source = """\ try: @@ -636,6 +670,7 @@ def test_else(self): source = getstatement(5, self.source) assert str(source) == " y = 7" + def test_semicolon(): s = """\ hello ; pytest.skip() @@ -643,6 +678,7 @@ def test_semicolon(): source = getstatement(0, s) assert str(source) == s.strip() + def test_def_online(): s = """\ def func(): raise ValueError(42) @@ -653,6 +689,7 @@ def something(): source = getstatement(0, s) assert str(source) == "def func(): raise ValueError(42)" + def XXX_test_expression_multiline(): source = """\ something diff --git a/testing/freeze/tests/test_trivial.py b/testing/freeze/tests/test_trivial.py index f0f29ee60b7..45622b850bb 100644 --- a/testing/freeze/tests/test_trivial.py +++ b/testing/freeze/tests/test_trivial.py @@ -2,5 +2,6 @@ def test_upper(): assert 'foo'.upper() == 'FOO' + def test_lower(): assert 'FOO'.lower() == 'foo' diff --git a/testing/python/collect.py b/testing/python/collect.py index 9e9753bf002..a3699751325 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -870,6 +870,7 @@ def test_something(): result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines('*1 passed*') + def test_setup_only_available_in_subdir(testdir): sub1 = testdir.mkpydir("sub1") sub2 = testdir.mkpydir("sub2") @@ -896,6 +897,7 @@ def pytest_runtest_teardown(item): result = testdir.runpytest("-v", "-s") result.assert_outcomes(passed=2) + def test_modulecol_roundtrip(testdir): modcol = testdir.getmodulecol("pass", withinit=True) trail = modcol.nodeid @@ -1180,6 +1182,7 @@ def test_hello(): "*1 passed*", ]) + def test_customize_through_attributes(testdir): testdir.makeconftest(""" import pytest diff --git a/testing/python/fixture.py b/testing/python/fixture.py index af8e6a77ac2..19cfabd2028 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -7,6 +7,7 @@ from _pytest.fixtures import FixtureLookupError from _pytest import fixtures + def test_getfuncargnames(): def f(): pass assert not fixtures.getfuncargnames(f) @@ -28,6 +29,7 @@ def f(self, arg1, arg2="hello"): if sys.version_info < (3, 0): assert fixtures.getfuncargnames(A.f) == ('arg1',) + class TestFillFixtures(object): def test_fillfuncargs_exposed(self): # used by oejskit, kept for compatibility @@ -815,6 +817,7 @@ def test_1(arg): reprec = testdir.inline_run() reprec.assertoutcome(passed=2) + class TestRequestMarking(object): def test_applymarker(self, testdir): item1, item2 = testdir.getitems(""" @@ -875,6 +878,7 @@ def test_fun2(keywords): reprec = testdir.inline_run() reprec.assertoutcome(passed=2) + class TestRequestCachedSetup(object): def test_request_cachedsetup_defaultmodule(self, testdir): reprec = testdir.inline_runsource(""" @@ -1040,6 +1044,7 @@ def test_func(app): "*ZeroDivisionError*", ]) + class TestFixtureUsages(object): def test_noargfixturedec(self, testdir): testdir.makepyfile(""" @@ -2587,6 +2592,7 @@ def test_func(arg): reprec = testdir.inline_run() reprec.assertoutcome(passed=1) + class TestErrors(object): def test_subfactory_missing_funcarg(self, testdir): testdir.makepyfile(""" @@ -2651,6 +2657,7 @@ def test_something(): "*1 error*", ]) + class TestShowFixtures(object): def test_funcarg_compat(self, testdir): config = testdir.parseconfigure("--funcargs") @@ -2919,6 +2926,7 @@ def test_1(meow): result = testdir.runpytest("-s") result.stdout.fnmatch_lines("*mew*") + class TestParameterizedSubRequest(object): def test_call_from_fixture(self, testdir): testfile = testdir.makepyfile(""" diff --git a/testing/python/integration.py b/testing/python/integration.py index 6acc3de7ca2..1a98eae2a1c 100644 --- a/testing/python/integration.py +++ b/testing/python/integration.py @@ -76,6 +76,7 @@ def wrapped_func(x, y, z): fs2, lineno2 = python.getfslineno(wrap) assert lineno > lineno2, "getfslineno does not unwrap correctly" + class TestMockDecoration(object): def test_wrapped_getfuncargnames(self): from _pytest.compat import getfuncargnames @@ -246,6 +247,7 @@ def test_fix(fix): *2 passed* """) + def test_pytestconfig_is_session_scoped(): from _pytest.fixtures import pytestconfig assert pytestconfig._pytestfixturefunction.scope == "session" diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py index dad73d87022..1023e183a83 100644 --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -3,6 +3,7 @@ # 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)) @@ -17,6 +18,8 @@ def equal_with_bash(prefix, ffc, fc, out=None): # 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): @@ -36,6 +39,7 @@ def _wrapcall(*args, **kargs): except py.std.subprocess.CalledProcessError: return [] + class FilesCompleter(object): 'File completer class, optionally takes a list of allowed extensions' @@ -70,6 +74,7 @@ def __call__(self, prefix, **kwargs): completion += [f + '/' for f in anticomp] return completion + class TestArgComplete(object): @pytest.mark.skipif("sys.platform in ('win32', 'darwin')") def test_compare_with_compgen(self): diff --git a/testing/test_assertion.py b/testing/test_assertion.py index e5eff7e03b5..a5174cc8cd4 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -283,6 +283,7 @@ def test_check(list): "*test_check*PASS*", ]) + def callequal(left, right, verbose=False): config = mock_config() config.verbose = verbose @@ -712,6 +713,7 @@ def test_rewritten(): *1 failed* """) + def test_rewritten(testdir): testdir.makepyfile(""" def test_rewritten(): @@ -719,11 +721,13 @@ def test_rewritten(): """) 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', '? +++'] + def test_pytest_assertrepr_compare_integration(testdir): testdir.makepyfile(""" def test_hello(): @@ -740,6 +744,7 @@ def test_hello(): "*E*50*", ]) + def test_sequence_comparison_uses_repr(testdir): testdir.makepyfile(""" def test_hello(): @@ -791,6 +796,7 @@ def test_hello(): result = testdir.runpytest_subprocess("--assert=plain") assert "3 == 4" not in result.stdout.str() + def test_triple_quoted_string_issue113(testdir): testdir.makepyfile(""" def test_hello(): @@ -802,6 +808,7 @@ def test_hello(): ]) assert 'SyntaxError' not in result.stdout.str() + def test_traceback_failure(testdir): p1 = testdir.makepyfile(""" def g(): @@ -893,6 +900,7 @@ def test_warn_missing(testdir): "*WARNING*assert statements are not executed*", ]) + def test_recursion_source_decode(testdir): testdir.makepyfile(""" def test_something(): @@ -907,6 +915,7 @@ def test_something(): """) + def test_AssertionError_message(testdir): testdir.makepyfile(""" def test_hello(): @@ -920,6 +929,7 @@ def test_hello(): *AssertionError: (1, 2)* """) + @pytest.mark.skipif(PY3, reason='This bug does not exist on PY3') def test_set_with_unsortable_elements(): # issue #718 @@ -956,6 +966,7 @@ def __hash__(self): """).strip() assert '\n'.join(expl) == dedent + def test_diff_newline_at_end(monkeypatch, testdir): testdir.makepyfile(r""" def test_diff(): @@ -970,6 +981,7 @@ def test_diff(): * ? + """) + def test_assert_tuple_warning(testdir): testdir.makepyfile(""" def test_tuple(): @@ -981,6 +993,7 @@ def test_tuple(): '*assertion is always true*', ]) + def test_assert_indirect_tuple_no_warning(testdir): testdir.makepyfile(""" def test_tuple(): @@ -991,6 +1004,7 @@ def test_tuple(): output = '\n'.join(result.stdout.lines) assert 'WR1' not in output + def test_assert_with_unicode(monkeypatch, testdir): testdir.makepyfile(u""" # -*- coding: utf-8 -*- @@ -1000,6 +1014,7 @@ def test_unicode(): result = testdir.runpytest() result.stdout.fnmatch_lines(['*AssertionError*']) + def test_raise_unprintable_assertion_error(testdir): testdir.makepyfile(r""" def test_raise_assertion_error(): @@ -1008,6 +1023,7 @@ def test_raise_assertion_error(): result = testdir.runpytest() result.stdout.fnmatch_lines([r"> raise AssertionError('\xff')", 'E AssertionError: *']) + def test_raise_assertion_error_raisin_repr(testdir): testdir.makepyfile(u""" class RaisingRepr(object): @@ -1019,6 +1035,7 @@ def test_raising_repr(): result = testdir.runpytest() result.stdout.fnmatch_lines(['E AssertionError: ']) + def test_issue_1944(testdir): testdir.makepyfile(""" def f(): diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 66af5414e85..72bc9aec214 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -24,6 +24,7 @@ def setup_module(mod): mod._old_reprcompare = util._reprcompare _pytest._code._reprcompare = None + def teardown_module(mod): util._reprcompare = mod._old_reprcompare del mod._old_reprcompare @@ -34,6 +35,7 @@ def rewrite(src): 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(_pytest._code.Code(f).source().lines) diff --git a/testing/test_cache.py b/testing/test_cache.py index 600b5e6d9fc..231a4e53d64 100755 --- a/testing/test_cache.py +++ b/testing/test_cache.py @@ -8,6 +8,7 @@ pytest_plugins = "pytester", + class TestNewAPI(object): def test_config_cache_makedir(self, testdir): testdir.makeini("[pytest]") diff --git a/testing/test_capture.py b/testing/test_capture.py index 4b495ed2ccd..326596ee58c 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -53,6 +53,7 @@ def oswritebytes(fd, 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) @@ -705,6 +706,7 @@ def tmpfile(testdir): if not f.closed: f.close() + @needsosdup def test_dupfile(tmpfile): flist = [] @@ -723,12 +725,14 @@ def test_dupfile(tmpfile): 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") @@ -1052,6 +1056,7 @@ def test_fdcapture_tmpfile_remains_the_same(tmpfile, use): capfile2 = cap.err.tmpfile assert capfile2 == capfile + @needsosdup def test_close_and_capture_again(testdir): testdir.makepyfile(""" diff --git a/testing/test_collection.py b/testing/test_collection.py index 49bfc2a5648..56a985bf159 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -3,6 +3,7 @@ from _pytest.main import Session, EXIT_NOTESTSCOLLECTED + class TestCollector(object): def test_collect_versus_item(self): from pytest import Collector, Item @@ -102,6 +103,7 @@ def test_foo(): '*no tests ran in*', ]) + class TestCollectFS(object): def test_ignored_certain_directories(self, testdir): tmpdir = testdir.tmpdir @@ -334,6 +336,7 @@ def pytest_collect_file(path, parent): "*test_x*" ]) + class TestSession(object): def test_parsearg(self, testdir): p = testdir.makepyfile("def test_func(): pass") @@ -510,6 +513,7 @@ def test_method(self): # ensure we are reporting the collection of the single test item (#2464) assert [x.name for x in self.get_reported_items(hookrec)] == ['test_method'] + class Test_getinitialnodes(object): def test_global_file(self, testdir, tmpdir): x = tmpdir.ensure("x.py") @@ -537,6 +541,7 @@ def test_pkgfile(self, testdir): for col in col.listchain(): assert col.config is config + class Test_genitems(object): def test_check_collect_hashes(self, testdir): p = testdir.makepyfile(""" @@ -689,6 +694,7 @@ def test_4(): """, ) + def test_exit_on_collection_error(testdir): """Verify that all collection errors are collected and no tests executed""" testdir.makepyfile(**COLLECTION_ERROR_PY_FILES) diff --git a/testing/test_config.py b/testing/test_config.py index b30675c04d2..7c6b7d6bc91 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -5,6 +5,7 @@ from _pytest.config import getcfg, get_common_ancestor, determine_setup from _pytest.main import EXIT_NOTESTSCOLLECTED + class TestParseIni(object): @pytest.mark.parametrize('section, filename', @@ -85,6 +86,7 @@ def test_confcutdir(self, testdir): result = testdir.inline_run("--confcutdir=.") assert result.ret == 0 + class TestConfigCmdlineParsing(object): def test_parsing_again_fails(self, testdir): config = testdir.parseconfig() @@ -116,6 +118,7 @@ def test_absolute_win32_path(self, testdir): ret = pytest.main("-c " + temp_cfg_file) assert ret == _pytest.main.EXIT_OK + class TestConfigAPI(object): def test_config_trace(self, testdir): config = testdir.parseconfig() @@ -472,6 +475,7 @@ def load(self): plugin = config.pluginmanager.getplugin("mytestplugin") assert plugin is None + def test_cmdline_processargs_simple(testdir): testdir.makeconftest(""" def pytest_cmdline_preparse(args): @@ -483,6 +487,7 @@ def pytest_cmdline_preparse(args): "*-h*", ]) + def test_invalid_options_show_extra_information(testdir): """display extra information when pytest exits due to unrecognized options in the command-line""" @@ -528,6 +533,7 @@ def test_toolongargs_issue224(testdir): result = testdir.runpytest("-m", "hello" * 500) assert result.ret == EXIT_NOTESTSCOLLECTED + def test_config_in_subdirectory_colon_command_line_issue2148(testdir): conftest_source = ''' def pytest_addoption(parser): @@ -643,6 +649,7 @@ def test_hello(fix): *hello* """) + class TestRootdir(object): def test_simple_noini(self, tmpdir): assert get_common_ancestor([tmpdir]) == tmpdir diff --git a/testing/test_conftest.py b/testing/test_conftest.py index bbb5bd496e5..05453f766a2 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -19,11 +19,13 @@ def basedir(request, tmpdir_factory): tmpdir.ensure("adir/b/__init__.py") return tmpdir + def ConftestWithSetinitial(path): conftest = PytestPluginManager() conftest_setinitial(conftest, [path]) return conftest + def conftest_setinitial(conftest, args, confcutdir=None): class Namespace(object): def __init__(self): @@ -32,6 +34,7 @@ def __init__(self): self.noconftest = False conftest._set_initial_conftests(Namespace()) + class TestConftestValueAccessGlobal(object): def test_basic_init(self, basedir): conftest = PytestPluginManager() @@ -70,6 +73,7 @@ def test_value_access_with_confmod(self, basedir): 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") @@ -77,6 +81,7 @@ def test_conftest_in_nonpkg_with_init(tmpdir): 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() @@ -85,6 +90,7 @@ def test_doubledash_considered(testdir): l = conftest._getconftestmodules(conf) assert len(l) == 1 + def test_issue151_load_all_conftests(testdir): names = "code proj src".split() for name in names: @@ -96,6 +102,7 @@ def test_issue151_load_all_conftests(testdir): d = list(conftest._conftestpath2mod.values()) assert len(d) == len(names) + def test_conftest_global_import(testdir): testdir.makeconftest("x=3") p = testdir.makepyfile(""" @@ -117,6 +124,7 @@ def test_conftest_global_import(testdir): res = testdir.runpython(p) assert res.ret == 0 + def test_conftestcutdir(testdir): conf = testdir.makeconftest("") p = testdir.mkdir("x") @@ -136,6 +144,7 @@ def test_conftestcutdir(testdir): assert len(l) == 1 assert l[0].__file__.startswith(str(conf)) + def test_conftestcutdir_inplace_considered(testdir): conf = testdir.makeconftest("") conftest = PytestPluginManager() @@ -144,6 +153,7 @@ def test_conftestcutdir_inplace_considered(testdir): 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) @@ -157,6 +167,7 @@ def test_setinitial_conftest_subdirs(testdir, name): assert subconftest not in conftest._conftestpath2mod assert len(conftest._conftestpath2mod) == 0 + def test_conftest_confcutdir(testdir): testdir.makeconftest("assert 0") x = testdir.mkdir("x") @@ -168,6 +179,7 @@ def pytest_addoption(parser): result.stdout.fnmatch_lines(["*--xyz*"]) assert 'warning: could not load initial' not in result.stdout.str() + def test_no_conftest(testdir): testdir.makeconftest("assert 0") result = testdir.runpytest("--noconftest") @@ -176,6 +188,7 @@ def test_no_conftest(testdir): result = testdir.runpytest() assert result.ret == EXIT_USAGEERROR + def test_conftest_existing_resultlog(testdir): x = testdir.mkdir("tests") x.join("conftest.py").write(_pytest._code.Source(""" @@ -186,6 +199,7 @@ def pytest_addoption(parser): 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(_pytest._code.Source(""" @@ -196,6 +210,7 @@ def pytest_addoption(parser): 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") diff --git a/testing/test_helpconfig.py b/testing/test_helpconfig.py index 3d216b3bc6c..845005a0575 100644 --- a/testing/test_helpconfig.py +++ b/testing/test_helpconfig.py @@ -2,6 +2,7 @@ from _pytest.main import EXIT_NOTESTSCOLLECTED import pytest + def test_version(testdir, pytestconfig): result = testdir.runpytest("--version") assert result.ret == 0 @@ -15,6 +16,7 @@ def test_version(testdir, pytestconfig): "*at*", ]) + def test_help(testdir): result = testdir.runpytest("--help") assert result.ret == 0 @@ -26,6 +28,7 @@ def test_help(testdir): *to see*fixtures*pytest --fixtures* """) + def test_hookvalidation_unknown(testdir): testdir.makeconftest(""" def pytest_hello(xyz): @@ -37,6 +40,7 @@ def pytest_hello(xyz): '*unknown hook*pytest_hello*' ]) + def test_hookvalidation_optional(testdir): testdir.makeconftest(""" import pytest @@ -47,6 +51,7 @@ def pytest_hello(xyz): result = testdir.runpytest() assert result.ret == EXIT_NOTESTSCOLLECTED + def test_traceconfig(testdir): result = testdir.runpytest("--traceconfig") result.stdout.fnmatch_lines([ @@ -54,12 +59,14 @@ def test_traceconfig(testdir): "*active plugins*", ]) + def test_debug(testdir, monkeypatch): result = testdir.runpytest_subprocess("--debug") assert result.ret == EXIT_NOTESTSCOLLECTED p = testdir.tmpdir.join("pytestdebug.log") assert "pytest_sessionstart" in p.read() + def test_PYTEST_DEBUG(testdir, monkeypatch): monkeypatch.setenv("PYTEST_DEBUG", "1") result = testdir.runpytest_subprocess() diff --git a/testing/test_junitxml.py b/testing/test_junitxml.py index af6eabf983f..b604c02a3de 100644 --- a/testing/test_junitxml.py +++ b/testing/test_junitxml.py @@ -600,6 +600,7 @@ def test_function(arg): assert "hello-stdout call" in systemout.toxml() assert "hello-stdout teardown" in systemout.toxml() + def test_mangle_test_address(): from _pytest.junitxml import mangle_test_address address = '::'.join( @@ -760,11 +761,13 @@ def test_pass(): assert result.ret == 0 assert testdir.tmpdir.join("path/to/results.xml").check() + def test_logxml_check_isdir(testdir): """Give an error if --junit-xml is a directory (#2089)""" result = testdir.runpytest("--junit-xml=.") result.stderr.fnmatch_lines(["*--junitxml must be a filename*"]) + def test_escaped_parametrized_names_xml(testdir): testdir.makepyfile(""" import pytest diff --git a/testing/test_mark.py b/testing/test_mark.py index 7a437b4a3b5..4e05d5a5cc0 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -5,6 +5,7 @@ import pytest from _pytest.mark import MarkGenerator as Mark, ParameterSet + class TestMark(object): def test_markinfo_repr(self): from _pytest.mark import MarkInfo, Mark @@ -140,6 +141,7 @@ def test_markers(pytestconfig): rec = testdir.inline_run() rec.assertoutcome(passed=1) + def test_markers_option(testdir): testdir.makeini(""" [pytest] @@ -153,6 +155,7 @@ def test_markers_option(testdir): "*a1some*another marker", ]) + def test_markers_option_with_plugin_in_current_dir(testdir): testdir.makeconftest('pytest_plugins = "flip_flop"') testdir.makepyfile(flip_flop="""\ @@ -186,6 +189,7 @@ def test_hello(): reprec = testdir.inline_run() reprec.assertoutcome(passed=1) + def test_strict_prohibits_unregistered_markers(testdir): testdir.makepyfile(""" import pytest @@ -199,6 +203,7 @@ def test_hello(): "*unregisteredmark*not*registered*", ]) + @pytest.mark.parametrize("spec", [ ("xyz", ("test_one",)), ("xyz and xyz2", ()), @@ -222,6 +227,7 @@ def test_two(): assert len(passed) == len(passed_result) assert list(passed) == list(passed_result) + @pytest.mark.parametrize("spec", [ ("interface", ("test_interface",)), ("not interface", ("test_nointer",)), @@ -247,6 +253,7 @@ def test_nointer(): assert len(passed) == len(passed_result) assert list(passed) == list(passed_result) + @pytest.mark.parametrize("spec", [ ("interface", ("test_interface",)), ("not interface", ("test_nointer", "test_pass")), diff --git a/testing/test_monkeypatch.py b/testing/test_monkeypatch.py index 789c8d1e717..4427908ab3b 100644 --- a/testing/test_monkeypatch.py +++ b/testing/test_monkeypatch.py @@ -319,6 +319,7 @@ def test_issue156_undo_staticmethod(Sample): monkeypatch.undo() assert Sample.hello() + def test_issue1338_name_resolving(): pytest.importorskip('requests') monkeypatch = MonkeyPatch() diff --git a/testing/test_nose.py b/testing/test_nose.py index 798badc1c9e..872922ed462 100644 --- a/testing/test_nose.py +++ b/testing/test_nose.py @@ -1,9 +1,11 @@ from __future__ import absolute_import, division, print_function import pytest + def setup_module(mod): mod.nose = pytest.importorskip("nose") + def test_nose_setup(testdir): p = testdir.makepyfile(""" l = [] @@ -44,6 +46,7 @@ class A(object): call_optional(A(), "f") + def test_nose_setup_func(testdir): p = testdir.makepyfile(""" from nose.tools import with_setup @@ -112,6 +115,7 @@ def test_hello(): reprec = testdir.inline_run() reprec.assertoutcome(passed=1) + def test_nose_setup_partial(testdir): pytest.importorskip("functools") p = testdir.makepyfile(""" @@ -266,6 +270,7 @@ def test_world(): "*2 passed*", ]) + def test_nose_setup_ordering(testdir): testdir.makepyfile(""" def setup_module(mod): @@ -305,6 +310,7 @@ def test_fun(self): result = testdir.runpytest() result.assert_outcomes(passed=1) + def test_setup_teardown_linking_issue265(testdir): # we accidentally didnt integrate nose setupstate with normal setupstate # this test ensures that won't happen again @@ -352,6 +358,7 @@ def test_skipping(): reprec = testdir.inline_run() reprec.assertoutcome(skipped=1) + def test_istest_function_decorator(testdir): p = testdir.makepyfile(""" import nose.tools @@ -362,6 +369,7 @@ def not_test_prefix(): result = testdir.runpytest(p) result.assert_outcomes(passed=1) + def test_nottest_function_decorator(testdir): testdir.makepyfile(""" import nose.tools @@ -374,6 +382,7 @@ def test_prefix(): calls = reprec.getreports("pytest_runtest_logreport") assert not calls + def test_istest_class_decorator(testdir): p = testdir.makepyfile(""" import nose.tools @@ -385,6 +394,7 @@ def test_method(self): result = testdir.runpytest(p) result.assert_outcomes(passed=1) + def test_nottest_class_decorator(testdir): testdir.makepyfile(""" import nose.tools diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index 104d66083d8..de386f4e9be 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -4,10 +4,12 @@ import py, pytest from _pytest import config as parseopt + @pytest.fixture def parser(): return parseopt.Parser() + class TestParser(object): def test_no_help_by_default(self, capsys): parser = parseopt.Parser(usage="xyz") diff --git a/testing/test_pastebin.py b/testing/test_pastebin.py index d8610ea180a..6b1742d1415 100644 --- a/testing/test_pastebin.py +++ b/testing/test_pastebin.py @@ -3,6 +3,7 @@ import sys import pytest + class TestPasteCapture(object): @pytest.fixture diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index d1e1ff2de95..be7980c261c 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -12,6 +12,7 @@ def pytestpm(): return PytestPluginManager() + class TestPytestPluginInteractions(object): def test_addhooks_conftestplugin(self, testdir): testdir.makepyfile(newhooks=""" @@ -197,6 +198,7 @@ def test_namespace_has_default_and_env_plugins(testdir): result = testdir.runpython(p) assert result.ret == 0 + def test_default_markers(testdir): result = testdir.runpytest("--markers") result.stdout.fnmatch_lines([ diff --git a/testing/test_pytester.py b/testing/test_pytester.py index 9d0a3ef7096..0e866969807 100644 --- a/testing/test_pytester.py +++ b/testing/test_pytester.py @@ -64,6 +64,7 @@ def test_parseconfig(testdir): assert config2 != config1 assert config1 != pytest.config + def test_testdir_runs_with_plugin(testdir): testdir.makepyfile(""" pytest_plugins = "pytester" @@ -118,6 +119,7 @@ def test_makepyfile_unicode(testdir): unichr = chr testdir.makepyfile(unichr(0xfffd)) + def test_inline_run_clean_modules(testdir): test_mod = testdir.makepyfile("def test_foo(): assert True") result = testdir.inline_run(str(test_mod)) @@ -127,6 +129,7 @@ def test_inline_run_clean_modules(testdir): result2 = testdir.inline_run(str(test_mod)) assert result2.ret == EXIT_TESTSFAILED + def test_assert_outcomes_after_pytest_erro(testdir): testdir.makepyfile("def test_foo(): assert True") diff --git a/testing/test_resultlog.py b/testing/test_resultlog.py index 86ae5ab392a..b7dd2687cdf 100644 --- a/testing/test_resultlog.py +++ b/testing/test_resultlog.py @@ -32,6 +32,7 @@ def test_generic_path(testdir): res = generic_path(item) assert res == 'test/a:B().c[1]' + def test_write_log_entry(): reslog = ResultLog(None, None) reslog.logfile = py.io.TextIO() @@ -176,6 +177,7 @@ def test_xfail_norun(): "x *:test_xfail_norun", ]) + def test_makedir_for_resultlog(testdir, LineMatcher): """--resultlog should automatically create directories for the log file""" testdir.plugins.append("resultlog") diff --git a/testing/test_runner.py b/testing/test_runner.py index 26e6816cb20..0d2ca7ee139 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -8,6 +8,7 @@ import sys from _pytest import runner, main + class TestSetupState(object): def test_setup(self, testdir): ss = runner.SetupState() @@ -316,6 +317,7 @@ def test_func(): else: pytest.fail("did not raise") + class TestExecutionNonForked(BaseFunctionalTests): def getrunner(self): def f(item): @@ -333,6 +335,7 @@ def test_func(): else: pytest.fail("did not raise") + class TestExecutionForked(BaseFunctionalTests): pytestmark = pytest.mark.skipif("not hasattr(os, 'fork')") @@ -351,6 +354,7 @@ def test_func(): assert rep.failed assert rep.when == "???" + class TestSessionReports(object): def test_collect_result(self, testdir): col = testdir.getmodulecol(""" @@ -380,6 +384,7 @@ class TestClass(object): runner.CollectReport, ] + @pytest.mark.parametrize('reporttype', reporttypes, ids=[x.__name__ for x in reporttypes]) def test_report_extra_parameters(reporttype): if hasattr(py.std.inspect, 'signature'): @@ -390,6 +395,7 @@ def test_report_extra_parameters(reporttype): report = reporttype(newthing=1, **basekw) assert report.newthing == 1 + def test_callinfo(): ci = runner.CallInfo(lambda: 0, '123') assert ci.when == "123" @@ -403,6 +409,8 @@ def test_callinfo(): # design question: do we want general hooks in python files? # then something like the following functional tests makes sense + + @pytest.mark.xfail def test_runtest_in_module_ordering(testdir): p1 = testdir.makepyfile(""" @@ -439,6 +447,7 @@ def test_outcomeexception_exceptionattributes(): outcome = runner.OutcomeException('test') assert outcome.args[0] == outcome.msg + def test_pytest_exit(): try: pytest.exit("hello") @@ -446,6 +455,7 @@ def test_pytest_exit(): excinfo = _pytest._code.ExceptionInfo() assert excinfo.errisinstance(KeyboardInterrupt) + def test_pytest_fail(): try: pytest.fail("hello") @@ -454,6 +464,7 @@ def test_pytest_fail(): s = excinfo.exconly(tryshort=True) assert s.startswith("Failed") + def test_pytest_exit_msg(testdir): testdir.makeconftest(""" import pytest @@ -466,6 +477,7 @@ def pytest_configure(config): "Exit: oh noes", ]) + def test_pytest_fail_notrace(testdir): testdir.makepyfile(""" import pytest @@ -531,6 +543,7 @@ def test_exception_printing_skip(): s = excinfo.exconly(tryshort=True) assert s.startswith("Skipped") + def test_importorskip(monkeypatch): importorskip = pytest.importorskip @@ -561,10 +574,12 @@ def f(): print(_pytest._code.ExceptionInfo()) pytest.fail("spurious skip") + def test_importorskip_imports_last_module_part(): ospath = pytest.importorskip("os.path") assert os.path == ospath + def test_importorskip_dev_module(monkeypatch): try: mod = py.std.types.ModuleType("mockmodule") diff --git a/testing/test_runner_xunit.py b/testing/test_runner_xunit.py index 676d119ffa1..f01eaca1336 100644 --- a/testing/test_runner_xunit.py +++ b/testing/test_runner_xunit.py @@ -36,6 +36,7 @@ def test_module(self): rep = reprec.matchreport("test_module") assert rep.passed + def test_module_setup_failure_no_teardown(testdir): reprec = testdir.inline_runsource(""" l = [] @@ -53,6 +54,7 @@ def teardown_module(module): calls = reprec.getcalls("pytest_runtest_setup") assert calls[0].item.module.l == [1] + def test_setup_function_failure_no_teardown(testdir): reprec = testdir.inline_runsource(""" modlevel = [] @@ -69,6 +71,7 @@ def test_func(): calls = reprec.getcalls("pytest_runtest_setup") assert calls[0].item.module.modlevel == [1] + def test_class_setup(testdir): reprec = testdir.inline_runsource(""" class TestSimpleClassSetup(object): @@ -92,6 +95,7 @@ def test_cleanup(): """) reprec.assertoutcome(passed=1 + 2 + 1) + def test_class_setup_failure_no_teardown(testdir): reprec = testdir.inline_runsource(""" class TestSimpleClassSetup(object): @@ -110,6 +114,7 @@ def test_cleanup(): """) reprec.assertoutcome(failed=1, passed=1) + def test_method_setup(testdir): reprec = testdir.inline_runsource(""" class TestSetupMethod(object): @@ -126,6 +131,7 @@ def test_other(self): """) reprec.assertoutcome(passed=2) + def test_method_setup_failure_no_teardown(testdir): reprec = testdir.inline_runsource(""" class TestMethodSetup(object): @@ -145,6 +151,7 @@ def test_cleanup(): """) reprec.assertoutcome(failed=1, passed=1) + def test_method_generator_setup(testdir): reprec = testdir.inline_runsource(""" class TestSetupTeardownOnInstance(object): @@ -167,6 +174,7 @@ def generated(self, value): """) reprec.assertoutcome(passed=1, failed=1) + def test_func_generator_setup(testdir): reprec = testdir.inline_runsource(""" import sys @@ -195,6 +203,7 @@ def check(): rep = reprec.matchreport("test_one", names="pytest_runtest_logreport") assert rep.passed + def test_method_setup_uses_fresh_instances(testdir): reprec = testdir.inline_runsource(""" class TestSelfState1(object): @@ -207,6 +216,7 @@ def test_afterhello(self): """) reprec.assertoutcome(passed=2, failed=0) + def test_setup_that_skips_calledagain(testdir): p = testdir.makepyfile(""" import pytest @@ -220,6 +230,7 @@ def test_function2(): reprec = testdir.inline_run(p) reprec.assertoutcome(skipped=2) + def test_setup_fails_again_on_all_tests(testdir): p = testdir.makepyfile(""" import pytest @@ -233,6 +244,7 @@ def test_function2(): reprec = testdir.inline_run(p) reprec.assertoutcome(failed=2) + def test_setup_funcarg_setup_when_outer_scope_fails(testdir): p = testdir.makepyfile(""" import pytest diff --git a/testing/test_session.py b/testing/test_session.py index 53f23df3c1d..39a9769f100 100644 --- a/testing/test_session.py +++ b/testing/test_session.py @@ -3,6 +3,7 @@ from _pytest.main import EXIT_NOTESTSCOLLECTED + class SessionTests(object): def test_basic_testitem_events(self, testdir): tfile = testdir.makepyfile(""" @@ -135,6 +136,7 @@ def test_one(): pass assert len(reports) == 1 assert reports[0].skipped + class TestNewSession(SessionTests): def test_order_of_execution(self, testdir): @@ -215,12 +217,14 @@ def test_plugin_specify(testdir): # "config.do_configure(config)" # ) + def test_plugin_already_exists(testdir): config = testdir.parseconfig("-p", "terminal") assert config.option.plugins == ['terminal'] config._do_configure() config._ensure_unconfigure() + def test_exclude(testdir): hellodir = testdir.mkdir("hello") hellodir.join("test_hello.py").write("x y syntaxerror") @@ -231,6 +235,7 @@ def test_exclude(testdir): assert result.ret == 0 result.stdout.fnmatch_lines(["*1 passed*"]) + def test_sessionfinish_with_start(testdir): testdir.makeconftest(""" import os diff --git a/testing/test_skipping.py b/testing/test_skipping.py index 3c92105d699..586244f2323 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -582,6 +582,7 @@ def test_hello(): "*1 skipped*", ]) + class TestSkipif(object): def test_skipif_conditional(self, testdir): item = testdir.getitem(""" @@ -687,6 +688,7 @@ class X(object): assert lineno == lineno assert reason == message + def test_skipped_reasons_functional(testdir): testdir.makepyfile( test_one=""" @@ -711,6 +713,7 @@ def doskip(): ]) assert result.ret == 0 + def test_reportchars(testdir): testdir.makepyfile(""" import pytest @@ -733,6 +736,7 @@ def test_4(): "SKIP*four*", ]) + def test_reportchars_error(testdir): testdir.makepyfile( conftest=""" @@ -748,6 +752,7 @@ def test_foo(): 'ERROR*test_foo*', ]) + def test_reportchars_all(testdir): testdir.makepyfile(""" import pytest @@ -770,6 +775,7 @@ def test_4(): "XPASS*test_3*", ]) + def test_reportchars_all_error(testdir): testdir.makepyfile( conftest=""" @@ -785,6 +791,7 @@ def test_foo(): 'ERROR*test_foo*', ]) + @pytest.mark.xfail("hasattr(sys, 'pypy_version_info')") def test_errors_in_xfail_skip_expressions(testdir): testdir.makepyfile(""" @@ -816,6 +823,7 @@ def test_func(): "*1 pass*2 error*", ]) + def test_xfail_skipif_with_globals(testdir): testdir.makepyfile(""" import pytest @@ -834,6 +842,7 @@ def test_boolean(): "*x == 3*", ]) + def test_direct_gives_error(testdir): testdir.makepyfile(""" import pytest @@ -854,6 +863,7 @@ def test_default_markers(testdir): "*xfail(*condition, reason=None, run=True, raises=None, strict=False)*expected failure*", ]) + def test_xfail_test_setup_exception(testdir): testdir.makeconftest(""" def pytest_runtest_setup(): @@ -870,6 +880,7 @@ def test_func(): assert 'xfailed' in result.stdout.str() assert 'xpassed' not in result.stdout.str() + def test_imperativeskip_on_xfail_test(testdir): testdir.makepyfile(""" import pytest @@ -893,6 +904,7 @@ def pytest_runtest_setup(item): *2 skipped* """) + class TestBooleanCondition(object): def test_skipif(self, testdir): testdir.makepyfile(""" diff --git a/testing/test_terminal.py b/testing/test_terminal.py index a1e480a66eb..43028fc4656 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -31,6 +31,7 @@ def args(self): l.append('--fulltrace') return l + def pytest_generate_tests(metafunc): if "option" in metafunc.fixturenames: metafunc.addcall(id="default", @@ -320,6 +321,7 @@ def test_repr_python_version(monkeypatch): finally: monkeypatch.undo() # do this early as pytest can get confused + class TestFixtureReporting(object): def test_setup_fixture_error(self, testdir): testdir.makepyfile(""" @@ -405,6 +407,7 @@ def teardown_function(function): "*1 failed*", ]) + class TestTerminalFunctional(object): def test_deselected(self, testdir): testpath = testdir.makepyfile(""" @@ -552,11 +555,13 @@ def test_fail_extra_reporting(testdir): "FAIL*test_fail_extra_reporting*", ]) + def test_fail_reporting_on_pass(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest('-rf') assert 'short test summary' not in result.stdout.str() + def test_pass_extra_reporting(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest() @@ -567,11 +572,13 @@ def test_pass_extra_reporting(testdir): "PASS*test_pass_extra_reporting*", ]) + def test_pass_reporting_on_fail(testdir): testdir.makepyfile("def test_this(): assert 0") result = testdir.runpytest('-rp') assert 'short test summary' not in result.stdout.str() + def test_pass_output_reporting(testdir): testdir.makepyfile(""" def test_pass_output(): @@ -584,6 +591,7 @@ def test_pass_output(): "Four score and seven years ago...", ]) + def test_color_yes(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest('--color=yes') @@ -660,6 +668,7 @@ def test_opt(tr): "*1 passed*" ]) + def test_tbstyle_short(testdir): p = testdir.makepyfile(""" import pytest @@ -685,6 +694,7 @@ def test_opt(arg): assert 'x = 0' in s assert 'assert x' in s + def test_traceconfig(testdir, monkeypatch): result = testdir.runpytest("--traceconfig") result.stdout.fnmatch_lines([ @@ -788,6 +798,7 @@ def pytest_report_header(config, startdir): str(testdir.tmpdir), ]) + @pytest.mark.xfail("not hasattr(os, 'dup')") def test_fdopen_kept_alive_issue124(testdir): testdir.makepyfile(""" @@ -806,6 +817,7 @@ def test_close_kept_alive_file(): "*2 passed*" ]) + def test_tbstyle_native_setup_error(testdir): testdir.makepyfile(""" import pytest @@ -821,6 +833,7 @@ def test_error_fixture(setup_error_fixture): '*File *test_tbstyle_native_setup_error.py", line *, in setup_error_fixture*' ]) + def test_terminal_summary(testdir): testdir.makeconftest(""" def pytest_terminal_summary(terminalreporter, exitstatus): diff --git a/testing/test_tmpdir.py b/testing/test_tmpdir.py index ccd70ed8bb0..467e77252e7 100644 --- a/testing/test_tmpdir.py +++ b/testing/test_tmpdir.py @@ -5,6 +5,7 @@ from _pytest.tmpdir import tmpdir + def test_funcarg(testdir): testdir.makepyfile(""" def pytest_generate_tests(metafunc): @@ -29,12 +30,14 @@ def test_func(tmpdir): pass bn = p.basename.strip("0123456789") assert bn == "qwe__abc" + def test_ensuretemp(recwarn): d1 = pytest.ensuretemp('hello') d2 = pytest.ensuretemp('hello') assert d1 == d2 assert d1.check(dir=1) + class TestTempdirHandler(object): def test_mktemp(self, testdir): from _pytest.tmpdir import TempdirFactory @@ -49,6 +52,7 @@ def test_mktemp(self, testdir): assert tmp2.relto(t.getbasetemp()).startswith("this") assert tmp2 != tmp + class TestConfigTmpdir(object): def test_getbasetemp_custom_removes_old(self, testdir): mytemp = testdir.tmpdir.join("xyz") @@ -76,6 +80,7 @@ def test_1(): assert result.ret == 0 assert mytemp.join('hello').check() + @pytest.mark.skipif(not hasattr(py.path.local, 'mksymlinkto'), reason="symlink not available on this platform") def test_tmpdir_always_is_realpath(testdir): diff --git a/testing/test_unittest.py b/testing/test_unittest.py index b3a06cb5a13..b869ec4ad1c 100644 --- a/testing/test_unittest.py +++ b/testing/test_unittest.py @@ -3,6 +3,7 @@ import pytest import gc + def test_simple_unittest(testdir): testpath = testdir.makepyfile(""" import unittest @@ -16,6 +17,7 @@ def test_failing(self): assert reprec.matchreport("testpassing").passed assert reprec.matchreport("test_failing").failed + def test_runTest_method(testdir): testdir.makepyfile(""" import unittest @@ -35,6 +37,7 @@ def test_something(self): *2 passed* """) + def test_isclasscheck_issue53(testdir): testpath = testdir.makepyfile(""" import unittest @@ -46,6 +49,7 @@ def __getattr__(self, tag): result = testdir.runpytest(testpath) assert result.ret == EXIT_NOTESTSCOLLECTED + def test_setup(testdir): testpath = testdir.makepyfile(""" import unittest @@ -66,6 +70,7 @@ def teardown_method(self, method): rep = reprec.matchreport("test_both", when="teardown") assert rep.failed and '42' in str(rep.longrepr) + def test_setUpModule(testdir): testpath = testdir.makepyfile(""" l = [] @@ -87,6 +92,7 @@ def test_world(): "*2 passed*", ]) + def test_setUpModule_failing_no_teardown(testdir): testpath = testdir.makepyfile(""" l = [] @@ -105,6 +111,7 @@ def test_hello(): call = reprec.getcalls("pytest_runtest_setup")[0] assert not call.item.module.l + def test_new_instances(testdir): testpath = testdir.makepyfile(""" import unittest @@ -117,6 +124,7 @@ def test_func2(self): reprec = testdir.inline_run(testpath) reprec.assertoutcome(passed=2) + def test_teardown(testdir): testpath = testdir.makepyfile(""" import unittest @@ -136,6 +144,7 @@ def test_check(self): assert passed == 2 assert passed + skipped + failed == 2 + def test_teardown_issue1649(testdir): """ Are TestCase objects cleaned up? Often unittest TestCase objects set @@ -158,6 +167,7 @@ def test_demo(self): for obj in gc.get_objects(): assert type(obj).__name__ != 'TestCaseObjectsShouldBeCleanedUp' + @pytest.mark.skipif("sys.version_info < (2,7)") def test_unittest_skip_issue148(testdir): testpath = testdir.makepyfile(""" @@ -177,6 +187,7 @@ def tearDownClass(self): reprec = testdir.inline_run(testpath) reprec.assertoutcome(skipped=1) + def test_method_and_teardown_failing_reporting(testdir): testdir.makepyfile(""" import unittest, pytest @@ -196,6 +207,7 @@ def test_method(self): "*1 failed*1 error*", ]) + def test_setup_failure_is_shown(testdir): testdir.makepyfile(""" import unittest @@ -216,6 +228,7 @@ def test_method(self): ]) assert 'never42' not in result.stdout.str() + def test_setup_setUpClass(testdir): testpath = testdir.makepyfile(""" import unittest @@ -238,6 +251,7 @@ def test_teareddown(): reprec = testdir.inline_run(testpath) reprec.assertoutcome(passed=3) + def test_setup_class(testdir): testpath = testdir.makepyfile(""" import unittest @@ -279,6 +293,7 @@ def test_hello(self): result = testdir.runpytest() assert 'should not raise' not in result.stdout.str() + @pytest.mark.parametrize("type", ['Error', 'Failure']) def test_testcase_custom_exception_info(testdir, type): testdir.makepyfile(""" @@ -310,6 +325,7 @@ def test_hello(self): "*1 failed*", ]) + def test_testcase_totally_incompatible_exception_info(testdir): item, = testdir.getitems(""" from unittest import TestCase @@ -321,6 +337,7 @@ def test_hello(self): excinfo = item._excinfo.pop(0) assert 'ERROR: Unknown Incompatible' in str(excinfo.getrepr()) + def test_module_level_pytestmark(testdir): testpath = testdir.makepyfile(""" import unittest @@ -520,6 +537,7 @@ def test_hello(self): child.expect("hellopdb") child.sendeof() + def test_djangolike_testcase(testdir): # contributed from Morten Breekevold testdir.makepyfile(""" @@ -585,6 +603,7 @@ def test_hello(self): res = testdir.runpytest() assert "failUnlessEqual" not in res.stdout.str() + def test_unorderable_types(testdir): testdir.makepyfile(""" import unittest @@ -602,6 +621,7 @@ class Test(unittest.TestCase): assert "TypeError" not in result.stdout.str() assert result.ret == EXIT_NOTESTSCOLLECTED + def test_unittest_typerror_traceback(testdir): testdir.makepyfile(""" import unittest @@ -769,6 +789,7 @@ def test_func(self): reprec = testdir.inline_run() reprec.assertoutcome(failed=1) + @pytest.mark.skipif("sys.version_info < (2,7)") def test_unittest_raise_skip_issue748(testdir): testdir.makepyfile(test_foo=""" @@ -784,6 +805,7 @@ def test_one(self): *1 skipped* """) + @pytest.mark.skipif("sys.version_info < (2,7)") def test_unittest_skip_issue1169(testdir): testdir.makepyfile(test_foo=""" @@ -800,6 +822,7 @@ def test_skip(self): *1 skipped* """) + def test_class_method_containing_test_issue1558(testdir): testdir.makepyfile(test_foo=""" import unittest diff --git a/testing/test_warnings.py b/testing/test_warnings.py index 213cc53705b..09693662c48 100644 --- a/testing/test_warnings.py +++ b/testing/test_warnings.py @@ -8,6 +8,7 @@ WARNINGS_SUMMARY_HEADER = 'warnings summary' + @pytest.fixture def pyfile_with_warnings(testdir, request): """ diff --git a/tox.ini b/tox.ini index e0cb0b80ea8..8479b2586d2 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E302,E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E303,E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 7248b759e88ff282cab5bf289d4d7047ef0bfaad Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 41/58] Fixed E303 flake8 errors too many blank lines (3) --- _pytest/assertion/__init__.py | 1 - _pytest/assertion/rewrite.py | 3 --- _pytest/cacheprovider.py | 1 - _pytest/compat.py | 2 -- _pytest/config.py | 1 - _pytest/debugging.py | 1 - _pytest/fixtures.py | 7 ------- _pytest/freeze_support.py | 1 - _pytest/main.py | 2 -- _pytest/mark.py | 4 ---- _pytest/pytester.py | 1 - _pytest/python.py | 2 -- _pytest/terminal.py | 1 - testing/acceptance_test.py | 3 --- testing/code/test_excinfo.py | 3 --- testing/code/test_source.py | 1 - testing/python/collect.py | 4 ---- testing/python/fixture.py | 8 -------- testing/python/metafunc.py | 5 ----- testing/python/raises.py | 1 - testing/test_cache.py | 4 ---- testing/test_capture.py | 2 -- testing/test_collection.py | 1 - testing/test_config.py | 1 - testing/test_doctest.py | 1 - testing/test_mark.py | 2 -- testing/test_pdb.py | 2 -- testing/test_recwarn.py | 1 - testing/test_skipping.py | 1 - testing/test_terminal.py | 1 - testing/test_warnings.py | 1 - tox.ini | 2 +- 32 files changed, 1 insertion(+), 70 deletions(-) diff --git a/_pytest/assertion/__init__.py b/_pytest/assertion/__init__.py index acb034d8649..b0ef667d565 100644 --- a/_pytest/assertion/__init__.py +++ b/_pytest/assertion/__init__.py @@ -25,7 +25,6 @@ def pytest_addoption(parser): expression information.""") - def register_assert_rewrite(*names): """Register one or more module names to be rewritten on import. diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 48f5d43887a..97663ccdaba 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -215,8 +215,6 @@ def load_module(self, name): raise return sys.modules[name] - - def is_package(self, name): try: fd, fn, desc = imp.find_module(name) @@ -900,7 +898,6 @@ def visit_Call_legacy(self, call): else: visit_Call = visit_Call_legacy - def visit_Attribute(self, attr): if not isinstance(attr.ctx, ast.Load): return self.generic_visit(attr) diff --git a/_pytest/cacheprovider.py b/_pytest/cacheprovider.py index 31cfb2a294d..6378e433874 100755 --- a/_pytest/cacheprovider.py +++ b/_pytest/cacheprovider.py @@ -180,7 +180,6 @@ def pytest_cmdline_main(config): return wrap_session(config, cacheshow) - @pytest.hookimpl(tryfirst=True) def pytest_configure(config): config.cache = Cache(config) diff --git a/_pytest/compat.py b/_pytest/compat.py index bebcc71f94d..cdca56387bd 100644 --- a/_pytest/compat.py +++ b/_pytest/compat.py @@ -13,7 +13,6 @@ import _pytest - try: import enum except ImportError: # pragma: no cover @@ -111,7 +110,6 @@ def getfuncargnames(function, startindex=None): return tuple(argnames[startindex:]) - if sys.version_info[:2] == (2, 6): def isclass(object): """ Return true if the object is a class. Overrides inspect.isclass for diff --git a/_pytest/config.py b/_pytest/config.py index 7d299b30fdc..d2d3c843920 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -851,7 +851,6 @@ def _format_action_invocation(self, action): return action._formatted_action_invocation - def _ensure_removed_sysmodule(modname): try: del sys.modules[modname] diff --git a/_pytest/debugging.py b/_pytest/debugging.py index 1d69cd0ad30..aa9c9a3863f 100644 --- a/_pytest/debugging.py +++ b/_pytest/debugging.py @@ -4,7 +4,6 @@ import sys - def pytest_addoption(parser): group = parser.getgroup("general") group._addoption( diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 67cf7e39eb4..50c2b95f8b7 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -116,7 +116,6 @@ def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): node._name2pseudofixturedef[argname] = fixturedef - def getfixturemarker(obj): """ return fixturemarker or None if it doesn't exist or raised exceptions.""" @@ -128,7 +127,6 @@ def getfixturemarker(obj): return None - def get_parametrized_fixture_keys(item, scopenum): """ return list of keys for all parametrized arguments which match the specified scope. """ @@ -240,7 +238,6 @@ def fillfixtures(function): request._fillfixtures() - def get_direct_param_fixture_func(request): return request.param @@ -283,7 +280,6 @@ def node(self): """ 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: @@ -305,7 +301,6 @@ def config(self): """ 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. """ @@ -839,7 +834,6 @@ def __call__(self, function): return function - def fixture(scope="function", params=None, autouse=False, ids=None, name=None): """ (return a) decorator to mark a fixture factory function. @@ -955,7 +949,6 @@ def __init__(self, session): 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: diff --git a/_pytest/freeze_support.py b/_pytest/freeze_support.py index 52f86087fff..97147a88250 100644 --- a/_pytest/freeze_support.py +++ b/_pytest/freeze_support.py @@ -5,7 +5,6 @@ from __future__ import absolute_import, division, print_function - def freeze_includes(): """ Returns a list of module names used by py.test that should be diff --git a/_pytest/main.py b/_pytest/main.py index b9850b8b687..97d7e0c71ce 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -77,7 +77,6 @@ def pytest_addoption(parser): help="base temporary directory for this test run.") - def pytest_namespace(): """keeping this one works around a deeper startup issue in pytest @@ -217,7 +216,6 @@ def __get__(self, obj, owner): return getattr(__import__('pytest'), self.name) - class NodeKeywords(MappingMixin): def __init__(self, node): self.node = node diff --git a/_pytest/mark.py b/_pytest/mark.py index 88642a000fc..67086ae8ba6 100644 --- a/_pytest/mark.py +++ b/_pytest/mark.py @@ -245,7 +245,6 @@ def test_function(): on the ``test_function`` object. """ _config = None - def __getattr__(self, name): if name[0] == "_": raise AttributeError("Marker name must NOT start with underscore") @@ -356,9 +355,6 @@ def __call__(self, *args, **kwargs): return self.__class__(self.mark.combined_with(mark)) - - - class Mark(namedtuple('Mark', 'name, args, kwargs')): def combined_with(self, other): diff --git a/_pytest/pytester.py b/_pytest/pytester.py index 12473231d2a..1783c9c0cfd 100644 --- a/_pytest/pytester.py +++ b/_pytest/pytester.py @@ -390,7 +390,6 @@ def assert_outcomes(self, passed=0, skipped=0, failed=0): assert failed == d.get("failed", 0) - class Testdir: """Temporary test directory with tools to test/run pytest itself. diff --git a/_pytest/python.py b/_pytest/python.py index 39dd5394a0b..47759eceee8 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -48,7 +48,6 @@ def filter_traceback(entry): return p != cutdir1 and not p.relto(cutdir2) and not p.relto(cutdir3) - def pyobj_property(name): def get(self): node = self.getparent(getattr(__import__('pytest'), name)) @@ -193,7 +192,6 @@ def pytest_make_parametrize_id(config, val, argname=None): return None - class PyobjContext(object): module = pyobj_property("Module") cls = pyobj_property("Class") diff --git a/_pytest/terminal.py b/_pytest/terminal.py index fdf9090429f..10f37c6a137 100644 --- a/_pytest/terminal.py +++ b/_pytest/terminal.py @@ -509,7 +509,6 @@ def print_teardown_sections(self, rep): content = content[:-1] self._tw.line(content) - def summary_failures(self): if self.config.option.tbstyle != "no": reports = self.getreports('failed') diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index 4426c068e7f..9a75a43e5f8 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -81,7 +81,6 @@ def pytest_unconfigure(): "*---unconfigure", ]) - def test_config_preparse_plugin_option(self, testdir): testdir.makepyfile(pytest_xyz=""" def pytest_addoption(parser): @@ -147,7 +146,6 @@ def test_issue486_better_reporting_on_conftest_load_failure(self, testdir): *ERROR*could not load*conftest.py* """) - def test_early_skip(self, testdir): testdir.mkdir("xyz") testdir.makeconftest(""" @@ -676,7 +674,6 @@ def test_core_backward_compatibility(self): import _pytest.config assert type(_pytest.config.get_plugin_manager()) is _pytest.config.PytestPluginManager - def test_has_plugin(self, request): """Test hasplugin function of the plugin manager (#932).""" assert request.config.pluginmanager.hasplugin('python') diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 48ef6e7e8d6..966ef192d1a 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -467,7 +467,6 @@ def f(): 'E AssertionError' ] - def test_repr_source_not_existing(self): pr = FormattedExcinfo() co = compile("raise ValueError()", "", "exec") @@ -553,14 +552,12 @@ class FakeRawTB(object): if py.std.sys.version_info[0] >= 3: assert repr.chain[0][0].reprentries[0].lines[0] == "> ???" - fail = py.error.ENOENT # noqa repr = pr.repr_excinfo(excinfo) assert repr.reprtraceback.reprentries[0].lines[0] == "> ???" if py.std.sys.version_info[0] >= 3: assert repr.chain[0][0].reprentries[0].lines[0] == "> ???" - def test_repr_local(self): p = FormattedExcinfo(showlocals=True) loc = {'y': 5, 'z': 7, 'x': 3, '@x': 2, '__builtins__': {}} diff --git a/testing/code/test_source.py b/testing/code/test_source.py index e9732d7f3f1..f7f272c7b6b 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -642,7 +642,6 @@ def test_finally(self): assert str(source) == " raise IndexError(1)" - class TestIf(object): pytestmark = astonly source = """\ diff --git a/testing/python/collect.py b/testing/python/collect.py index a3699751325..a7e632018d3 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -476,7 +476,6 @@ def test_archival_to_version(key, value): rec = testdir.inline_run() rec.assertoutcome(passed=2) - def test_parametrize_with_non_hashable_values_indirect(self, testdir): """Test parametrization with non-hashable values with indirect parametrization.""" testdir.makepyfile(""" @@ -504,7 +503,6 @@ def test_archival_to_version(key, value): rec = testdir.inline_run() rec.assertoutcome(passed=2) - def test_parametrize_overrides_fixture(self, testdir): """Test parametrization when parameter overrides existing fixture with same name.""" testdir.makepyfile(""" @@ -532,7 +530,6 @@ def test_overridden_via_multiparam(other, value): rec = testdir.inline_run() rec.assertoutcome(passed=3) - def test_parametrize_overrides_parametrized_fixture(self, testdir): """Test parametrization when parameter overrides existing parametrized fixture with same name.""" testdir.makepyfile(""" @@ -1352,7 +1349,6 @@ def test_real(): ]) - def test_keep_duplicates(testdir): """Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609) diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 19cfabd2028..ba6e94bf087 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -441,7 +441,6 @@ def test_lookup_error(unknown): ]) assert "INTERNAL" not in result.stdout.str() - def test_fixture_excinfo_leak(self, testdir): # on python2 sys.excinfo would leak into fixture executions testdir.makepyfile(""" @@ -641,7 +640,6 @@ def test_fix(myfix): mod = reprec.getcalls("pytest_runtest_setup")[0].item.module assert not mod.l - def test_request_addfinalizer_partial_setup_failure(self, testdir): p = testdir.makepyfile(""" import pytest @@ -1603,8 +1601,6 @@ def f(hello): reprec = testdir.inline_run() reprec.assertoutcome(passed=2) - - def test_funcarg_and_setup(self, testdir): testdir.makepyfile(""" import pytest @@ -2406,7 +2402,6 @@ def test_3(): reprec = testdir.inline_run("-v") reprec.assertoutcome(passed=5) - @pytest.mark.issue246 @pytest.mark.parametrize("scope", ["session", "function", "module"]) def test_finalizer_order_on_parametrization(self, scope, testdir): @@ -2638,8 +2633,6 @@ def test_3(): *3 pass*2 error* """) - - def test_setupfunc_missing_funcarg(self, testdir): testdir.makepyfile(""" import pytest @@ -2747,7 +2740,6 @@ def arg2(): """) - def test_show_fixtures_different_files(self, testdir): """ #833: --fixtures only shows fixtures from first file diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 8c0bf41d026..fef4221f3fe 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -331,7 +331,6 @@ def ids(val): "\nUpdate your code as this will raise an error in pytest-4.0.", ] - def test_parametrize_ids_exception(self, testdir): """ :param testdir: the instance of Testdir class, a temporary @@ -776,7 +775,6 @@ def test_hello(xyz): result = testdir.runpytest(p) result.assert_outcomes(passed=1) - def test_generate_plugin_and_module(self, testdir): testdir.makeconftest(""" def pytest_generate_tests(metafunc): @@ -1435,7 +1433,6 @@ def test_increment(n, expected): reprec = testdir.inline_run() reprec.assertoutcome(passed=2, skipped=2) - @pytest.mark.issue290 def test_parametrize_ID_generation_string_int_works(self, testdir): testdir.makepyfile(""" @@ -1452,7 +1449,6 @@ def test_limit(limit, myfixture): reprec = testdir.inline_run() reprec.assertoutcome(passed=2) - @pytest.mark.parametrize('strict', [True, False]) def test_parametrize_marked_value(self, testdir, strict): s = """ @@ -1476,7 +1472,6 @@ def test_increment(n, expected): passed, failed = (0, 2) if strict else (2, 0) reprec.assertoutcome(passed=passed, failed=failed) - def test_pytest_make_parametrize_id(self, testdir): testdir.makeconftest(""" def pytest_make_parametrize_id(config, val): diff --git a/testing/python/raises.py b/testing/python/raises.py index 21a6f808c0d..321ee349ee6 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -118,7 +118,6 @@ def __call__(self): for o in gc.get_objects(): assert type(o) is not T - def test_raises_match(self): msg = r"with base \d+" with pytest.raises(ValueError, match=msg): diff --git a/testing/test_cache.py b/testing/test_cache.py index 231a4e53d64..1a570e2c32c 100755 --- a/testing/test_cache.py +++ b/testing/test_cache.py @@ -89,7 +89,6 @@ def test_cachefuncarg(cache): result.stdout.fnmatch_lines(["*1 passed*"]) - def test_cache_reportheader(testdir): testdir.makepyfile(""" def test_hello(): @@ -339,7 +338,6 @@ def rlf(fail_import, fail_run): lastfailed = rlf(fail_import=0, fail_run=1) assert list(lastfailed) == ['test_maybe.py::test_hello'] - def test_lastfailed_failure_subset(self, testdir, monkeypatch): testdir.makepyfile(test_maybe=""" @@ -381,12 +379,10 @@ def rlf(fail_import, fail_run, args=()): result, lastfailed = rlf(fail_import=1, fail_run=0) assert sorted(list(lastfailed)) == ['test_maybe.py', 'test_maybe2.py'] - result, lastfailed = rlf(fail_import=0, fail_run=0, args=('test_maybe2.py',)) assert list(lastfailed) == ['test_maybe.py'] - # edge case of test selection - even if we remember failures # from other tests we still need to run all tests if no test # matches the failures diff --git a/testing/test_capture.py b/testing/test_capture.py index 326596ee58c..302a02d1015 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -49,7 +49,6 @@ def oswritebytes(fd, obj): os.write(fd, tobytes(obj)) - def StdCaptureFD(out=True, err=True, in_=True): return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture) @@ -1076,7 +1075,6 @@ def test_capture_again(): """) - @pytest.mark.parametrize('method', ['SysCapture', 'FDCapture']) def test_capturing_and_logging_fundamentals(testdir, method): if method == "StdCaptureFD" and not hasattr(os, 'dup'): diff --git a/testing/test_collection.py b/testing/test_collection.py index 56a985bf159..05d9244a022 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -69,7 +69,6 @@ def test_foo(): parent = fn.getparent(pytest.Class) assert parent is cls - def test_getcustomfile_roundtrip(self, testdir): hello = testdir.makefile(".xxx", hello="world") testdir.makepyfile(conftest=""" diff --git a/testing/test_config.py b/testing/test_config.py index 7c6b7d6bc91..495821cd511 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -731,7 +731,6 @@ def test_pass(pytestconfig): assert result.ret == 0 result.stdout.fnmatch_lines(["custom_option:3.0"]) - def test_override_ini_pathlist(self, testdir): testdir.makeconftest(""" def pytest_addoption(parser): diff --git a/testing/test_doctest.py b/testing/test_doctest.py index dfbab28cca3..dd444569c79 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -294,7 +294,6 @@ def somefunc(): "*:5: DocTestFailure" ]) - def test_txtfile_failing(self, testdir): p = testdir.maketxtfile(""" >>> i = 0 diff --git a/testing/test_mark.py b/testing/test_mark.py index 4e05d5a5cc0..f0fc375b836 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -462,7 +462,6 @@ def test_bar(self): pass items, rec = testdir.inline_genitems(p) self.assert_markers(items, test_foo=('a', 'b'), test_bar=('a',)) - @pytest.mark.issue568 @pytest.mark.xfail(reason="markers smear on methods of base classes") def test_mark_should_not_pass_to_siebling_class(self, testdir): @@ -487,7 +486,6 @@ class TestOtherSub(TestBase): assert not hasattr(base_item.obj, 'b') assert not hasattr(sub_item_other.obj, 'b') - def test_mark_decorator_baseclasses_merged(self, testdir): p = testdir.makepyfile(""" import pytest diff --git a/testing/test_pdb.py b/testing/test_pdb.py index b6543b05365..70a5c3c5bdb 100644 --- a/testing/test_pdb.py +++ b/testing/test_pdb.py @@ -33,7 +33,6 @@ def interaction(self, *args): return called - class TestPDB(object): @pytest.fixture @@ -377,7 +376,6 @@ def test_pdb_custom_cls(self, testdir, custom_pdb_calls): ]) assert custom_pdb_calls == ["init", "reset", "interaction"] - def test_pdb_custom_cls_without_pdb(self, testdir, custom_pdb_calls): p1 = testdir.makepyfile("""xxx """) result = testdir.runpytest_inprocess( diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index f1048f07d0f..e8b1db399ba 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -295,7 +295,6 @@ class MyRuntimeWarning(RuntimeWarning): pass assert str(record[0].message) == "user" assert str(record[1].message) == "runtime" - def test_double_test(self, testdir): """If a test is run again, the warning should still be raised""" testdir.makepyfile(''' diff --git a/testing/test_skipping.py b/testing/test_skipping.py index 586244f2323..b780e4dc8c2 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -350,7 +350,6 @@ def test_this2(arg): "*1 xfailed*", ]) - @pytest.mark.parametrize('expected, actual, matchline', [('TypeError', 'TypeError', "*1 xfailed*"), ('(AttributeError, TypeError)', 'TypeError', "*1 xfailed*"), diff --git a/testing/test_terminal.py b/testing/test_terminal.py index 43028fc4656..bac3ab8b128 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -734,7 +734,6 @@ def test_3(): "*2 failed*", ]) - def test_tb_option(self, testdir, option): testdir.makepyfile(""" import pytest diff --git a/testing/test_warnings.py b/testing/test_warnings.py index 09693662c48..8589328467b 100644 --- a/testing/test_warnings.py +++ b/testing/test_warnings.py @@ -113,7 +113,6 @@ def test_ignore(testdir, pyfile_with_warnings, method): assert WARNINGS_SUMMARY_HEADER not in result.stdout.str() - @pytest.mark.skipif(sys.version_info < (3, 0), reason='warnings message is unicode is ok in python3') def test_unicode(testdir, pyfile_with_warnings): diff --git a/tox.ini b/tox.ini index 8479b2586d2..3c3f890550c 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E303,E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E401,E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 45ac863069a45d4874370c2028aa7f2aae2cff91 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 42/58] Fixed E401 flake8 errors multiple imports on one line --- _pytest/_code/source.py | 3 ++- _pytest/helpconfig.py | 3 ++- testing/test_argcomplete.py | 3 ++- testing/test_collection.py | 3 ++- testing/test_config.py | 3 ++- testing/test_parseopt.py | 3 ++- tox.ini | 2 +- 7 files changed, 13 insertions(+), 7 deletions(-) diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index fb00db1a6c8..2ee1c317e44 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -2,7 +2,8 @@ from bisect import bisect_right import sys -import inspect, tokenize +import inspect +import tokenize import py cpy_compile = compile diff --git a/_pytest/helpconfig.py b/_pytest/helpconfig.py index 5be1caa1dad..e744637f866 100644 --- a/_pytest/helpconfig.py +++ b/_pytest/helpconfig.py @@ -4,7 +4,8 @@ import py import pytest from _pytest.config import PrintHelp -import os, sys +import os +import sys from argparse import Action diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py index 1023e183a83..b07f6e83b24 100644 --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -1,5 +1,6 @@ from __future__ import absolute_import, division, print_function -import py, pytest +import py +import pytest # test for _argcomplete but not specific for any application diff --git a/testing/test_collection.py b/testing/test_collection.py index 05d9244a022..a0b481628bf 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -1,5 +1,6 @@ from __future__ import absolute_import, division, print_function -import pytest, py +import pytest +import py from _pytest.main import Session, EXIT_NOTESTSCOLLECTED diff --git a/testing/test_config.py b/testing/test_config.py index 495821cd511..2ea4d0c10cc 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -1,5 +1,6 @@ from __future__ import absolute_import, division, print_function -import py, pytest +import py +import pytest import _pytest._code from _pytest.config import getcfg, get_common_ancestor, determine_setup diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index de386f4e9be..86e76cc0a5f 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -1,7 +1,8 @@ from __future__ import absolute_import, division, print_function import sys import os -import py, pytest +import py +import pytest from _pytest import config as parseopt diff --git a/tox.ini b/tox.ini index 3c3f890550c..9312432b223 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E401,E402,E501,E701,E702,E704,E712,E731 +ignore = E402,E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From b9e318866eab409ae6487a5790a87610d6933258 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:09 +0200 Subject: [PATCH 43/58] Fixed E402 flake8 errors module level import not at top of file --- testing/code/test_excinfo.py | 8 ++++---- testing/test_assertrewrite.py | 12 ++++++------ tox.ini | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 966ef192d1a..a1b308760a4 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -12,9 +12,6 @@ ReprExceptionInfo, ExceptionChainRepr) -queue = py.builtin._tryimport('queue', 'Queue') - -failsonjython = pytest.mark.xfail("sys.platform.startswith('java')") from test_source import astonly try: @@ -24,7 +21,10 @@ else: invalidate_import_caches = getattr(importlib, "invalidate_caches", None) -import pytest +queue = py.builtin._tryimport('queue', 'Queue') + +failsonjython = pytest.mark.xfail("sys.platform.startswith('java')") + pytest_version_info = tuple(map(int, pytest.__version__.split(".")[:3])) diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 72bc9aec214..2d61b74408c 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -1,24 +1,24 @@ from __future__ import absolute_import, division, print_function + import glob import os import py_compile import stat import sys 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 _pytest._code from _pytest.assertion import util from _pytest.assertion.rewrite import rewrite_asserts, PYTEST_TAG, AssertionRewritingHook from _pytest.main import EXIT_NOTESTSCOLLECTED +ast = pytest.importorskip("ast") +if sys.platform.startswith("java"): + # XXX should be xfail + pytest.skip("assert rewrite does currently not work on jython") + def setup_module(mod): mod._old_reprcompare = util._reprcompare diff --git a/tox.ini b/tox.ini index 9312432b223..438910f4338 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E402,E501,E701,E702,E704,E712,E731 +ignore = E501,E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 7d2ceb7872c653019cd07fc0a405410072860e1e Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:10 +0200 Subject: [PATCH 44/58] Fixed E501 flake8 errors line too long (> 120 characters) --- _pytest/config.py | 3 ++- _pytest/main.py | 6 ++++-- testing/python/approx.py | 3 ++- testing/python/metafunc.py | 26 +++++++++++++++++++++----- tox.ini | 2 +- 5 files changed, 30 insertions(+), 10 deletions(-) diff --git a/_pytest/config.py b/_pytest/config.py index d2d3c843920..4698ba79086 100644 --- a/_pytest/config.py +++ b/_pytest/config.py @@ -211,7 +211,8 @@ def addhooks(self, module_or_class): """ .. deprecated:: 2.8 - Use :py:meth:`pluggy.PluginManager.add_hookspecs <_pytest.vendored_packages.pluggy.PluginManager.add_hookspecs>` instead. + Use :py:meth:`pluggy.PluginManager.add_hookspecs <_pytest.vendored_packages.pluggy.PluginManager.add_hookspecs>` + instead. """ warning = dict(code="I2", fslocation=_pytest._code.getfslineno(sys._getframe(1)), diff --git a/_pytest/main.py b/_pytest/main.py index 97d7e0c71ce..a4cc21a5778 100644 --- a/_pytest/main.py +++ b/_pytest/main.py @@ -30,7 +30,8 @@ def pytest_addoption(parser): parser.addini("norecursedirs", "directory patterns to avoid for recursion", type="args", default=['.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg', 'venv']) - parser.addini("testpaths", "directories to search for tests when no files or directories are given in the command line.", + parser.addini("testpaths", "directories to search for tests when no files or directories are given in the " + "command line.", type="args", default=[]) # parser.addini("dirpatterns", # "patterns specifying possible locations of test files", @@ -47,7 +48,8 @@ def pytest_addoption(parser): group._addoption('--strict', action="store_true", help="marks not registered in configuration file raise errors.") group._addoption("-c", metavar="file", type=str, dest="inifilename", - help="load configuration from `file` instead of trying to locate one of the implicit configuration files.") + help="load configuration from `file` instead of trying to locate one of the implicit " + "configuration files.") group._addoption("--continue-on-collection-errors", action="store_true", default=False, dest="continue_on_collection_errors", help="Force test execution even if collection errors occur.") diff --git a/testing/python/approx.py b/testing/python/approx.py index f849ede160e..704a7c43ee1 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -29,7 +29,8 @@ def test_repr_string(self): if sys.version_info[:2] == (2, 6): tol1, tol2, infr = '???', '???', '???' assert repr(approx(1.0)) == '1.0 {pm} {tol1}'.format(pm=plus_minus, tol1=tol1) - assert repr(approx([1.0, 2.0])) == '1.0 {pm} {tol1}, 2.0 {pm} {tol2}'.format(pm=plus_minus, tol1=tol1, tol2=tol2) + assert repr(approx([1.0, 2.0])) == '1.0 {pm} {tol1}, 2.0 {pm} {tol2}'.format( + pm=plus_minus, tol1=tol1, tol2=tol2) assert repr(approx(inf)) == 'inf' assert repr(approx(1.0, rel=nan)) == '1.0 {pm} ???'.format(pm=plus_minus) assert repr(approx(1.0, rel=inf)) == '1.0 {pm} {infr}'.format(pm=plus_minus, infr=infr) diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index fef4221f3fe..4a29cdc87e5 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -178,11 +178,27 @@ def test_unicode_idval(self): """ from _pytest.python import _idval values = [ - (u'', ''), - (u'ascii', 'ascii'), - (u'ação', 'a\\xe7\\xe3o'), - (u'josé@blah.com', 'jos\\xe9@blah.com'), - (u'δοκ.ιμή@παράδειγμα.δοκιμή', '\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae'), + ( + u'', + '' + ), + ( + u'ascii', + 'ascii' + ), + ( + u'ação', + 'a\\xe7\\xe3o' + ), + ( + u'josé@blah.com', + 'jos\\xe9@blah.com' + ), + ( + u'δοκ.ιμή@παράδειγμα.δοκιμή', + '\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3' + '\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae' + ), ] for val, expected in values: assert _idval(val, 'a', 6, None) == expected diff --git a/tox.ini b/tox.ini index 438910f4338..c67225bfa75 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E501,E701,E702,E704,E712,E731 +ignore = E701,E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 85141a419f7c8ca314ff682ad58b18f1485da993 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:10 +0200 Subject: [PATCH 45/58] Fixed E701 flake8 errors multiple statements on one line (colon) --- testing/code/test_code.py | 16 ++++++++++------ testing/code/test_excinfo.py | 6 ++++-- testing/python/metafunc.py | 6 ++++-- testing/test_recwarn.py | 6 ++++-- tox.ini | 2 +- 5 files changed, 23 insertions(+), 13 deletions(-) diff --git a/testing/code/test_code.py b/testing/code/test_code.py index acf1ffc91c1..6db5c6fbdb0 100644 --- a/testing/code/test_code.py +++ b/testing/code/test_code.py @@ -149,8 +149,10 @@ class TestExceptionInfo(object): def test_bad_getsource(self): try: - if False: pass - else: assert False + if False: + pass + else: + assert False except AssertionError: exci = _pytest._code.ExceptionInfo() assert exci.getrepr() @@ -160,11 +162,13 @@ class TestTracebackEntry(object): def test_getsource(self): try: - if False: pass - else: assert False + if False: + pass + else: + assert False except AssertionError: exci = _pytest._code.ExceptionInfo() entry = exci.traceback[0] source = entry.getsource() - assert len(source) == 4 - assert 'else: assert False' in source[3] + assert len(source) == 6 + assert 'assert False' in source[5] diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index a1b308760a4..a7dfe80a6c9 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -991,7 +991,8 @@ def i(): r = excinfo.getrepr(style="long") tw = TWMock() r.toterminal(tw) - for line in tw.lines: print (line) + for line in tw.lines: + print (line) assert tw.lines[0] == "" assert tw.lines[1] == " def f():" assert tw.lines[2] == "> g()" @@ -1038,7 +1039,8 @@ def h(): r = excinfo.getrepr(style="long") tw = TWMock() r.toterminal(tw) - for line in tw.lines: print (line) + for line in tw.lines: + print (line) assert tw.lines[0] == "" assert tw.lines[1] == " def f():" assert tw.lines[2] == " try:" diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index 4a29cdc87e5..bda36f1e285 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -68,7 +68,8 @@ def test_addcall_param(self): def func(arg1): pass metafunc = self.Metafunc(func) - class obj(object): pass + class obj(object): + pass metafunc.addcall(param=obj) metafunc.addcall(param=obj) @@ -83,7 +84,8 @@ def func(x): pass metafunc = self.Metafunc(func) - class obj(object): pass + class obj(object): + pass metafunc.addcall(funcargs={"x": 2}) metafunc.addcall(funcargs={"x": 3}) diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index e8b1db399ba..5611d1a4467 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -283,9 +283,11 @@ def test_record_by_subclass(self): assert str(record[0].message) == "user" assert str(record[1].message) == "runtime" - class MyUserWarning(UserWarning): pass + class MyUserWarning(UserWarning): + pass - class MyRuntimeWarning(RuntimeWarning): pass + class MyRuntimeWarning(RuntimeWarning): + pass with pytest.warns((UserWarning, RuntimeWarning)) as record: warnings.warn("user", MyUserWarning) diff --git a/tox.ini b/tox.ini index c67225bfa75..5a11cfaa665 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E701,E702,E704,E712,E731 +ignore = E702,E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From bf259d3c93427cb09c6ff40741a62e81678ee369 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:10 +0200 Subject: [PATCH 46/58] Fixed E702 flake8 errors multiple statements on one line (semicolon) --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 5a11cfaa665..f30ba37b9ba 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E702,E704,E712,E731 +ignore = E704,E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 5ae59279f48b500625b8cffb8ca3e6f8386aa291 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:10 +0200 Subject: [PATCH 47/58] Fixed E704 flake8 errors multiple statements on one line (def) --- _pytest/_argcomplete.py | 3 +- testing/python/fixture.py | 15 +++++--- testing/python/metafunc.py | 72 +++++++++++++++++++++++++------------- testing/test_runner.py | 15 +++++--- tox.ini | 2 +- 5 files changed, 71 insertions(+), 36 deletions(-) diff --git a/_pytest/_argcomplete.py b/_pytest/_argcomplete.py index 8fec0effe7c..1ba1ecc1e7c 100644 --- a/_pytest/_argcomplete.py +++ b/_pytest/_argcomplete.py @@ -100,5 +100,6 @@ def __call__(self, prefix, **kwargs): def try_argcomplete(parser): argcomplete.autocomplete(parser) else: - def try_argcomplete(parser): pass + def try_argcomplete(parser): + pass filescompleter = None diff --git a/testing/python/fixture.py b/testing/python/fixture.py index ba6e94bf087..6da7cadd491 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -9,16 +9,20 @@ def test_getfuncargnames(): - def f(): pass + def f(): + pass assert not fixtures.getfuncargnames(f) - def g(arg): pass + def g(arg): + pass assert fixtures.getfuncargnames(g) == ('arg',) - def h(arg1, arg2="hello"): pass + def h(arg1, arg2="hello"): + pass assert fixtures.getfuncargnames(h) == ('arg1',) - def h(arg1, arg2, arg3="hello"): pass + def h(arg1, arg2, arg3="hello"): + pass assert fixtures.getfuncargnames(h) == ('arg1', 'arg2') class A(object): @@ -552,7 +556,8 @@ def test_func(something): pass else: # see #1830 for a cleaner way to accomplish this @contextlib.contextmanager - def expecting_no_warning(): yield + def expecting_no_warning(): + yield warning_expectation = expecting_no_warning() diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index bda36f1e285..5eee2ffba1c 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -29,13 +29,15 @@ def __init__(self, names): return python.Metafunc(func, fixtureinfo, None) def test_no_funcargs(self, testdir): - def function(): pass + def function(): + pass metafunc = self.Metafunc(function) assert not metafunc.fixturenames repr(metafunc._calls) def test_function_basic(self): - def func(arg1, arg2="qwe"): pass + def func(arg1, arg2="qwe"): + pass metafunc = self.Metafunc(func) assert len(metafunc.fixturenames) == 1 assert 'arg1' in metafunc.fixturenames @@ -43,7 +45,8 @@ def func(arg1, arg2="qwe"): pass assert metafunc.cls is None def test_addcall_no_args(self): - def func(arg1): pass + def func(arg1): + pass metafunc = self.Metafunc(func) metafunc.addcall() assert len(metafunc._calls) == 1 @@ -52,7 +55,8 @@ def func(arg1): pass assert not hasattr(call, 'param') def test_addcall_id(self): - def func(arg1): pass + def func(arg1): + pass metafunc = self.Metafunc(func) pytest.raises(ValueError, "metafunc.addcall(id=None)") @@ -65,7 +69,8 @@ def func(arg1): pass assert metafunc._calls[1].id == "2" def test_addcall_param(self): - def func(arg1): pass + def func(arg1): + pass metafunc = self.Metafunc(func) class obj(object): @@ -80,7 +85,8 @@ class obj(object): assert metafunc._calls[2].getparam("arg1") == 1 def test_addcall_funcargs(self): - def func(x): pass + def func(x): + pass metafunc = self.Metafunc(func) @@ -96,7 +102,8 @@ class obj(object): assert not hasattr(metafunc._calls[1], 'param') def test_parametrize_error(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.parametrize("x", [1, 2]) pytest.raises(ValueError, lambda: metafunc.parametrize("x", [5, 6])) @@ -106,7 +113,8 @@ def func(x, y): pass pytest.raises(ValueError, lambda: metafunc.parametrize("y", [5, 6])) def test_parametrize_bad_scope(self, testdir): - def func(x): pass + def func(x): + pass metafunc = self.Metafunc(func) try: metafunc.parametrize("x", [1], scope='doggy') @@ -114,7 +122,8 @@ def func(x): pass assert "has an unsupported scope value 'doggy'" in str(ve) def test_parametrize_and_id(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.parametrize("x", [1, 2], ids=['basic', 'advanced']) @@ -124,14 +133,16 @@ def func(x, y): pass def test_parametrize_and_id_unicode(self): """Allow unicode strings for "ids" parameter in Python 2 (##1905)""" - def func(x): pass + def func(x): + pass metafunc = self.Metafunc(func) metafunc.parametrize("x", [1, 2], ids=[u'basic', u'advanced']) ids = [x.id for x in metafunc._calls] assert ids == [u"basic", u"advanced"] def test_parametrize_with_wrong_number_of_ids(self, testdir): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) pytest.raises(ValueError, lambda: @@ -143,13 +154,15 @@ def func(x, y): pass @pytest.mark.issue510 def test_parametrize_empty_list(self): - def func(y): pass + def func(y): + pass metafunc = self.Metafunc(func) metafunc.parametrize("y", []) assert 'skip' in metafunc._calls[0].keywords def test_parametrize_with_userobjects(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) class A(object): @@ -393,7 +406,8 @@ def test_idmaker_with_ids_unique_names(self): assert result == ["a0", "a1", "b0", "c", "b1"] def test_addcall_and_parametrize(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.addcall({'x': 1}) metafunc.parametrize('y', [2, 3]) @@ -405,7 +419,8 @@ def func(x, y): pass @pytest.mark.issue714 def test_parametrize_indirect(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.parametrize('x', [1], indirect=True) metafunc.parametrize('y', [2, 3], indirect=True) @@ -417,7 +432,8 @@ def func(x, y): pass @pytest.mark.issue714 def test_parametrize_indirect_list(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.parametrize('x, y', [('a', 'b')], indirect=['x']) assert metafunc._calls[0].funcargs == dict(y='b') @@ -425,7 +441,8 @@ def func(x, y): pass @pytest.mark.issue714 def test_parametrize_indirect_list_all(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.parametrize('x, y', [('a', 'b')], indirect=['x', 'y']) assert metafunc._calls[0].funcargs == {} @@ -433,7 +450,8 @@ def func(x, y): pass @pytest.mark.issue714 def test_parametrize_indirect_list_empty(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.parametrize('x, y', [('a', 'b')], indirect=[]) assert metafunc._calls[0].funcargs == dict(x='a', y='b') @@ -471,7 +489,8 @@ def test_simple(x,y): @pytest.mark.issue714 def test_parametrize_indirect_list_error(self, testdir): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) with pytest.raises(ValueError): metafunc.parametrize('x, y', [('a', 'b')], indirect=['x', 'z']) @@ -567,7 +586,8 @@ def test_simple(x): ]) def test_addcalls_and_parametrize_indirect(self): - def func(x, y): pass + def func(x, y): + pass metafunc = self.Metafunc(func) metafunc.addcall(param="123") metafunc.parametrize('x', [1], indirect=True) @@ -689,16 +709,20 @@ def test_3(self, arg, arg2): """) def test_format_args(self): - def function1(): pass + def function1(): + pass assert fixtures._format_args(function1) == '()' - def function2(arg1): pass + def function2(arg1): + pass assert fixtures._format_args(function2) == "(arg1)" - def function3(arg1, arg2="qwe"): pass + def function3(arg1, arg2="qwe"): + pass assert fixtures._format_args(function3) == "(arg1, arg2='qwe')" - def function4(arg1, *args, **kwargs): pass + def function4(arg1, *args, **kwargs): + pass assert fixtures._format_args(function4) == "(arg1, *args, **kwargs)" diff --git a/testing/test_runner.py b/testing/test_runner.py index 0d2ca7ee139..842810f1b66 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -40,11 +40,14 @@ def test_func(): pass def test_teardown_multiple_one_fails(self, testdir): r = [] - def fin1(): r.append('fin1') + def fin1(): + r.append('fin1') - def fin2(): raise Exception('oops') + def fin2(): + raise Exception('oops') - def fin3(): r.append('fin3') + def fin3(): + r.append('fin3') item = testdir.getitem("def test_func(): pass") ss = runner.SetupState() @@ -59,9 +62,11 @@ def fin3(): r.append('fin3') def test_teardown_multiple_fail(self, testdir): # Ensure the first exception is the one which is re-raised. # Ideally both would be reported however. - def fin1(): raise Exception('oops1') + def fin1(): + raise Exception('oops1') - def fin2(): raise Exception('oops2') + def fin2(): + raise Exception('oops2') item = testdir.getitem("def test_func(): pass") ss = runner.SetupState() diff --git a/tox.ini b/tox.ini index f30ba37b9ba..43be981c49c 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E704,E712,E731 +ignore = E712,E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From 15610289ac720bbdd90c5b69b6a5ef6405a2c4ab Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:10 +0200 Subject: [PATCH 48/58] Fixed E712 flake8 errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit comparison to True should be ‘if cond is True:’ or ‘if cond:’ --- _pytest/fixtures.py | 2 +- testing/test_parseopt.py | 8 ++++---- tox.ini | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/_pytest/fixtures.py b/_pytest/fixtures.py index 50c2b95f8b7..5505fb4e19e 100644 --- a/_pytest/fixtures.py +++ b/_pytest/fixtures.py @@ -872,7 +872,7 @@ def fixture(scope="function", params=None, autouse=False, ids=None, name=None): instead of ``return``. In this case, the code block after the ``yield`` statement is executed as teardown code regardless of the test outcome. A fixture function must yield exactly once. """ - 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, name=name)(scope) diff --git a/testing/test_parseopt.py b/testing/test_parseopt.py index 86e76cc0a5f..02fdf0adaac 100644 --- a/testing/test_parseopt.py +++ b/testing/test_parseopt.py @@ -164,12 +164,12 @@ def test_parse_split_positional_arguments(self, parser): assert getattr(args, parseopt.FILE_OR_DIR) == ['4', '2'] args = parser.parse(['-R', '-S', '4', '2', '-R']) assert getattr(args, parseopt.FILE_OR_DIR) == ['4', '2'] - assert args.R == True - assert args.S == False + assert args.R is True + assert args.S is False args = parser.parse(['-R', '4', '-S', '2']) assert getattr(args, parseopt.FILE_OR_DIR) == ['4', '2'] - assert args.R == True - assert args.S == False + assert args.R is True + assert args.S is False def test_parse_defaultgetter(self): def defaultget(option): diff --git a/tox.ini b/tox.ini index 43be981c49c..144fe623d7d 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,6 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E712,E731 +ignore = E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From b49e8baab3759d70d4af138d76cf28321f3e7807 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 01:25:10 +0200 Subject: [PATCH 49/58] Fixed E731 flake8 errors do not assign a lambda expression, use a def --- _pytest/_code/source.py | 3 ++- _pytest/assertion/rewrite.py | 3 ++- _pytest/assertion/util.py | 16 +++++++++++----- _pytest/python.py | 8 ++++++-- testing/test_session.py | 5 ++++- tox.ini | 1 - 6 files changed, 25 insertions(+), 11 deletions(-) diff --git a/_pytest/_code/source.py b/_pytest/_code/source.py index 2ee1c317e44..e21fecb1e39 100644 --- a/_pytest/_code/source.py +++ b/_pytest/_code/source.py @@ -136,7 +136,8 @@ def isparseable(self, deindent=True): try: import parser except ImportError: - syntax_checker = lambda x: compile(x, 'asd', 'exec') + def syntax_checker(x): + return compile(x, 'asd', 'exec') else: syntax_checker = parser.suite diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index 97663ccdaba..992002b8135 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -39,7 +39,8 @@ if sys.version_info >= (3, 5): ast_Call = ast.Call else: - ast_Call = lambda a, b, c: ast.Call(a, b, c, None, None) + def ast_Call(a, b, c): + return ast.Call(a, b, c, None, None) class AssertionRewritingHook(object): diff --git a/_pytest/assertion/util.py b/_pytest/assertion/util.py index c2a5ddee01e..41e66448d52 100644 --- a/_pytest/assertion/util.py +++ b/_pytest/assertion/util.py @@ -111,11 +111,17 @@ def assertrepr_compare(config, op, left, right): summary = u('%s %s %s') % (ecu(left_repr), op, ecu(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 isinstance(x, basestring)) + + 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: diff --git a/_pytest/python.py b/_pytest/python.py index 47759eceee8..5b0ebe24032 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -1415,7 +1415,10 @@ def expected(self): # or a sequence of numbers, return a list of ApproxNotIterable objects # that can be compared against. from collections import Iterable - approx_non_iter = lambda x: ApproxNonIterable(x, self.rel, self.abs) + + def approx_non_iter(x): + return ApproxNonIterable(x, self.rel, self.abs) + if isinstance(self._expected, Iterable): return [approx_non_iter(x) for x in self._expected] else: @@ -1489,7 +1492,8 @@ def __ne__(self, actual): @property def tolerance(self): - 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 # either None or a value specified by the user. diff --git a/testing/test_session.py b/testing/test_session.py index 39a9769f100..f9eb95f3bed 100644 --- a/testing/test_session.py +++ b/testing/test_session.py @@ -22,7 +22,10 @@ def test_two(self, someargs): assert len(skipped) == 0 assert len(passed) == 1 assert len(failed) == 3 - end = lambda x: x.nodeid.split("::")[-1] + + def end(x): + return x.nodeid.split("::")[-1] + assert end(failed[0]) == "test_one_one" assert end(failed[1]) == "test_other" itemstarted = reprec.getcalls("pytest_itemcollected") diff --git a/tox.ini b/tox.ini index 144fe623d7d..c6fa445af52 100644 --- a/tox.ini +++ b/tox.ini @@ -196,6 +196,5 @@ filterwarnings = ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning [flake8] -ignore = E731 max-line-length = 120 exclude = _pytest/vendored_packages/pluggy.py From b2a5ec3b9457734488dac9dd402876739985af40 Mon Sep 17 00:00:00 2001 From: Andras Tim Date: Mon, 17 Jul 2017 02:16:51 +0200 Subject: [PATCH 50/58] updated meta --- AUTHORS | 1 + changelog/2581.trivial | 1 + 2 files changed, 2 insertions(+) create mode 100644 changelog/2581.trivial diff --git a/AUTHORS b/AUTHORS index ca282870fb9..2ffab85cb80 100644 --- a/AUTHORS +++ b/AUTHORS @@ -9,6 +9,7 @@ Ahn Ki-Wook Alexander Johnson Alexei Kozlenok Anatoly Bubenkoff +Andras Tim Andreas Zeidler Andrzej Ostrowski Andy Freeland diff --git a/changelog/2581.trivial b/changelog/2581.trivial new file mode 100644 index 00000000000..ea6785c792d --- /dev/null +++ b/changelog/2581.trivial @@ -0,0 +1 @@ +Fixed all flake8 errors and warnings From 7b1870a94ed27b6e4517026d248c756df1ce9b8e Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Mon, 17 Jul 2017 21:16:14 -0300 Subject: [PATCH 51/58] Fix flake8 in features branch --- _pytest/deprecated.py | 2 +- _pytest/mark.py | 2 ++ _pytest/python.py | 6 +++++- _pytest/python_api.py | 13 +++++++------ testing/code/test_excinfo.py | 16 ++++++++-------- testing/code/test_source.py | 7 +++---- testing/python/approx.py | 29 +++++++++++++++-------------- testing/python/collect.py | 2 +- testing/test_cache.py | 1 + testing/test_capture.py | 26 +++++++++++++------------- testing/test_conftest.py | 4 ++-- testing/test_mark.py | 3 +-- testing/test_runner.py | 4 ++-- 13 files changed, 61 insertions(+), 54 deletions(-) diff --git a/_pytest/deprecated.py b/_pytest/deprecated.py index 38574211166..4f7b9e9361e 100644 --- a/_pytest/deprecated.py +++ b/_pytest/deprecated.py @@ -36,4 +36,4 @@ class RemovedInPytest4Warning(DeprecationWarning): "Applying marks directly to parameters is deprecated," " please use pytest.param(..., marks=...) instead.\n" "For more details, see: https://docs.pytest.org/en/latest/parametrize.html" -) \ No newline at end of file +) diff --git a/_pytest/mark.py b/_pytest/mark.py index 7714c7f5e0d..c2959606cee 100644 --- a/_pytest/mark.py +++ b/_pytest/mark.py @@ -8,6 +8,7 @@ from .compat import imap from .deprecated import MARK_INFO_ATTRIBUTE, MARK_PARAMETERSET_UNPACKING + def alias(name, warning=None): getter = attrgetter(name) @@ -351,6 +352,7 @@ def __call__(self, *args, **kwargs): mark = Mark(self.name, args, kwargs) return self.__class__(self.mark.combined_with(mark)) + def get_unpacked_marks(obj): """ obtain the unpacked marks that are stored on a object diff --git a/_pytest/python.py b/_pytest/python.py index bf3b1965d7e..dca900a6afd 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -281,7 +281,10 @@ def istestfunction(self, obj, name): obj = safe_getattr(obj, '__func__', False) if obj is False: # 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 ( safe_getattr(obj, "__call__", False) and fixtures.getfixturemarker(obj) is None @@ -1510,6 +1513,7 @@ def set_default(x, default): # the basic pytest Function item # + class Function(FunctionMixin, main.Item, fixtures.FuncargnamesCompatAttr): """ a Function Item is responsible for setting up and executing a Python test function. diff --git a/_pytest/python_api.py b/_pytest/python_api.py index cb7d5e4590e..c5493f49519 100644 --- a/_pytest/python_api.py +++ b/_pytest/python_api.py @@ -9,6 +9,7 @@ # builtin pytest.approx helper + class ApproxBase(object): """ Provide shared utilities for making approximate comparisons between numbers @@ -26,8 +27,8 @@ def __repr__(self): def __eq__(self, actual): return all( - a == self._approx_scalar(x) - for a, x in self._yield_comparisons(actual)) + a == self._approx_scalar(x) + for a, x in self._yield_comparisons(actual)) __hash__ = None @@ -138,7 +139,7 @@ class ApproxMapping(ApproxBase): def __repr__(self): return "approx({0!r})".format(dict( (k, self._approx_scalar(v)) - for k,v in self.expected.items())) + for k, v in self.expected.items())) def __eq__(self, actual): if set(actual.keys()) != set(self.expected.keys()): @@ -241,7 +242,7 @@ def tolerance(self): absolute tolerance or a relative tolerance, depending on what the user 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 # either None or a value specified by the user. @@ -274,7 +275,6 @@ def tolerance(self): return max(relative_tolerance, absolute_tolerance) - def approx(expected, rel=None, abs=None, nan_ok=False): """ 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) 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 = _pytest._code.Source(code).compile() py.builtin.exec_(code, frame.f_globals, loc) @@ -593,6 +593,7 @@ def raises(expected_exception, *args, **kwargs): raises.Exception = fail.Exception + class RaisesContext(object): def __init__(self, expected_exception, message, match_expr): self.expected_exception = expected_exception diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index a7dfe80a6c9..37ceeb4237a 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -144,10 +144,10 @@ def xyz(): xyz() """) try: - exec (source.compile()) + exec(source.compile()) except NameError: tb = _pytest._code.ExceptionInfo().traceback - print (tb[-1].getsource()) + print(tb[-1].getsource()) s = str(tb[-1].getsource()) assert s.startswith("def xyz():\n try:") assert s.strip().endswith("except somenoname:") @@ -341,7 +341,7 @@ def test_excinfo_errisinstance(): def test_excinfo_no_sourcecode(): try: - exec ("raise ValueError()") + exec("raise ValueError()") except ValueError: excinfo = _pytest._code.ExceptionInfo() s = str(excinfo.traceback[-1]) @@ -431,7 +431,7 @@ def importasmod(source): def excinfo_from_exec(self, source): source = _pytest._code.Source(source).strip() try: - exec (source.compile()) + exec(source.compile()) except KeyboardInterrupt: raise except: @@ -471,7 +471,7 @@ def test_repr_source_not_existing(self): pr = FormattedExcinfo() co = compile("raise ValueError()", "", "exec") try: - exec (co) + exec(co) except ValueError: excinfo = _pytest._code.ExceptionInfo() repr = pr.repr_excinfo(excinfo) @@ -486,7 +486,7 @@ def test_repr_many_line_source_not_existing(self): raise ValueError() """, "", "exec") try: - exec (co) + exec(co) except ValueError: excinfo = _pytest._code.ExceptionInfo() repr = pr.repr_excinfo(excinfo) @@ -992,7 +992,7 @@ def i(): tw = TWMock() r.toterminal(tw) for line in tw.lines: - print (line) + print(line) assert tw.lines[0] == "" assert tw.lines[1] == " def f():" assert tw.lines[2] == "> g()" @@ -1040,7 +1040,7 @@ def h(): tw = TWMock() r.toterminal(tw) for line in tw.lines: - print (line) + print(line) assert tw.lines[0] == "" assert tw.lines[1] == " def f():" assert tw.lines[2] == " try:" diff --git a/testing/code/test_source.py b/testing/code/test_source.py index f7f272c7b6b..6432bf95c35 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -170,12 +170,12 @@ def f(x): def test_compile(self): co = _pytest._code.compile("x=3") d = {} - exec (co, d) + exec(co, d) assert d['x'] == 3 def test_compile_and_getsource_simple(self): co = _pytest._code.compile("x=3") - exec (co) + exec(co) source = _pytest._code.Source(co) assert str(source) == "x=3" @@ -342,8 +342,7 @@ def __init__(self, *args): self.source = _pytest._code.Frame(frame).statement x = A('x', - 'y' - , + 'y', 'z') l = [i for i in x.source.lines if i.strip()] diff --git a/testing/python/approx.py b/testing/python/approx.py index 9aed0fa0add..ebd0234de0e 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -9,6 +9,7 @@ from fractions import Fraction inf, nan = float('inf'), float('nan') + class MyDocTestRunner(doctest.DocTestRunner): def __init__(self): @@ -37,8 +38,8 @@ def test_repr_string(self): # Dictionaries aren't ordered, so we need to check both orders. 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({{'b': 2.0 {pm} {tol2}, 'a': 1.0 {pm} {tol1}}})".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), ) def test_operator_overloading(self): @@ -218,11 +219,11 @@ def test_expecting_inf(self): def test_expecting_nan(self): examples = [ - (eq, nan, nan), - (eq, -nan, -nan), - (eq, nan, -nan), - (ne, 0.0, nan), - (ne, inf, nan), + (eq, nan, nan), + (eq, -nan, -nan), + (eq, nan, -nan), + (ne, 0.0, nan), + (ne, inf, nan), ] for op, a, x in examples: # Nothing is equal to NaN by default. @@ -266,10 +267,10 @@ def test_fraction(self): def test_complex(self): within_1e6 = [ - ( 1.000001 + 1.0j, 1.0 + 1.0j), - (1.0 + 1.000001j, 1.0 + 1.0j), - (-1.000001 + 1.0j, -1.0 + 1.0j), - (1.0 - 1.000001j, 1.0 - 1.0j), + (1.000001 + 1.0j, 1.0 + 1.0j), + (1.0 + 1.000001j, 1.0 + 1.0j), + (-1.000001 + 1.0j, -1.0 + 1.0j), + (1.0 - 1.000001j, 1.0 - 1.0j), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) @@ -289,7 +290,7 @@ def test_list(self): def test_list_wrong_len(self): assert [1, 2] != approx([1]) - assert [1, 2] != approx([1,2,3]) + assert [1, 2] != approx([1, 2, 3]) def test_tuple(self): actual = (1 + 1e-7, 2 + 1e-8) @@ -303,7 +304,7 @@ def test_tuple(self): def test_tuple_wrong_len(self): assert (1, 2) != approx((1,)) - assert (1, 2) != approx((1,2,3)) + assert (1, 2) != approx((1, 2, 3)) def test_dict(self): actual = {'a': 1 + 1e-7, 'b': 2 + 1e-8} @@ -344,7 +345,7 @@ def test_numpy_array_wrong_shape(self): np = pytest.importorskip('numpy') a12 = np.array([[1, 2]]) - a21 = np.array([[1],[2]]) + a21 = np.array([[1], [2]]) assert a12 != approx(a21) assert a21 != approx(a12) diff --git a/testing/python/collect.py b/testing/python/collect.py index 64a4ff7aa8c..977ef1c82bf 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -151,7 +151,7 @@ def test_something(): pass """) 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 result.stdout.fnmatch_lines([ "*collected 0 items*", diff --git a/testing/test_cache.py b/testing/test_cache.py index 7fea5cdfd1e..36059ec296e 100755 --- a/testing/test_cache.py +++ b/testing/test_cache.py @@ -119,6 +119,7 @@ def test_custom_cache_dir_with_env_var(self, testdir, monkeypatch): testdir.runpytest() assert testdir.tmpdir.join('custom_cache_dir').isdir() + def test_cache_reportheader(testdir): testdir.makepyfile(""" def test_hello(): diff --git a/testing/test_capture.py b/testing/test_capture.py index 302a02d1015..a5d8c9c13e1 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -83,14 +83,14 @@ def test_capturing_basic_api(self, method): assert outerr == ("", "") outerr = capman.suspendcapture() assert outerr == ("", "") - print ("hello") + print("hello") out, err = capman.suspendcapture() if method == "no": assert old == (sys.stdout, sys.stderr, sys.stdin) else: assert not out capman.resumecapture() - print ("hello") + print("hello") out, err = capman.suspendcapture() if method != "no": assert out == "hello\n" @@ -305,7 +305,7 @@ def teardown_function(function): assert 0 """) for optargs in (('--capture=sys',), ('--capture=fd',)): - print (optargs) + print(optargs) result = testdir.runpytest_subprocess(p, *optargs) s = result.stdout.str() result.stdout.fnmatch_lines([ @@ -331,7 +331,7 @@ def teardown_module(function): assert 0 """) for optargs in (('--capture=sys',), ('--capture=fd',)): - print (optargs) + print(optargs) result = testdir.runpytest_subprocess(p, *optargs) s = result.stdout.str() result.stdout.fnmatch_lines([ @@ -879,7 +879,7 @@ def test_capturing_reset_simple(self): def test_capturing_readouterr(self): with self.getcapture() as cap: - print ("hello world") + print("hello world") sys.stderr.write("hello error\n") out, err = cap.readouterr() assert out == "hello world\n" @@ -890,7 +890,7 @@ def test_capturing_readouterr(self): def test_capturing_readouterr_unicode(self): with self.getcapture() as cap: - print ("hx\xc4\x85\xc4\x87") + print("hx\xc4\x85\xc4\x87") out, err = cap.readouterr() assert out == py.builtin._totext("hx\xc4\x85\xc4\x87\n", "utf8") @@ -905,7 +905,7 @@ def test_capturing_readouterr_decode_error_handling(self): def test_reset_twice_error(self): with self.getcapture() as cap: - print ("hello") + print("hello") out, err = cap.readouterr() pytest.raises(ValueError, cap.stop_capturing) assert out == "hello\n" @@ -919,7 +919,7 @@ def test_capturing_modify_sysouterr_in_between(self): sys.stderr.write("world") sys.stdout = capture.CaptureIO() sys.stderr = capture.CaptureIO() - print ("not seen") + print("not seen") sys.stderr.write("not seen\n") out, err = cap.readouterr() assert out == "hello" @@ -929,9 +929,9 @@ def test_capturing_modify_sysouterr_in_between(self): def test_capturing_error_recursive(self): with self.getcapture() as cap1: - print ("cap1") + print("cap1") with self.getcapture() as cap2: - print ("cap2") + print("cap2") out2, err2 = cap2.readouterr() out1, err1 = cap1.readouterr() assert out1 == "cap1\n" @@ -961,9 +961,9 @@ def test_stdin_restored(self): assert sys.stdin is old def test_stdin_nulled_by_default(self): - print ("XXX this test may well hang instead of crashing") - print ("XXX which indicates an error in the underlying capturing") - print ("XXX mechanisms") + print("XXX this test may well hang instead of crashing") + print("XXX which indicates an error in the underlying capturing") + print("XXX mechanisms") with self.getcapture(): pytest.raises(IOError, "sys.stdin.read()") diff --git a/testing/test_conftest.py b/testing/test_conftest.py index 05453f766a2..39590f5f260 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -321,9 +321,9 @@ def test_no_conftest(fxtr): # use value from parent dir's """)) - print ("created directory structure:") + print("created directory structure:") for x in testdir.tmpdir.visit(): - print (" " + x.relto(testdir.tmpdir)) + print(" " + x.relto(testdir.tmpdir)) return { "runner": runner, diff --git a/testing/test_mark.py b/testing/test_mark.py index 744e6ce522f..f3966d733a9 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -791,11 +791,10 @@ class FakeClass(object): def fake_method(self): pass - transfer_markers(fake_method, FakeClass, FakeModule) # legacy marks transfer smeared assert fake_method.nofun assert fake_method.fun # pristine marks dont transfer - assert fake_method.pytestmark == [pytest.mark.fun.mark] \ No newline at end of file + assert fake_method.pytestmark == [pytest.mark.fun.mark] diff --git a/testing/test_runner.py b/testing/test_runner.py index 842810f1b66..567b98eebe6 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -226,7 +226,7 @@ def teardown_function(func): raise ValueError(42) """) reps = rec.getreports("pytest_runtest_logreport") - print (reps) + print(reps) for i in range(2): assert reps[i].nodeid.endswith("test_method") assert reps[i].passed @@ -253,7 +253,7 @@ def test_method(self): assert True """) reps = rec.getreports("pytest_runtest_logreport") - print (reps) + print(reps) assert len(reps) == 3 # assert reps[0].nodeid.endswith("test_method") From bd96b0aabcfd8944f4f50995201a3584d78ce965 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Tue, 18 Jul 2017 09:47:06 -0300 Subject: [PATCH 52/58] Remove _pytest/impl file The file apparently contains an early design document to what has become @pytest.fixture and can be deleted --- _pytest/impl | 254 --------------------------------------------------- 1 file changed, 254 deletions(-) delete mode 100644 _pytest/impl diff --git a/_pytest/impl b/_pytest/impl deleted file mode 100644 index 889e37e5abc..00000000000 --- a/_pytest/impl +++ /dev/null @@ -1,254 +0,0 @@ -Sorting per-resource ------------------------------ - -for any given set of items: - -- collect items per session-scoped parametrized funcarg -- re-order until items no parametrizations are mixed - - examples: - - test() - test1(s1) - test1(s2) - test2() - test3(s1) - test3(s2) - - gets sorted to: - - test() - test2() - test1(s1) - test3(s1) - test1(s2) - test3(s2) - - -the new @setup functions --------------------------------------- - -Consider a given @setup-marked function:: - - @pytest.mark.setup(maxscope=SCOPE) - def mysetup(request, arg1, arg2, ...) - ... - request.addfinalizer(fin) - ... - -then FUNCARGSET denotes the set of (arg1, arg2, ...) funcargs and -all of its dependent funcargs. The mysetup function will execute -for any matching test item once per scope. - -The scope is determined as the minimum scope of all scopes of the args -in FUNCARGSET and the given "maxscope". - -If mysetup has been called and no finalizers have been called it is -called "active". - -Furthermore the following rules apply: - -- if an arg value in FUNCARGSET is about to be torn down, the - mysetup-registered finalizers will execute as well. - -- There will never be two active mysetup invocations. - -Example 1, session scope:: - - @pytest.mark.funcarg(scope="session", params=[1,2]) - def db(request): - request.addfinalizer(db_finalize) - - @pytest.mark.setup - def mysetup(request, db): - request.addfinalizer(mysetup_finalize) - ... - -And a given test module: - - def test_something(): - ... - def test_otherthing(): - pass - -Here is what happens:: - - db(request) executes with request.param == 1 - mysetup(request, db) executes - test_something() executes - test_otherthing() executes - mysetup_finalize() executes - db_finalize() executes - db(request) executes with request.param == 2 - mysetup(request, db) executes - test_something() executes - test_otherthing() executes - mysetup_finalize() executes - db_finalize() executes - -Example 2, session/function scope:: - - @pytest.mark.funcarg(scope="session", params=[1,2]) - def db(request): - request.addfinalizer(db_finalize) - - @pytest.mark.setup(scope="function") - def mysetup(request, db): - ... - request.addfinalizer(mysetup_finalize) - ... - -And a given test module: - - def test_something(): - ... - def test_otherthing(): - pass - -Here is what happens:: - - db(request) executes with request.param == 1 - mysetup(request, db) executes - test_something() executes - mysetup_finalize() executes - mysetup(request, db) executes - test_otherthing() executes - mysetup_finalize() executes - db_finalize() executes - db(request) executes with request.param == 2 - mysetup(request, db) executes - test_something() executes - mysetup_finalize() executes - mysetup(request, db) executes - test_otherthing() executes - mysetup_finalize() executes - db_finalize() executes - - -Example 3 - funcargs session-mix ----------------------------------------- - -Similar with funcargs, an example:: - - @pytest.mark.funcarg(scope="session", params=[1,2]) - def db(request): - request.addfinalizer(db_finalize) - - @pytest.mark.funcarg(scope="function") - def table(request, db): - ... - request.addfinalizer(table_finalize) - ... - -And a given test module: - - def test_something(table): - ... - def test_otherthing(table): - pass - def test_thirdthing(): - pass - -Here is what happens:: - - db(request) executes with param == 1 - table(request, db) - test_something(table) - table_finalize() - table(request, db) - test_otherthing(table) - table_finalize() - db_finalize - db(request) executes with param == 2 - table(request, db) - test_something(table) - table_finalize() - table(request, db) - test_otherthing(table) - table_finalize() - db_finalize - test_thirdthing() - -Data structures --------------------- - -pytest internally maintains a dict of active funcargs with cache, param, -finalizer, (scopeitem?) information: - - active_funcargs = dict() - -if a parametrized "db" is activated: - - active_funcargs["db"] = FuncargInfo(dbvalue, paramindex, - FuncargFinalize(...), scopeitem) - -if a test is torn down and the next test requires a differently -parametrized "db": - - for argname in item.callspec.params: - if argname in active_funcargs: - funcarginfo = active_funcargs[argname] - if funcarginfo.param != item.callspec.params[argname]: - funcarginfo.callfinalizer() - del node2funcarg[funcarginfo.scopeitem] - del active_funcargs[argname] - nodes_to_be_torn_down = ... - for node in nodes_to_be_torn_down: - if node in node2funcarg: - argname = node2funcarg[node] - active_funcargs[argname].callfinalizer() - del node2funcarg[node] - del active_funcargs[argname] - -if a test is setup requiring a "db" funcarg: - - if "db" in active_funcargs: - return active_funcargs["db"][0] - funcarginfo = setup_funcarg() - active_funcargs["db"] = funcarginfo - node2funcarg[funcarginfo.scopeitem] = "db" - -Implementation plan for resources ------------------------------------------- - -1. Revert FuncargRequest to the old form, unmerge item/request - (done) -2. make funcarg factories be discovered at collection time -3. Introduce funcarg marker -4. Introduce funcarg scope parameter -5. Introduce funcarg parametrize parameter -6. make setup functions be discovered at collection time -7. (Introduce a pytest_fixture_protocol/setup_funcargs hook) - -methods and data structures --------------------------------- - -A FuncarcManager holds all information about funcarg definitions -including parametrization and scope definitions. It implements -a pytest_generate_tests hook which performs parametrization as appropriate. - -as a simple example, let's consider a tree where a test function requires -a "abc" funcarg and its factory defines it as parametrized and scoped -for Modules. When collections hits the function item, it creates -the metafunc object, and calls funcargdb.pytest_generate_tests(metafunc) -which looks up available funcarg factories and their scope and parametrization. -This information is equivalent to what can be provided today directly -at the function site and it should thus be relatively straight forward -to implement the additional way of defining parametrization/scoping. - -conftest loading: - each funcarg-factory will populate the session.funcargmanager - -When a test item is collected, it grows a dictionary -(funcargname2factorycalllist). A factory lookup is performed -for each required funcarg. The resulting factory call is stored -with the item. If a function is parametrized multiple items are -created with respective factory calls. Else if a factory is parametrized -multiple items and calls to the factory function are created as well. - -At setup time, an item populates a funcargs mapping, mapping names -to values. If a value is funcarg factories are queried for a given item -test functions and setup functions are put in a class -which looks up required funcarg factories. - - From 2840634c2c918fb5ff74536999a2f7de495a6ea4 Mon Sep 17 00:00:00 2001 From: Raphael Pierzina Date: Sat, 15 Jul 2017 11:45:28 +0200 Subject: [PATCH 53/58] Fix typo and improve comment about cookiecutter-template --- doc/en/writing_plugins.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/en/writing_plugins.rst b/doc/en/writing_plugins.rst index 9f5190c3eed..25097db6d5e 100644 --- a/doc/en/writing_plugins.rst +++ b/doc/en/writing_plugins.rst @@ -122,8 +122,8 @@ to extend and add functionality. for authoring plugins. The template provides an excellent starting point with a working plugin, - tests running with tox, comprehensive README and - entry-pointy already pre-configured. + tests running with tox, a comprehensive README file as well as a + pre-configured entry-point. Also consider :ref:`contributing your plugin to pytest-dev` once it has some happy users other than yourself. From 91b4b229aa82711c3ee4eaa8159fe5face1bbcfb Mon Sep 17 00:00:00 2001 From: Raphael Pierzina Date: Sat, 15 Jul 2017 16:48:02 +0200 Subject: [PATCH 54/58] Update documentation for testing plugin code --- doc/en/writing_plugins.rst | 81 ++++++++++++++++++++++++++++---------- 1 file changed, 60 insertions(+), 21 deletions(-) diff --git a/doc/en/writing_plugins.rst b/doc/en/writing_plugins.rst index 25097db6d5e..85c9e6b71b2 100644 --- a/doc/en/writing_plugins.rst +++ b/doc/en/writing_plugins.rst @@ -286,34 +286,73 @@ the ``--trace-config`` option. Testing plugins --------------- -pytest comes with some facilities that you can enable for testing your -plugin. Given that you have an installed plugin you can enable the -:py:class:`testdir <_pytest.pytester.Testdir>` fixture via specifying a -command line option to include the pytester plugin (``-p pytester``) or -by putting ``pytest_plugins = "pytester"`` into your test or -``conftest.py`` file. You then will have a ``testdir`` fixture which you -can use like this:: +pytest comes with a plugin named ``pytester`` that helps you write tests for +your plugin code. The plugin is disabled by default, so you will have to enable +it before you can use it. - # content of test_myplugin.py +You can do so by adding the following line to a ``conftest.py`` file in your +testing directory: - pytest_plugins = "pytester" # to get testdir fixture +.. code-block:: python - def test_myplugin(testdir): - testdir.makepyfile(""" - def test_example(): - pass + # content of conftest.py + + pytest_plugins = ["pytester"] + +Alternatively you can invoke pytest with the ``-p pytester`` command line +option. + +This will allow you to use the :py:class:`testdir <_pytest.pytester.Testdir>` +fixture for testing your plugin code. + +Let's demonstrate what you can do with the plugin with an example. Imagine we +developed a plugin that provides a fixture ``hello`` which yields a function +and we can invoke this function with one optional parameter. It will return a +string value of ``Hello World!`` if we do not supply a value or ``Hello +{value}!`` if we do supply a string value. + +Now the ``testdir`` fixture provides a convenient API for creating temporary +``conftest.py`` files and test files. It also allows us to run the tests and +return a result object, with which we can assert the tests' outcomes. + +.. code-block:: python + + def test_hello(testdir): + """Make sure that our plugin works.""" + + # create a temporary conftest.py file + testdir.makeconftest(""" + import pytest + + @pytest.fixture(params=[ + "Brianna", + "Andreas", + "Floris", + ]) + def name(request): + return request.param """) - result = testdir.runpytest("--verbose") - result.stdout.fnmatch_lines(""" - test_example* + + # create a temporary pytest test file + testdir.makepyfile(""" + def test_hello_default(hello): + assert hello() == "Hello World!" + + def test_hello_name(hello, name): + assert hello(name) == "Hello {0}!".format(name) """) -Note that by default ``testdir.runpytest()`` will perform a pytest -in-process. You can pass the command line option ``--runpytest=subprocess`` -to have it happen in a subprocess. + # run all tests with pytest + result = testdir.runpytest() + + # check that all 4 tests passed + result.assert_outcomes(passed=4) + + +For more information about the result object, that ``runpytest()`` returns, and +the methods that it provides please check out the :py:class:`RunResult +<_pytest.pytester.RunResult>` documentation. -Also see the :py:class:`RunResult <_pytest.pytester.RunResult>` for more -methods of the result object that you get from a call to ``runpytest``. .. _`writinghooks`: From e73a2f7ad98e35ec6ee972d2003a417731c1eb86 Mon Sep 17 00:00:00 2001 From: Raphael Pierzina Date: Wed, 19 Jul 2017 18:57:32 +0200 Subject: [PATCH 55/58] Add changelog entry changelog/971.doc --- changelog/971.doc | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog/971.doc diff --git a/changelog/971.doc b/changelog/971.doc new file mode 100644 index 00000000000..e182cf8eeb7 --- /dev/null +++ b/changelog/971.doc @@ -0,0 +1 @@ +Extend documentation for testing plugin code with the ``pytester`` plugin. From d06d97a7ac6b9f6c723eadaa2fc3fd59e2f91b4f Mon Sep 17 00:00:00 2001 From: Raphael Pierzina Date: Wed, 19 Jul 2017 19:42:33 +0200 Subject: [PATCH 56/58] Remove unnecessary comma from docs --- doc/en/writing_plugins.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/en/writing_plugins.rst b/doc/en/writing_plugins.rst index 85c9e6b71b2..ad568ee33f2 100644 --- a/doc/en/writing_plugins.rst +++ b/doc/en/writing_plugins.rst @@ -349,7 +349,7 @@ return a result object, with which we can assert the tests' outcomes. result.assert_outcomes(passed=4) -For more information about the result object, that ``runpytest()`` returns, and +For more information about the result object that ``runpytest()`` returns, and the methods that it provides please check out the :py:class:`RunResult <_pytest.pytester.RunResult>` documentation. From 1ac02b8a3bb41864ffe2c2aa028ef385adb559b8 Mon Sep 17 00:00:00 2001 From: Raphael Pierzina Date: Wed, 19 Jul 2017 20:14:46 +0200 Subject: [PATCH 57/58] Add plugin code --- doc/en/writing_plugins.rst | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/doc/en/writing_plugins.rst b/doc/en/writing_plugins.rst index ad568ee33f2..861f2f48a0e 100644 --- a/doc/en/writing_plugins.rst +++ b/doc/en/writing_plugins.rst @@ -311,6 +311,34 @@ and we can invoke this function with one optional parameter. It will return a string value of ``Hello World!`` if we do not supply a value or ``Hello {value}!`` if we do supply a string value. +.. code-block:: python + + # -*- coding: utf-8 -*- + + import pytest + + def pytest_addoption(parser): + group = parser.getgroup('helloworld') + group.addoption( + '--name', + action='store', + dest='name', + default='World', + help='Default "name" for hello().' + ) + + @pytest.fixture + def hello(request): + name = request.config.option.name + + def _hello(name=None): + if not name: + name = request.config.option.name + return "Hello {name}!".format(name=name) + + return _hello + + Now the ``testdir`` fixture provides a convenient API for creating temporary ``conftest.py`` files and test files. It also allows us to run the tests and return a result object, with which we can assert the tests' outcomes. From 24da93832138b048c9126bbd7f1ab7bf6c091edf Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Wed, 19 Jul 2017 17:42:21 -0300 Subject: [PATCH 58/58] Fix additional flake8 errors --- testing/code/test_source.py | 3 ++- testing/python/approx.py | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/testing/code/test_source.py b/testing/code/test_source.py index 6432bf95c35..f8b6af3ee58 100644 --- a/testing/code/test_source.py +++ b/testing/code/test_source.py @@ -342,7 +342,8 @@ def __init__(self, *args): self.source = _pytest._code.Frame(frame).statement x = A('x', - 'y', + 'y' + , 'z') l = [i for i in x.source.lines if i.strip()] diff --git a/testing/python/approx.py b/testing/python/approx.py index ebd0234de0e..876226e068e 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -29,7 +29,9 @@ def test_repr_string(self): if sys.version_info[:2] == (2, 6): tol1, tol2, infr = '???', '???', '???' assert repr(approx(1.0)) == '1.0 {pm} {tol1}'.format(pm=plus_minus, tol1=tol1) - assert repr(approx([1.0, 2.0])) == '1.0 {pm} {tol1}, 2.0 {pm} {tol2}'.format( + assert repr(approx([1.0, 2.0])) == 'approx([1.0 {pm} {tol1}, 2.0 {pm} {tol2}])'.format( + pm=plus_minus, tol1=tol1, tol2=tol2) + assert repr(approx((1.0, 2.0))) == 'approx((1.0 {pm} {tol1}, 2.0 {pm} {tol2}))'.format( pm=plus_minus, tol1=tol1, tol2=tol2) assert repr(approx(inf)) == 'inf' assert repr(approx(1.0, rel=nan)) == '1.0 {pm} ???'.format(pm=plus_minus)