From b8471aa527ab1a21ee66f24e5c23a9773b5b0793 Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Sat, 18 Jul 2020 12:35:13 +0300 Subject: [PATCH 1/2] testing: fix some docstring issues In preparation for enforcing some docstring lints. --- doc/en/example/nonpython/conftest.py | 9 ++-- scripts/release.py | 4 +- testing/acceptance_test.py | 28 +++++-------- testing/code/test_excinfo.py | 2 +- testing/freeze/create_executable.py | 4 +- testing/logging/test_fixture.py | 8 ++-- testing/logging/test_reporting.py | 19 +++------ testing/python/approx.py | 4 +- testing/python/collect.py | 12 +++--- testing/python/fixtures.py | 10 ++--- testing/python/metafunc.py | 61 ++++++++++++---------------- testing/python/raises.py | 4 +- testing/test_argcomplete.py | 14 +++---- testing/test_assertion.py | 17 +++----- testing/test_assertrewrite.py | 11 ++--- testing/test_cacheprovider.py | 4 +- testing/test_capture.py | 9 ++-- testing/test_collection.py | 6 +-- testing/test_config.py | 14 +++---- testing/test_conftest.py | 4 +- testing/test_doctest.py | 20 +++------ testing/test_faulthandler.py | 14 +++---- testing/test_helpconfig.py | 6 +-- testing/test_junitxml.py | 17 ++++---- testing/test_link_resolve.py | 4 +- testing/test_mark.py | 18 ++++---- testing/test_meta.py | 3 +- testing/test_pastebin.py | 16 +++----- testing/test_pathlib.py | 11 +++-- testing/test_pluginmanager.py | 4 +- testing/test_pytester.py | 8 ++-- testing/test_reports.py | 7 +--- testing/test_runner.py | 15 +++---- testing/test_runner_xunit.py | 7 +--- testing/test_setuponly.py | 2 +- testing/test_setupplan.py | 9 ++-- testing/test_skipping.py | 21 +++------- testing/test_terminal.py | 21 ++++------ testing/test_unittest.py | 4 +- testing/test_warnings.py | 19 +++------ 40 files changed, 175 insertions(+), 295 deletions(-) diff --git a/doc/en/example/nonpython/conftest.py b/doc/en/example/nonpython/conftest.py index d30ab3841dc..6e5a5709290 100644 --- a/doc/en/example/nonpython/conftest.py +++ b/doc/en/example/nonpython/conftest.py @@ -9,7 +9,8 @@ def pytest_collect_file(parent, path): class YamlFile(pytest.File): def collect(self): - import yaml # we need a yaml parser, e.g. PyYAML + # We need a yaml parser, e.g. PyYAML. + import yaml raw = yaml.safe_load(self.fspath.open()) for name, spec in sorted(raw.items()): @@ -23,12 +24,12 @@ def __init__(self, name, parent, spec): def runtest(self): for name, value in sorted(self.spec.items()): - # some custom test execution (dumb example follows) + # Some custom test execution (dumb example follows). if name != value: raise YamlException(self, name, value) def repr_failure(self, excinfo): - """ called when self.runtest() raises an exception. """ + """Called when self.runtest() raises an exception.""" if isinstance(excinfo.value, YamlException): return "\n".join( [ @@ -43,4 +44,4 @@ def reportinfo(self): class YamlException(Exception): - """ custom exception for error reporting. """ + """Custom exception for error reporting.""" diff --git a/scripts/release.py b/scripts/release.py index 443b868f3d7..5e3158ab52b 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -1,6 +1,4 @@ -""" -Invoke development tasks. -""" +"""Invoke development tasks.""" import argparse import os from pathlib import Path diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index 2a386e2c6e4..3172dad7cc3 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -403,15 +403,12 @@ def pytest_sessionfinish(exitstatus): result.stdout.fnmatch_lines(["pytest_sessionfinish_called"]) assert result.ret == ExitCode.USAGE_ERROR - @pytest.mark.usefixtures("recwarn") def test_namespace_import_doesnt_confuse_import_hook(self, testdir): - """ - Ref #383. Python 3.3's namespace package messed with our import hooks + """Ref #383. + + Python 3.3's namespace package messed with our import hooks. Importing a module that didn't exist, even if the ImportError was gracefully handled, would make our test crash. - - Use recwarn here to silence this warning in Python 2.7: - ImportWarning: Not importing directory '...\not_a_package': missing __init__.py """ testdir.mkdir("not_a_package") p = testdir.makepyfile( @@ -457,10 +454,8 @@ def test_foo(invalid_fixture): ) def test_plugins_given_as_strings(self, tmpdir, monkeypatch, _sys_snapshot): - """test that str values passed to main() as `plugins` arg - are interpreted as module names to be imported and registered. - #855. - """ + """Test that str values passed to main() as `plugins` arg are + interpreted as module names to be imported and registered (#855).""" with pytest.raises(ImportError) as excinfo: pytest.main([str(tmpdir)], plugins=["invalid.module"]) assert "invalid" in str(excinfo.value) @@ -664,8 +659,7 @@ def test_cmdline_python_package(self, testdir, monkeypatch): result.stderr.fnmatch_lines(["*not*found*test_missing*"]) def test_cmdline_python_namespace_package(self, testdir, monkeypatch): - """ - test --pyargs option with namespace packages (#1567) + """Test --pyargs option with namespace packages (#1567). Ref: https://packaging.python.org/guides/packaging-namespace-packages/ """ @@ -1011,9 +1005,7 @@ def test_pytest_plugins_as_module(testdir): def test_deferred_hook_checking(testdir): - """ - Check hooks as late as possible (#1821). - """ + """Check hooks as late as possible (#1821).""" testdir.syspathinsert() testdir.makepyfile( **{ @@ -1089,8 +1081,7 @@ def test2(): def test_fixture_order_respects_scope(testdir): - """Ensure that fixtures are created according to scope order, regression test for #2405 - """ + """Ensure that fixtures are created according to scope order (#2405).""" testdir.makepyfile( """ import pytest @@ -1115,7 +1106,8 @@ def test_value(): def test_frame_leak_on_failing_test(testdir): - """pytest would leak garbage referencing the frames of tests that failed that could never be reclaimed (#2798) + """Pytest would leak garbage referencing the frames of tests that failed + that could never be reclaimed (#2798). Unfortunately it was not possible to remove the actual circles because most of them are made of traceback objects which cannot be weakly referenced. Those objects at least diff --git a/testing/code/test_excinfo.py b/testing/code/test_excinfo.py index 78b55e26e01..75446c570b2 100644 --- a/testing/code/test_excinfo.py +++ b/testing/code/test_excinfo.py @@ -464,7 +464,7 @@ def f(x): assert lines[1] == " pass" def test_repr_source_excinfo(self) -> None: - """ check if indentation is right """ + """Check if indentation is right.""" try: def f(): diff --git a/testing/freeze/create_executable.py b/testing/freeze/create_executable.py index b53eb09f53b..998df7b1ca7 100644 --- a/testing/freeze/create_executable.py +++ b/testing/freeze/create_executable.py @@ -1,6 +1,4 @@ -""" -Generates an executable with pytest runner embedded using PyInstaller. -""" +"""Generate an executable with pytest runner embedded using PyInstaller.""" if __name__ == "__main__": import pytest import subprocess diff --git a/testing/logging/test_fixture.py b/testing/logging/test_fixture.py index 6e5e9c2b42a..cbd28f798bf 100644 --- a/testing/logging/test_fixture.py +++ b/testing/logging/test_fixture.py @@ -268,10 +268,10 @@ def test_log_level_override(request, caplog): def test_log_report_captures_according_to_config_option_upon_failure(testdir): - """ Test that upon failure: - (1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised - (2) The `DEBUG` message does NOT appear in the `Captured log call` report - (3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO` + """Test that upon failure: + (1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised. + (2) The `DEBUG` message does NOT appear in the `Captured log call` report. + (3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO`. """ testdir.makepyfile( """ diff --git a/testing/logging/test_reporting.py b/testing/logging/test_reporting.py index 32224325884..bab28aea4ef 100644 --- a/testing/logging/test_reporting.py +++ b/testing/logging/test_reporting.py @@ -1066,10 +1066,8 @@ def test_second(): def test_colored_captured_log(testdir): - """ - Test that the level names of captured log messages of a failing test are - colored. - """ + """Test that the level names of captured log messages of a failing test + are colored.""" testdir.makepyfile( """ import logging @@ -1092,9 +1090,7 @@ def test_foo(): def test_colored_ansi_esc_caplogtext(testdir): - """ - Make sure that caplog.text does not contain ANSI escape sequences. - """ + """Make sure that caplog.text does not contain ANSI escape sequences.""" testdir.makepyfile( """ import logging @@ -1111,8 +1107,7 @@ def test_foo(caplog): def test_logging_emit_error(testdir: Testdir) -> None: - """ - An exception raised during emit() should fail the test. + """An exception raised during emit() should fail the test. The default behavior of logging is to print "Logging error" to stderr with the call stack and some extra details. @@ -1138,10 +1133,8 @@ def test_bad_log(): def test_logging_emit_error_supressed(testdir: Testdir) -> None: - """ - If logging is configured to silently ignore errors, pytest - doesn't propagate errors either. - """ + """If logging is configured to silently ignore errors, pytest + doesn't propagate errors either.""" testdir.makepyfile( """ import logging diff --git a/testing/python/approx.py b/testing/python/approx.py index db67fe5aa7f..194423dc3b0 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -488,9 +488,7 @@ def test_expected_value_type_error(self, x): ], ) def test_comparison_operator_type_error(self, op): - """ - pytest.approx should raise TypeError for operators other than == and != (#2003). - """ + """pytest.approx should raise TypeError for operators other than == and != (#2003).""" with pytest.raises(TypeError): op(1, approx(1, rel=1e-6, abs=1e-12)) diff --git a/testing/python/collect.py b/testing/python/collect.py index ed778c265ff..778ceeddf8d 100644 --- a/testing/python/collect.py +++ b/testing/python/collect.py @@ -984,8 +984,7 @@ def test_traceback_error_during_import(self, testdir): result.stdout.fnmatch_lines([">*asd*", "E*NameError*"]) def test_traceback_filter_error_during_fixture_collection(self, testdir): - """integration test for issue #995. - """ + """Integration test for issue #995.""" testdir.makepyfile( """ import pytest @@ -1011,8 +1010,9 @@ def test_failing_fixture(fail_fixture): result.stdout.fnmatch_lines(["*ValueError: fail me*", "* 1 error in *"]) def test_filter_traceback_generated_code(self) -> None: - """test that filter_traceback() works with the fact that + """Test that filter_traceback() works with the fact that _pytest._code.code.Code.path attribute might return an str object. + In this case, one of the entries on the traceback was produced by dynamically generated code. See: https://bitbucket.org/pytest-dev/py/issues/71 @@ -1033,8 +1033,9 @@ def test_filter_traceback_generated_code(self) -> None: assert not filter_traceback(traceback[-1]) def test_filter_traceback_path_no_longer_valid(self, testdir) -> None: - """test that filter_traceback() works with the fact that + """Test that filter_traceback() works with the fact that _pytest._code.code.Code.path attribute might return an str object. + In this case, one of the files in the traceback no longer exists. This fixes #1133. """ @@ -1250,8 +1251,7 @@ def test_injection(self): def test_syntax_error_with_non_ascii_chars(testdir): - """Fix decoding issue while formatting SyntaxErrors during collection (#578) - """ + """Fix decoding issue while formatting SyntaxErrors during collection (#578).""" testdir.makepyfile("☃") result = testdir.runpytest() result.stdout.fnmatch_lines(["*ERROR collecting*", "*SyntaxError*", "*1 error in*"]) diff --git a/testing/python/fixtures.py b/testing/python/fixtures.py index 70370915b0e..8ea1a75ff6f 100644 --- a/testing/python/fixtures.py +++ b/testing/python/fixtures.py @@ -1684,10 +1684,8 @@ def test_func2(request): reprec.assertoutcome(passed=2) def test_callables_nocode(self, testdir): - """ - an imported mock.call would break setup/factory discovery - due to it being callable and __code__ not being a code object - """ + """An imported mock.call would break setup/factory discovery due to + it being callable and __code__ not being a code object.""" testdir.makepyfile( """ class _call(tuple): @@ -3333,9 +3331,7 @@ def fixture1(self): ) def test_show_fixtures_different_files(self, testdir): - """ - #833: --fixtures only shows fixtures from first file - """ + """`--fixtures` only shows fixtures from first file (#833).""" testdir.makepyfile( test_a=''' import pytest diff --git a/testing/python/metafunc.py b/testing/python/metafunc.py index f7cf2533b99..7aa608a0423 100644 --- a/testing/python/metafunc.py +++ b/testing/python/metafunc.py @@ -29,9 +29,9 @@ class TestMetafunc: def Metafunc(self, func, config=None) -> python.Metafunc: - # the unit tests of this class check if things work correctly + # The unit tests of this class check if things work correctly # on the funcarg level, so we don't need a full blown - # initialization + # initialization. class FuncFixtureInfoMock: name2fixturedefs = None @@ -136,7 +136,7 @@ def func(request): metafunc.parametrize("request", [1]) def test_find_parametrized_scope(self) -> None: - """unittest for _find_parametrized_scope (#3941)""" + """Unit test for _find_parametrized_scope (#3941).""" from _pytest.python import _find_parametrized_scope @attr.s @@ -285,30 +285,29 @@ def test_idval_hypothesis(self, value) -> None: escaped.encode("ascii") def test_unicode_idval(self) -> None: - """This tests that Unicode strings outside the ASCII character set get + """Test that Unicode strings outside the ASCII character set get escaped, using byte escapes if they're in that range or unicode escapes if they're not. """ values = [ - ("", ""), - ("ascii", "ascii"), - ("ação", "a\\xe7\\xe3o"), - ("josé@blah.com", "jos\\xe9@blah.com"), + ("", r""), + ("ascii", r"ascii"), + ("ação", r"a\xe7\xe3o"), + ("josé@blah.com", r"jos\xe9@blah.com"), ( - "δοκ.ιμή@παράδειγμα.δοκιμή", - "\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3" - "\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae", + r"δοκ.ιμή@παράδειγμα.δοκιμή", + r"\u03b4\u03bf\u03ba.\u03b9\u03bc\u03ae@\u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3" + r"\u03bc\u03b1.\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae", ), ] for val, expected in values: assert _idval(val, "a", 6, None, nodeid=None, config=None) == expected def test_unicode_idval_with_config(self) -> None: - """unittest for expected behavior to obtain ids with + """Unit test for expected behavior to obtain ids with disable_test_id_escaping_and_forfeit_all_rights_to_community_support - option. (#5294) - """ + option (#5294).""" class MockConfig: def __init__(self, config): @@ -335,25 +334,20 @@ def getini(self, name): assert actual == expected def test_bytes_idval(self) -> None: - """unittest for the expected behavior to obtain ids for parametrized - bytes values: - - python2: non-ascii strings are considered bytes and formatted using - "binary escape", where any byte < 127 is escaped into its hex form. - - python3: bytes objects are always escaped using "binary escape". - """ + """Unit test for the expected behavior to obtain ids for parametrized + bytes values: bytes objects are always escaped using "binary escape".""" values = [ - (b"", ""), - (b"\xc3\xb4\xff\xe4", "\\xc3\\xb4\\xff\\xe4"), - (b"ascii", "ascii"), - ("αρά".encode(), "\\xce\\xb1\\xcf\\x81\\xce\\xac"), + (b"", r""), + (b"\xc3\xb4\xff\xe4", r"\xc3\xb4\xff\xe4"), + (b"ascii", r"ascii"), + ("αρά".encode(), r"\xce\xb1\xcf\x81\xce\xac"), ] for val, expected in values: assert _idval(val, "a", 6, idfn=None, nodeid=None, config=None) == expected def test_class_or_function_idval(self) -> None: - """unittest for the expected behavior to obtain ids for parametrized - values that are classes or functions: their __name__. - """ + """Unit test for the expected behavior to obtain ids for parametrized + values that are classes or functions: their __name__.""" class TestClass: pass @@ -484,9 +478,9 @@ def ids(val: object) -> str: assert result == ["a-a0", "a-a1", "a-a2"] def test_idmaker_with_idfn_and_config(self) -> None: - """unittest for expected behavior to create ids with idfn and + """Unit test for expected behavior to create ids with idfn and disable_test_id_escaping_and_forfeit_all_rights_to_community_support - option. (#5294) + option (#5294). """ class MockConfig: @@ -516,9 +510,9 @@ def getini(self, name): assert result == [expected] def test_idmaker_with_ids_and_config(self) -> None: - """unittest for expected behavior to create ids with ids and + """Unit test for expected behavior to create ids with ids and disable_test_id_escaping_and_forfeit_all_rights_to_community_support - option. (#5294) + option (#5294). """ class MockConfig: @@ -1420,9 +1414,8 @@ def test_foo(x): class TestMetafuncFunctionalAuto: - """ - Tests related to automatically find out the correct scope for parametrized tests (#1832). - """ + """Tests related to automatically find out the correct scope for + parametrized tests (#1832).""" def test_parametrize_auto_scope(self, testdir: Testdir) -> None: testdir.makepyfile( diff --git a/testing/python/raises.py b/testing/python/raises.py index 46b200921e3..26931a37844 100644 --- a/testing/python/raises.py +++ b/testing/python/raises.py @@ -157,9 +157,7 @@ def test_no_raise_message(self) -> None: @pytest.mark.parametrize("method", ["function", "function_match", "with"]) def test_raises_cyclic_reference(self, method): - """ - Ensure pytest.raises does not leave a reference cycle (#1965). - """ + """Ensure pytest.raises does not leave a reference cycle (#1965).""" import gc class T: diff --git a/testing/test_argcomplete.py b/testing/test_argcomplete.py index 08362c62a63..9cab242c0e0 100644 --- a/testing/test_argcomplete.py +++ b/testing/test_argcomplete.py @@ -3,7 +3,7 @@ import pytest -# test for _argcomplete but not specific for any application +# Test for _argcomplete but not specific for any application. def equal_with_bash(prefix, ffc, fc, out=None): @@ -18,9 +18,9 @@ def equal_with_bash(prefix, ffc, fc, out=None): return retval -# copied from argcomplete.completers as import from there -# also pulls in argcomplete.__init__ which opens filedescriptor 9 -# this gives an OSError at the end of testrun +# Copied from argcomplete.completers as import from there. +# Also pulls in argcomplete.__init__ which opens filedescriptor 9. +# This gives an OSError at the end of testrun. def _wrapcall(*args, **kargs): @@ -31,7 +31,7 @@ def _wrapcall(*args, **kargs): class FilesCompleter: - "File completer class, optionally takes a list of allowed extensions" + """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 @@ -91,9 +91,7 @@ def test_compare_with_compgen(self, tmpdir): @pytest.mark.skipif("sys.platform in ('win32', 'darwin')") def test_remove_dir_prefix(self): - """this is not compatible with compgen but it is with bash itself: - ls /usr/ - """ + """This is not compatible with compgen but it is with bash itself: ls /usr/.""" from _pytest._argcomplete import FastFilesCompleter ffc = FastFilesCompleter() diff --git a/testing/test_assertion.py b/testing/test_assertion.py index 2adfb98a8d0..1cb63a329f6 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -29,9 +29,7 @@ class TestImportHookInstallation: @pytest.mark.parametrize("initial_conftest", [True, False]) @pytest.mark.parametrize("mode", ["plain", "rewrite"]) def test_conftest_assertion_rewrite(self, testdir, initial_conftest, mode): - """Test that conftest files are using assertion rewrite on import. - (#1619) - """ + """Test that conftest files are using assertion rewrite on import (#1619).""" testdir.tmpdir.join("foo/tests").ensure(dir=1) conftest_path = "conftest.py" if initial_conftest else "foo/conftest.py" contents = { @@ -569,7 +567,7 @@ def test_dict_omitting(self) -> None: assert "b" not in line def test_dict_omitting_with_verbosity_1(self) -> None: - """ Ensure differing items are visible for verbosity=1 (#1512) """ + """Ensure differing items are visible for verbosity=1 (#1512).""" lines = callequal({"a": 0, "b": 1}, {"a": 1, "b": 1}, verbose=1) assert lines is not None assert lines[1].startswith("Omitting 1 identical item") @@ -719,10 +717,7 @@ def __repr__(self): ] def test_one_repr_empty(self): - """ - the faulty empty string repr did trigger - an unbound local error in _diff_text - """ + """The faulty empty string repr did trigger an unbound local error in _diff_text.""" class A(str): def __repr__(self): @@ -1135,7 +1130,7 @@ def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self): assert last_line_before_trunc_msg.endswith("...") def test_full_output_truncated(self, monkeypatch, testdir): - """ Test against full runpytest() output. """ + """Test against full runpytest() output.""" line_count = 7 line_len = 100 @@ -1370,9 +1365,7 @@ def test_onefails(): def test_exception_handling_no_traceback(testdir): - """ - Handle chain exceptions in tasks submitted by the multiprocess module (#1984). - """ + """Handle chain exceptions in tasks submitted by the multiprocess module (#1984).""" p1 = testdir.makepyfile( """ from multiprocessing import Pool diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index e403bb2ec9b..23f535173c2 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -233,7 +233,7 @@ def f() -> None: def test_dont_rewrite_if_hasattr_fails(self, request) -> None: class Y: - """ A class whos getattr fails, but not with `AttributeError` """ + """A class whose getattr fails, but not with `AttributeError`.""" def __getattr__(self, attribute_name): raise KeyError() @@ -911,10 +911,8 @@ def test_rewritten(): assert testdir.runpytest_subprocess().ret == 0 def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch): - """ - AssertionRewriteHook should remember rewritten modules so it - doesn't give false positives (#2005). - """ + """`AssertionRewriteHook` should remember rewritten modules so it + doesn't give false positives (#2005).""" monkeypatch.syspath_prepend(testdir.tmpdir) testdir.makepyfile(test_remember_rewritten_modules="") warnings = [] @@ -1091,8 +1089,7 @@ def test_loader(): result.stdout.fnmatch_lines(["* 1 passed*"]) def test_get_data_support(self, testdir): - """Implement optional PEP302 api (#808). - """ + """Implement optional PEP302 api (#808).""" path = testdir.mkpydir("foo") path.join("test_foo.py").write( textwrap.dedent( diff --git a/testing/test_cacheprovider.py b/testing/test_cacheprovider.py index c133663ea1b..a911257ce24 100644 --- a/testing/test_cacheprovider.py +++ b/testing/test_cacheprovider.py @@ -643,9 +643,7 @@ def get_cached_last_failed(self, testdir): return sorted(config.cache.get("cache/lastfailed", {})) def test_cache_cumulative(self, testdir): - """ - Test workflow where user fixes errors gradually file by file using --lf. - """ + """Test workflow where user fixes errors gradually file by file using --lf.""" # 1. initial run test_bar = testdir.makepyfile( test_bar=""" diff --git a/testing/test_capture.py b/testing/test_capture.py index bc89501c73b..15077a3e974 100644 --- a/testing/test_capture.py +++ b/testing/test_capture.py @@ -635,9 +635,8 @@ def test_normal(): @pytest.mark.parametrize("fixture", ["capsys", "capfd"]) def test_fixture_use_by_other_fixtures(self, testdir, fixture): - """ - Ensure that capsys and capfd can be used by other fixtures during setup and teardown. - """ + """Ensure that capsys and capfd can be used by other fixtures during + setup and teardown.""" testdir.makepyfile( """\ import sys @@ -1109,8 +1108,8 @@ class TestTeeStdCapture(TestStdCapture): captureclass = staticmethod(TeeStdCapture) def test_capturing_error_recursive(self): - """ for TeeStdCapture since we passthrough stderr/stdout, cap1 - should get all output, while cap2 should only get "cap2\n" """ + r"""For TeeStdCapture since we passthrough stderr/stdout, cap1 + should get all output, while cap2 should only get "cap2\n".""" with self.getcapture() as cap1: print("cap1") diff --git a/testing/test_collection.py b/testing/test_collection.py index f5e8abfd727..9f22f3ee038 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -725,10 +725,8 @@ def testmethod_two(self, arg0): print(s) def test_class_and_functions_discovery_using_glob(self, testdir): - """ - tests that python_classes and python_functions config options work - as prefixes and glob-like patterns (issue #600). - """ + """Test that Python_classes and Python_functions config options work + as prefixes and glob-like patterns (#600).""" testdir.makeini( """ [pytest] diff --git a/testing/test_config.py b/testing/test_config.py index 9b1c11d5edc..26d2a3ef09b 100644 --- a/testing/test_config.py +++ b/testing/test_config.py @@ -47,7 +47,7 @@ def test_getcfg_and_config(self, testdir, tmpdir, section, filename): assert config.inicfg["name"] == "value" def test_getcfg_empty_path(self): - """correctly handle zero length arguments (a la pytest '')""" + """Correctly handle zero length arguments (a la pytest '').""" locate_config([""]) def test_setupcfg_uses_toolpytest_with_pytest(self, testdir): @@ -1006,8 +1006,8 @@ def pytest_cmdline_preparse(args): def test_invalid_options_show_extra_information(testdir): - """display extra information when pytest exits due to unrecognized - options in the command-line""" + """Display extra information when pytest exits due to unrecognized + options in the command-line.""" testdir.makeini( """ [pytest] @@ -1441,7 +1441,7 @@ def test_addopts_from_env_not_concatenated(self, monkeypatch, _config_for_test): ) def test_addopts_from_ini_not_concatenated(self, testdir): - """addopts from ini should not take values from normal args (#4265).""" + """`addopts` from ini should not take values from normal args (#4265).""" testdir.makeini( """ [pytest] @@ -1777,10 +1777,8 @@ def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives def test_conftest_import_error_repr(tmpdir): - """ - ConftestImportFailure should use a short error message and readable path to the failed - conftest.py file - """ + """`ConftestImportFailure` should use a short error message and readable + path to the failed conftest.py file.""" path = tmpdir.join("foo/conftest.py") with pytest.raises( ConftestImportFailure, diff --git a/testing/test_conftest.py b/testing/test_conftest.py index dbafe7dd34b..d1a69f4babc 100644 --- a/testing/test_conftest.py +++ b/testing/test_conftest.py @@ -196,9 +196,7 @@ def pytest_addoption(parser): def test_conftest_symlink(testdir): - """ - conftest.py discovery follows normal path resolution and does not resolve symlinks. - """ + """`conftest.py` discovery follows normal path resolution and does not resolve symlinks.""" # Structure: # /real # /real/conftest.py diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 965dba6c179..0b32ad32203 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -115,8 +115,7 @@ def test_new_pattern(self, testdir): reprec.assertoutcome(failed=1) def test_multiple_patterns(self, testdir): - """Test support for multiple --doctest-glob arguments (#1255). - """ + """Test support for multiple --doctest-glob arguments (#1255).""" testdir.maketxtfile( xdoc=""" >>> 1 @@ -149,8 +148,7 @@ def test_multiple_patterns(self, testdir): [("foo", "ascii"), ("öäü", "latin1"), ("öäü", "utf-8")], ) def test_encoding(self, testdir, test_string, encoding): - """Test support for doctest_encoding ini option. - """ + """Test support for doctest_encoding ini option.""" testdir.makeini( """ [pytest] @@ -667,8 +665,7 @@ def test_non_ignored_whitespace_glob(self, testdir): reprec.assertoutcome(failed=1, passed=0) def test_contains_unicode(self, testdir): - """Fix internal error with docstrings containing non-ascii characters. - """ + """Fix internal error with docstrings containing non-ascii characters.""" testdir.makepyfile( '''\ def foo(): @@ -701,9 +698,7 @@ def add_one(x): reprec.assertoutcome(skipped=1, failed=1, passed=0) def test_junit_report_for_doctest(self, testdir): - """ - #713: Fix --junit-xml option when used with --doctest-modules. - """ + """#713: Fix --junit-xml option when used with --doctest-modules.""" p = testdir.makepyfile( """ def foo(): @@ -775,9 +770,7 @@ def test_print_unicode_value(self, testdir): result.stdout.fnmatch_lines(["* 1 passed *"]) def test_reportinfo(self, testdir): - """ - Test case to make sure that DoctestItem.reportinfo() returns lineno. - """ + """Make sure that DoctestItem.reportinfo() returns lineno.""" p = testdir.makepyfile( test_reportinfo=""" def foo(x): @@ -1167,8 +1160,7 @@ class TestDoctestAutoUseFixtures: SCOPES = ["module", "session", "class", "function"] def test_doctest_module_session_fixture(self, testdir): - """Test that session fixtures are initialized for doctest modules (#768) - """ + """Test that session fixtures are initialized for doctest modules (#768).""" # session fixture which changes some global data, which will # be accessed by doctests in a module testdir.makeconftest( diff --git a/testing/test_faulthandler.py b/testing/test_faulthandler.py index 46adccd2159..87a195bf807 100644 --- a/testing/test_faulthandler.py +++ b/testing/test_faulthandler.py @@ -19,8 +19,7 @@ def test_crash(): def test_crash_near_exit(testdir): """Test that fault handler displays crashes that happen even after - pytest is exiting (for example, when the interpreter is shutting down). - """ + pytest is exiting (for example, when the interpreter is shutting down).""" testdir.makepyfile( """ import faulthandler @@ -35,8 +34,7 @@ def test_ok(): def test_disabled(testdir): - """Test option to disable fault handler in the command line. - """ + """Test option to disable fault handler in the command line.""" testdir.makepyfile( """ import faulthandler @@ -60,6 +58,7 @@ def test_disabled(): ) def test_timeout(testdir, enabled: bool) -> None: """Test option to dump tracebacks after a certain timeout. + If faulthandler is disabled, no traceback will be dumped. """ testdir.makepyfile( @@ -90,9 +89,8 @@ def test_timeout(): @pytest.mark.parametrize("hook_name", ["pytest_enter_pdb", "pytest_exception_interact"]) def test_cancel_timeout_on_hook(monkeypatch, hook_name): """Make sure that we are cancelling any scheduled traceback dumping due - to timeout before entering pdb (pytest-dev/pytest-faulthandler#12) or any other interactive - exception (pytest-dev/pytest-faulthandler#14). - """ + to timeout before entering pdb (pytest-dev/pytest-faulthandler#12) or any + other interactive exception (pytest-dev/pytest-faulthandler#14).""" import faulthandler from _pytest.faulthandler import FaultHandlerHooks @@ -111,7 +109,7 @@ def test_cancel_timeout_on_hook(monkeypatch, hook_name): @pytest.mark.parametrize("faulthandler_timeout", [0, 2]) def test_already_initialized(faulthandler_timeout, testdir): - """Test for faulthandler being initialized earlier than pytest (#6575)""" + """Test for faulthandler being initialized earlier than pytest (#6575).""" testdir.makepyfile( """ def test(): diff --git a/testing/test_helpconfig.py b/testing/test_helpconfig.py index a33273a2c1d..6116242ec0d 100644 --- a/testing/test_helpconfig.py +++ b/testing/test_helpconfig.py @@ -39,8 +39,7 @@ def test_help(testdir): def test_none_help_param_raises_exception(testdir): - """Tests a None help param raises a TypeError. - """ + """Test that a None help param raises a TypeError.""" testdir.makeconftest( """ def pytest_addoption(parser): @@ -54,8 +53,7 @@ def pytest_addoption(parser): def test_empty_help_param(testdir): - """Tests an empty help param is displayed correctly. - """ + """Test that an empty help param is displayed correctly.""" testdir.makeconftest( """ def pytest_addoption(parser): diff --git a/testing/test_junitxml.py b/testing/test_junitxml.py index 5487940fbcd..3cc93a39805 100644 --- a/testing/test_junitxml.py +++ b/testing/test_junitxml.py @@ -22,7 +22,7 @@ @pytest.fixture(scope="session") def schema(): - """Returns a xmlschema.XMLSchema object for the junit-10.xsd file""" + """Return an xmlschema.XMLSchema object for the junit-10.xsd file.""" fn = Path(__file__).parent / "example_scripts/junit-10.xsd" with fn.open() as f: return xmlschema.XMLSchema(f) @@ -30,9 +30,8 @@ def schema(): @pytest.fixture def run_and_parse(testdir, schema): - """ - Fixture that returns a function that can be used to execute pytest and return - the parsed ``DomNode`` of the root xml node. + """Fixture that returns a function that can be used to execute pytest and + return the parsed ``DomNode`` of the root xml node. The ``family`` parameter is used to configure the ``junit_family`` of the written report. "xunit2" is also automatically validated against the schema. @@ -720,7 +719,7 @@ def test_hello(): assert "hx" in fnode.toxml() def test_assertion_binchars(self, testdir, run_and_parse): - """this test did fail when the escaping wasnt strict""" + """This test did fail when the escaping wasn't strict.""" testdir.makepyfile( """ @@ -1212,8 +1211,7 @@ def test_record(record_xml_attribute, other): @pytest.mark.filterwarnings("default") @pytest.mark.parametrize("fixture_name", ["record_xml_attribute", "record_property"]) def test_record_fixtures_xunit2(testdir, fixture_name, run_and_parse): - """Ensure record_xml_attribute and record_property drop values when outside of legacy family - """ + """Ensure record_xml_attribute and record_property drop values when outside of legacy family.""" testdir.makeini( """ [pytest] @@ -1250,10 +1248,9 @@ def test_record({fixture_name}, other): def test_random_report_log_xdist(testdir, monkeypatch, run_and_parse): - """xdist calls pytest_runtest_logreport as they are executed by the workers, + """`xdist` calls pytest_runtest_logreport as they are executed by the workers, with nodes from several nodes overlapping, so junitxml must cope with that - to produce correct reports. #1064 - """ + to produce correct reports (#1064).""" pytest.importorskip("xdist") monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) testdir.makepyfile( diff --git a/testing/test_link_resolve.py b/testing/test_link_resolve.py index 3e9199dff56..f43f7ded567 100644 --- a/testing/test_link_resolve.py +++ b/testing/test_link_resolve.py @@ -50,9 +50,7 @@ def subst_path_linux(filename): def test_link_resolve(testdir: pytester.Testdir) -> None: - """ - See: https://github.com/pytest-dev/pytest/issues/5965 - """ + """See: https://github.com/pytest-dev/pytest/issues/5965.""" sub1 = testdir.mkpydir("sub1") p = sub1.join("test_foo.py") p.write( diff --git a/testing/test_mark.py b/testing/test_mark.py index f00c1330e65..5d5e0cf42f7 100644 --- a/testing/test_mark.py +++ b/testing/test_mark.py @@ -370,9 +370,8 @@ def test_func(arg): def test_parametrized_collected_from_command_line(testdir): - """Parametrized test not collected if test named specified - in command line issue#649. - """ + """Parametrized test not collected if test named specified in command + line issue#649.""" py_file = testdir.makepyfile( """ import pytest @@ -430,7 +429,7 @@ def test_func(a, b): def test_parametrize_iterator(testdir): - """parametrize should work with generators (#5354).""" + """`parametrize` should work with generators (#5354).""" py_file = testdir.makepyfile( """\ import pytest @@ -669,13 +668,12 @@ def test_some(request): reprec.assertoutcome(passed=1) def assert_markers(self, items, **expected): - """assert that given items have expected marker names applied to them. - expected should be a dict of (item name -> seq of expected marker names) + """Assert that given items have expected marker names applied to them. + expected should be a dict of (item name -> seq of expected marker names). - .. note:: this could be moved to ``testdir`` if proven to be useful + Note: this could be moved to ``testdir`` if proven to be useful to other modules. """ - items = {x.name: x for x in items} for name, expected_markers in expected.items(): markers = {m.name for m in items[name].iter_markers()} @@ -866,9 +864,7 @@ def test_one(): assert 1 assert len(deselected_tests) == 1 def test_no_match_directories_outside_the_suite(self, testdir): - """ - -k should not match against directories containing the test suite (#7040). - """ + """`-k` should not match against directories containing the test suite (#7040).""" test_contents = """ def test_aaa(): pass def test_ddd(): pass diff --git a/testing/test_meta.py b/testing/test_meta.py index 7ab8951a015..1acf6d09f59 100644 --- a/testing/test_meta.py +++ b/testing/test_meta.py @@ -1,5 +1,4 @@ -""" -Test importing of all internal packages and modules. +"""Test importing of all internal packages and modules. This ensures all internal packages can be imported without needing the pytest namespace being set, which is critical for the initialization of xdist. diff --git a/testing/test_pastebin.py b/testing/test_pastebin.py index 0701641f805..7f88a13eb43 100644 --- a/testing/test_pastebin.py +++ b/testing/test_pastebin.py @@ -87,9 +87,7 @@ def pastebin(self, request): @pytest.fixture def mocked_urlopen_fail(self, monkeypatch): - """ - monkeypatch the actual urlopen call to emulate a HTTP Error 400 - """ + """Monkeypatch the actual urlopen call to emulate a HTTP Error 400.""" calls = [] import urllib.error @@ -104,11 +102,9 @@ def mocked(url, data): @pytest.fixture def mocked_urlopen_invalid(self, monkeypatch): - """ - monkeypatch the actual urlopen calls done by the internal plugin + """Monkeypatch the actual urlopen calls done by the internal plugin function that connects to bpaste service, but return a url in an - unexpected format - """ + unexpected format.""" calls = [] def mocked(url, data): @@ -128,10 +124,8 @@ def read(self): @pytest.fixture def mocked_urlopen(self, monkeypatch): - """ - monkeypatch the actual urlopen calls done by the internal plugin - function that connects to bpaste service. - """ + """Monkeypatch the actual urlopen calls done by the internal plugin + function that connects to bpaste service.""" calls = [] def mocked(url, data): diff --git a/testing/test_pathlib.py b/testing/test_pathlib.py index 2c1a1c021f8..74dac21d996 100644 --- a/testing/test_pathlib.py +++ b/testing/test_pathlib.py @@ -18,9 +18,8 @@ class TestFNMatcherPort: - """Test that our port of py.common.FNMatcher (fnmatch_ex) produces the same results as the - original py.path.local.fnmatch method. - """ + """Test that our port of py.common.FNMatcher (fnmatch_ex) produces the + same results as the original py.path.local.fnmatch method.""" @pytest.fixture(params=["pathlib", "py.path"]) def match(self, request): @@ -268,19 +267,19 @@ def foo(x): return 40 + x return fn def test_importmode_importlib(self, simple_module): - """importlib mode does not change sys.path""" + """`importlib` mode does not change sys.path.""" module = import_path(simple_module, mode="importlib") assert module.foo(2) == 42 # type: ignore[attr-defined] assert simple_module.dirname not in sys.path def test_importmode_twice_is_different_module(self, simple_module): - """importlib mode always returns a new module""" + """`importlib` mode always returns a new module.""" module1 = import_path(simple_module, mode="importlib") module2 = import_path(simple_module, mode="importlib") assert module1 is not module2 def test_no_meta_path_found(self, simple_module, monkeypatch): - """Even without any meta_path should still import module""" + """Even without any meta_path should still import module.""" monkeypatch.setattr(sys, "meta_path", []) module = import_path(simple_module, mode="importlib") assert module.foo(2) == 42 # type: ignore[attr-defined] diff --git a/testing/test_pluginmanager.py b/testing/test_pluginmanager.py index 448900501b1..a083f4b4f37 100644 --- a/testing/test_pluginmanager.py +++ b/testing/test_pluginmanager.py @@ -362,10 +362,10 @@ def test_plugin_prevent_register_unregistered_alredy_registered(self, pytestpm): def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister( self, pytestpm ): - """ From PR #4304 : The only way to unregister a module is documented at + """From PR #4304: The only way to unregister a module is documented at the end of https://docs.pytest.org/en/stable/plugins.html. - When unregister cacheprovider, then unregister stepwise too + When unregister cacheprovider, then unregister stepwise too. """ pytestpm.register(42, name="cacheprovider") pytestpm.register(43, name="stepwise") diff --git a/testing/test_pytester.py b/testing/test_pytester.py index 46f3e1cabfa..5259b448418 100644 --- a/testing/test_pytester.py +++ b/testing/test_pytester.py @@ -166,18 +166,18 @@ def test_potato(): def make_holder(): class apiclass: def pytest_xyz(self, arg): - "x" + """X""" def pytest_xyz_noarg(self): - "x" + """X""" apimod = type(os)("api") def pytest_xyz(arg): - "x" + """X""" def pytest_xyz_noarg(): - "x" + """X""" apimod.pytest_xyz = pytest_xyz # type: ignore apimod.pytest_xyz_noarg = pytest_xyz_noarg # type: ignore diff --git a/testing/test_reports.py b/testing/test_reports.py index 08ac014a40b..a47d5378705 100644 --- a/testing/test_reports.py +++ b/testing/test_reports.py @@ -9,8 +9,7 @@ class TestReportSerialization: def test_xdist_longrepr_to_str_issue_241(self, testdir): - """ - Regarding issue pytest-xdist#241 + """Regarding issue pytest-xdist#241. This test came originally from test_remote.py in xdist (ca03269). """ @@ -133,9 +132,7 @@ def test_repr_entry_native(): assert rep_entries[i].lines == a_entries[i].lines def test_itemreport_outcomes(self, testdir): - """ - This test came originally from test_remote.py in xdist (ca03269). - """ + # This test came originally from test_remote.py in xdist (ca03269). reprec = testdir.inline_runsource( """ import pytest diff --git a/testing/test_runner.py b/testing/test_runner.py index b207ccc927f..b9d22370a7b 100644 --- a/testing/test_runner.py +++ b/testing/test_runner.py @@ -310,7 +310,7 @@ def teardown_function(func): assert reps[5].failed def test_exact_teardown_issue1206(self, testdir) -> None: - """issue shadowing error with wrong number of arguments on teardown_method.""" + """Issue shadowing error with wrong number of arguments on teardown_method.""" rec = testdir.inline_runsource( """ import pytest @@ -742,7 +742,7 @@ def test_importorskip_dev_module(monkeypatch) -> None: def test_importorskip_module_level(testdir) -> None: - """importorskip must be able to skip entire modules when used at module level""" + """`importorskip` must be able to skip entire modules when used at module level.""" testdir.makepyfile( """ import pytest @@ -757,7 +757,7 @@ def test_foo(): def test_importorskip_custom_reason(testdir) -> None: - """make sure custom reasons are used""" + """Make sure custom reasons are used.""" testdir.makepyfile( """ import pytest @@ -871,9 +871,8 @@ def test_fix(foo): def test_store_except_info_on_error() -> None: - """ Test that upon test failure, the exception info is stored on - sys.last_traceback and friends. - """ + """Test that upon test failure, the exception info is stored on + sys.last_traceback and friends.""" # Simulate item that might raise a specific exception, depending on `raise_error` class var class ItemMightRaise: nodeid = "item_that_raises" @@ -934,9 +933,7 @@ def test(fix): class TestReportContents: - """ - Test user-level API of ``TestReport`` objects. - """ + """Test user-level API of ``TestReport`` objects.""" def getrunner(self): return lambda item: runner.runtestprotocol(item, log=False) diff --git a/testing/test_runner_xunit.py b/testing/test_runner_xunit.py index 1b5d9737177..1abb35043b7 100644 --- a/testing/test_runner_xunit.py +++ b/testing/test_runner_xunit.py @@ -1,7 +1,4 @@ -""" - test correct setup/teardowns at - module, class, and instance level -""" +"""Test correct setup/teardowns at module, class, and instance level.""" from typing import List import pytest @@ -246,7 +243,7 @@ def test_function2(hello): def test_setup_teardown_function_level_with_optional_argument( testdir, monkeypatch, arg: str, ) -> None: - """parameter to setup/teardown xunit-style functions parameter is now optional (#1728).""" + """Parameter to setup/teardown xunit-style functions parameter is now optional (#1728).""" import sys trace_setups_teardowns = [] # type: List[str] diff --git a/testing/test_setuponly.py b/testing/test_setuponly.py index 221c32a310b..a43c850696e 100644 --- a/testing/test_setuponly.py +++ b/testing/test_setuponly.py @@ -254,7 +254,7 @@ def test_capturing(two): def test_show_fixtures_and_execute_test(testdir): - """ Verifies that setups are shown and tests are executed. """ + """Verify that setups are shown and tests are executed.""" p = testdir.makepyfile( """ import pytest diff --git a/testing/test_setupplan.py b/testing/test_setupplan.py index 64b464b32dd..929e883cce2 100644 --- a/testing/test_setupplan.py +++ b/testing/test_setupplan.py @@ -1,5 +1,5 @@ def test_show_fixtures_and_test(testdir, dummy_yaml_custom_test): - """ Verifies that fixtures are not executed. """ + """Verify that fixtures are not executed.""" testdir.makepyfile( """ import pytest @@ -20,8 +20,7 @@ def test_arg(arg): def test_show_multi_test_fixture_setup_and_teardown_correctly_simple(testdir): - """ - Verify that when a fixture lives for longer than a single test, --setup-plan + """Verify that when a fixture lives for longer than a single test, --setup-plan correctly displays the SETUP/TEARDOWN indicators the right number of times. As reported in https://github.com/pytest-dev/pytest/issues/2049 @@ -68,9 +67,7 @@ def test_two(self, fix): def test_show_multi_test_fixture_setup_and_teardown_same_as_setup_show(testdir): - """ - Verify that SETUP/TEARDOWN messages match what comes out of --setup-show. - """ + """Verify that SETUP/TEARDOWN messages match what comes out of --setup-show.""" testdir.makepyfile( """ import pytest diff --git a/testing/test_skipping.py b/testing/test_skipping.py index 92182ff382f..b32d2267d21 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -188,9 +188,7 @@ def test_func(): assert callreport.wasxfail == "this is an xfail" def test_xfail_using_platform(self, testdir): - """ - Verify that platform can be used with xfail statements. - """ + """Verify that platform can be used with xfail statements.""" item = testdir.getitem( """ import pytest @@ -476,9 +474,8 @@ def test_raises(): result.stdout.fnmatch_lines([matchline]) def test_strict_sanity(self, testdir): - """sanity check for xfail(strict=True): a failing test should behave - exactly like a normal xfail. - """ + """Sanity check for xfail(strict=True): a failing test should behave + exactly like a normal xfail.""" p = testdir.makepyfile( """ import pytest @@ -1137,9 +1134,7 @@ def pytest_collect_file(path, parent): def test_module_level_skip_error(testdir): - """ - Verify that using pytest.skip at module level causes a collection error - """ + """Verify that using pytest.skip at module level causes a collection error.""" testdir.makepyfile( """ import pytest @@ -1156,9 +1151,7 @@ def test_func(): def test_module_level_skip_with_allow_module_level(testdir): - """ - Verify that using pytest.skip(allow_module_level=True) is allowed - """ + """Verify that using pytest.skip(allow_module_level=True) is allowed.""" testdir.makepyfile( """ import pytest @@ -1173,9 +1166,7 @@ def test_func(): def test_invalid_skip_keyword_parameter(testdir): - """ - Verify that using pytest.skip() with unknown parameter raises an error - """ + """Verify that using pytest.skip() with unknown parameter raises an error.""" testdir.makepyfile( """ import pytest diff --git a/testing/test_terminal.py b/testing/test_terminal.py index a524fe0d86f..36604ece78a 100644 --- a/testing/test_terminal.py +++ b/testing/test_terminal.py @@ -1,6 +1,4 @@ -""" -terminal reporting of the full testing process. -""" +"""Terminal reporting of the full testing process.""" import collections import os import sys @@ -440,10 +438,8 @@ def test_collectonly_error(self, testdir): ) def test_collectonly_missing_path(self, testdir): - """this checks issue 115, - failure in parseargs will cause session - not to have the items attribute - """ + """Issue 115: failure in parseargs will cause session not to + have the items attribute.""" result = testdir.runpytest("--collect-only", "uhm_missing_path") assert result.ret == 4 result.stderr.fnmatch_lines(["*ERROR: file not found*"]) @@ -531,7 +527,7 @@ def teardown_function(function): ) def test_setup_teardown_output_and_test_failure(self, testdir): - """ Test for issue #442 """ + """Test for issue #442.""" testdir.makepyfile( """ def setup_function(function): @@ -1076,9 +1072,7 @@ def test_color_no(testdir): @pytest.mark.parametrize("verbose", [True, False]) def test_color_yes_collection_on_non_atty(testdir, verbose): - """skip collect progress report when working on non-terminals. - #1397 - """ + """#1397: Skip collect progress report when working on non-terminals.""" testdir.makepyfile( """ import pytest @@ -1208,9 +1202,8 @@ def test_traceconfig(testdir): class TestGenericReporting: - """ this test class can be subclassed with a different option - provider to run e.g. distributed tests. - """ + """Test class which 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") diff --git a/testing/test_unittest.py b/testing/test_unittest.py index 6ddc6186be4..f9455e63b42 100644 --- a/testing/test_unittest.py +++ b/testing/test_unittest.py @@ -1196,9 +1196,7 @@ def test_2(self): @pytest.mark.parametrize("mark", ["@unittest.skip", "@pytest.mark.skip"]) def test_pdb_teardown_skipped(testdir, monkeypatch, mark: str) -> None: - """ - With --pdb, setUp and tearDown should not be called for skipped tests. - """ + """With --pdb, setUp and tearDown should not be called for skipped tests.""" tracked = [] # type: List[str] monkeypatch.setattr(pytest, "test_pdb_teardown_skipped", tracked, raising=False) diff --git a/testing/test_warnings.py b/testing/test_warnings.py index c3668180216..d26c71ca3b2 100644 --- a/testing/test_warnings.py +++ b/testing/test_warnings.py @@ -13,9 +13,7 @@ @pytest.fixture def pyfile_with_warnings(testdir: Testdir, request: FixtureRequest) -> str: - """ - Create a test file which calls a function in a module which generates warnings. - """ + """Create a test file which calls a function in a module which generates warnings.""" testdir.syspathinsert() test_name = request.function.__name__ module_name = test_name.lstrip("test_") + "_module" @@ -42,9 +40,7 @@ def foo(): @pytest.mark.filterwarnings("default") def test_normal_flow(testdir, pyfile_with_warnings): - """ - Check that the warnings section is displayed. - """ + """Check that the warnings section is displayed.""" result = testdir.runpytest(pyfile_with_warnings) result.stdout.fnmatch_lines( [ @@ -180,9 +176,8 @@ def test_my_warning(self): @pytest.mark.parametrize("default_config", ["ini", "cmdline"]) def test_filterwarnings_mark(testdir, default_config): - """ - Test ``filterwarnings`` mark works and takes precedence over command line and ini options. - """ + """Test ``filterwarnings`` mark works and takes precedence over command + line and ini options.""" if default_config == "ini": testdir.makeini( """ @@ -305,9 +300,7 @@ def pytest_warning_recorded(self, warning_message, when, nodeid, location): @pytest.mark.filterwarnings("always") def test_collection_warnings(testdir): - """ - Check that we also capture warnings issued during test collection (#3251). - """ + """Check that we also capture warnings issued during test collection (#3251).""" testdir.makepyfile( """ import warnings @@ -387,7 +380,7 @@ def test_bar(): @pytest.mark.parametrize("ignore_on_cmdline", [True, False]) def test_option_precedence_cmdline_over_ini(testdir, ignore_on_cmdline): - """filters defined in the command-line should take precedence over filters in ini files (#3946).""" + """Filters defined in the command-line should take precedence over filters in ini files (#3946).""" testdir.makeini( """ [pytest] From 9a18b57c7cca54352dac7497a608925691b8d0bd Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Sat, 18 Jul 2020 12:28:44 +0300 Subject: [PATCH 2/2] Enforce some pydocstyle lints with flake8-docstrings There are some ones we *would* like to enforce, like D401 First line should be in imperative mood but have too many false positives, so I left them out. --- .pre-commit-config.yaml | 4 +++- tox.ini | 12 +++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 817cee60406..6068a2d324d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -25,7 +25,9 @@ repos: hooks: - id: flake8 language_version: python3 - additional_dependencies: [flake8-typing-imports==1.9.0] + additional_dependencies: + - flake8-typing-imports==1.9.0 + - flake8-docstrings==1.5.0 - repo: https://github.com/asottile/reorder_python_imports rev: v2.3.0 hooks: diff --git a/tox.ini b/tox.ini index c8165a3c3bb..30aeb27be33 100644 --- a/tox.ini +++ b/tox.ini @@ -154,7 +154,17 @@ commands = python scripts/publish-gh-release-notes.py {posargs} [flake8] max-line-length = 120 -extend-ignore = E203 +extend-ignore = + ; whitespace before ':' + E203 + ; Missing Docstrings + D100,D101,D102,D103,D104,D105,D106,D107 + ; Whitespace Issues + D202,D203,D204,D205,D209,D213 + ; Quotes Issues + D302 + ; Docstring Content Issues + D400,D401,D401,D402,D405,D406,D407,D408,D409,D410,D411,D412,D413,D414,D415,D416,D417 [isort] ; This config mimics what reorder-python-imports does.