Skip to content

Commit

Permalink
Merge pull request #7603 from bluetech/flake8-docstrings
Browse files Browse the repository at this point in the history
Enforce some pydocstyle lints with flake8-docstrings & docstring fixes in testing/
  • Loading branch information
bluetech committed Aug 4, 2020
2 parents 701998b + 9a18b57 commit 0dd5e16
Show file tree
Hide file tree
Showing 42 changed files with 189 additions and 297 deletions.
4 changes: 3 additions & 1 deletion .pre-commit-config.yaml
Expand Up @@ -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:
Expand Down
9 changes: 5 additions & 4 deletions doc/en/example/nonpython/conftest.py
Expand Up @@ -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()):
Expand All @@ -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(
[
Expand All @@ -43,4 +44,4 @@ def reportinfo(self):


class YamlException(Exception):
""" custom exception for error reporting. """
"""Custom exception for error reporting."""
4 changes: 1 addition & 3 deletions scripts/release.py
@@ -1,6 +1,4 @@
"""
Invoke development tasks.
"""
"""Invoke development tasks."""
import argparse
import os
from pathlib import Path
Expand Down
28 changes: 10 additions & 18 deletions testing/acceptance_test.py
Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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/
"""
Expand Down Expand Up @@ -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(
**{
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion testing/code/test_excinfo.py
Expand Up @@ -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():
Expand Down
4 changes: 1 addition & 3 deletions 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
Expand Down
8 changes: 4 additions & 4 deletions testing/logging/test_fixture.py
Expand Up @@ -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(
"""
Expand Down
19 changes: 6 additions & 13 deletions testing/logging/test_reporting.py
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand Down
4 changes: 1 addition & 3 deletions testing/python/approx.py
Expand Up @@ -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))

Expand Down
12 changes: 6 additions & 6 deletions testing/python/collect.py
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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.
"""
Expand Down Expand Up @@ -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*"])
Expand Down
10 changes: 3 additions & 7 deletions testing/python/fixtures.py
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 0dd5e16

Please sign in to comment.