diff --git a/docs/Coding-Conventions.md b/docs/Coding-Conventions.md index eccbab26..fdcccc8d 100644 --- a/docs/Coding-Conventions.md +++ b/docs/Coding-Conventions.md @@ -982,6 +982,12 @@ def go_shopping(): â„šī¸ You can document a package by documenting the module docstring of the package directory's `__init__.py` +### Which docstring format should I follow? + +We recommend (and internally use) the [Google docstring format](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods) but you can choose any format so long as you are consistent. + +**Note**: Through the use of the [Sphinx napoleon](https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html#getting-started) extension, Sphinx docs generation can interpret [Google style docstrings](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods). + ### [D.1.2] âœ”ī¸ **DO** List exported modules and subpackages in a package's docstring > 🐍 This rule stems from [PEP 257](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings) @@ -1070,7 +1076,7 @@ The summary line should be on the same line as the opening quotes. ```python # Bad - will produce D205 def sell(type_): - """Sell the specified type of cheese. + """Sells the specified type of cheese. Will throw an OutOfStockException if the specified type of cheese is out of stock. """ ``` @@ -1079,7 +1085,7 @@ def sell(type_): # Bad - will produce D212 def sell(type_): """ - Sell the specified type of cheese. + Sells the specified type of cheese. Will throw an OutOfStockException if the specified type of cheese is out of stock. """ @@ -1088,7 +1094,7 @@ def sell(type_): ```python # Good def sell(type_): - """Sell the specified type of cheese. + """Sells the specified type of cheese. Will throw an OutOfStockException if the specified type of cheese is out of stock. """ @@ -1100,7 +1106,7 @@ class CheeseShop(object): """Finest cheese shop in the district, offering a wide variety of cheeses.""" def sell(self, type_): - """Sell the specified type of cheese.""" + """Sells the specified type of cheese.""" ``` ### [D.1.11] âœ”ī¸ **DO** Put closing `"""` on its own line for multiline docstrings đŸ’ģ @@ -1117,7 +1123,7 @@ class CheeseShop(object): Cheeses are sold first-come-first-served, and can run out of stock rather quickly.""" def sell(self, type_): - """Sell the specified type of cheese. + """Sells the specified type of cheese. Will throw an OutOfStockException if the specified type of cheese is out of stock.""" ``` @@ -1131,7 +1137,7 @@ class CheeseShop(object): """ def sell(self, type_): - """Sell the specified type of cheese. + """Sells the specified type of cheese. Will throw an OutOfStockException if the specified type of cheese is out of stock. """ @@ -1157,7 +1163,7 @@ class CheeseShop(object): class CheeseShop(object): def sell(self, type_): - """Sell the specified type of cheese.""" + """Sells the specified type of cheese.""" ``` ```python @@ -1166,7 +1172,7 @@ class CheeseShop(object): """Finest cheese shop in the district, offering a wide variety of cheeses.""" def sell(self, type_): - """Sell the specified type of cheese.""" + """Sells the specified type of cheese.""" ``` ### [D.1.13] ❌ **DO NOT** Put a blank line after a one line function docstring đŸ’ģ @@ -1178,7 +1184,7 @@ class CheeseShop(object): ```python # Bad def sell(self, type_): - """Sell the specified type of cheese.""" + """Sells the specified type of cheese.""" self._do_transaction(type_) ``` @@ -1186,10 +1192,47 @@ def sell(self, type_): ```python # Good def sell(self, type_): - """Sell the specified type of cheese.""" + """Sells the specified type of cheese.""" self._do_transaction(type_) ``` + +### [D.1.14] ❌ **DO NOT** Put a blank line after section headers đŸ’ģ + +> đŸ’ģ This rule is enforced by error code D412 + +```python +# Bad - will produce D412 +class CheeseShop(object): + def sell(self, type_): + """Sells the specified type of cheese. + + Args: + + type_: the desired type + """ + self._do_transaction(type_) +``` + +```python +# Good +class CheeseShop(object): + def sell(self, type_: str): + """Sells the specified type of cheese. + + Args: + type_: the desired cheese type + """ + self._do_transaction(type_) +``` + +```python +# Best +class CheeseShop(object): + def sell(self, type_: str): + """Sells the specified type of cheese.""" + self._do_transaction(type_) +``` --- # [C] Comments diff --git a/ni_python_styleguide/_acknowledge_existing_errors/__init__.py b/ni_python_styleguide/_acknowledge_existing_errors/__init__.py index 354a6fc8..fee6e7ce 100644 --- a/ni_python_styleguide/_acknowledge_existing_errors/__init__.py +++ b/ni_python_styleguide/_acknowledge_existing_errors/__init__.py @@ -35,7 +35,7 @@ def _filter_suppresion_from_line(line: str): def acknowledge_lint_errors( exclude, app_import_names, extend_ignore, file_or_dir, *_, aggressive=False ): - """Add a "noqa" comment for each of existing errors (unless excluded). + """Adds a "noqa" comment for each of existing errors (unless excluded). Excluded error (reason): BLK100 - run black @@ -94,7 +94,7 @@ def acknowledge_lint_errors( def remove_auto_suppressions_from_file(file: pathlib.Path): - """Remove auto-suppressions from file.""" + """Removes auto-suppressions from file.""" lines = file.read_text(encoding=_utils.DEFAULT_ENCODING).splitlines() stripped_lines = [_filter_suppresion_from_line(line) for line in lines] file.write_text("\n".join(stripped_lines) + "\n", encoding=_utils.DEFAULT_ENCODING) diff --git a/ni_python_styleguide/_cli.py b/ni_python_styleguide/_cli.py index d2202933..b82357d4 100644 --- a/ni_python_styleguide/_cli.py +++ b/ni_python_styleguide/_cli.py @@ -40,7 +40,7 @@ def _read_pyproject_toml(ctx, param, value): def _get_application_import_names(pyproject): - """Return the application package name the config.""" + """Returns the application package name the config.""" # Otherwise override with what was specified app_name = ( pyproject.get("tool", {}) @@ -59,7 +59,7 @@ class ConfigGroup(click.Group): """click.Group subclass which allows for a config option to load options from.""" def __init__(self, *args, **kwargs): - """Construct the click.Group with the config option.""" + """Constructs the click.Group with the config option.""" kwargs["params"].append( click.Option( ["--config"], diff --git a/ni_python_styleguide/_fix.py b/ni_python_styleguide/_fix.py index 07957f85..178c5195 100644 --- a/ni_python_styleguide/_fix.py +++ b/ni_python_styleguide/_fix.py @@ -15,7 +15,7 @@ def _split_imports_line(lines: str, *_, **__): - r"""Split multi-import lines to multiple lines. + r"""Splits multi-import lines to multiple lines. >>> _split_imports_line("import os, collections\n") 'import os\nimport collections\n' diff --git a/ni_python_styleguide/_format.py b/ni_python_styleguide/_format.py index ba0e50b2..ea794a61 100644 --- a/ni_python_styleguide/_format.py +++ b/ni_python_styleguide/_format.py @@ -8,7 +8,7 @@ def format(file_or_dir, *additional_formatter_args): - """Format the specified file or directory using the builtin config.""" + """Formats the specified file or directory using the builtin config.""" try: black.main( [ @@ -25,7 +25,7 @@ def format(file_or_dir, *additional_formatter_args): def format_check(file_or_dir): - """Perform format and return True if changes were made (False otherwise).""" + """Formats and returns True if changes were made (False otherwise).""" capture = StringIO() with contextlib.redirect_stderr(capture): format(file_or_dir) diff --git a/ni_python_styleguide/_utils/code_analysis.py b/ni_python_styleguide/_utils/code_analysis.py index eec22f73..7c9faabe 100644 --- a/ni_python_styleguide/_utils/code_analysis.py +++ b/ni_python_styleguide/_utils/code_analysis.py @@ -4,7 +4,7 @@ def find_import_region(file: pathlib.Path) -> Tuple[int, int]: - """Return the index of the first last import line that precedes any other code. + """Returns the index of the first last import line that precedes any other code. Note: will not handle try/except imports diff --git a/ni_python_styleguide/_utils/lint.py b/ni_python_styleguide/_utils/lint.py index f53f47ac..c78472db 100644 --- a/ni_python_styleguide/_utils/lint.py +++ b/ni_python_styleguide/_utils/lint.py @@ -28,7 +28,7 @@ def get_errors_to_process(exclude, app_import_names, extend_ignore, file_or_dir, def parse(line): r""" - Parse line into :class:`LintError`. + Parses line into :class:`LintError`. >>> parse(r'source\arfile.py:55:16: BLK100 Black would make changes.') LintError(file='source\\arfile.py', line=55, column=16, code='BLK100', explanation='Black would make changes.') @@ -65,7 +65,7 @@ def _to_lint_error(file: str, line: str, column: str, code: str, explanation: st ) def parse(self, line): - """Parse `line` and return a :class:`LintError`. + """Parses `line` and return a :class:`LintError`. :param line: the line to parse :return: lint error as metada object diff --git a/ni_python_styleguide/_utils/string_helpers.py b/ni_python_styleguide/_utils/string_helpers.py index 339fba9f..9fdc796f 100644 --- a/ni_python_styleguide/_utils/string_helpers.py +++ b/ni_python_styleguide/_utils/string_helpers.py @@ -23,11 +23,11 @@ def __init__(self, error_file: Optional[str] = None, *_, lines: Optional[List[st @property def values(self): - """Return the values for the file.""" + """The values for the file.""" return self._values def in_multiline_string(self, lineno): - """Check if lineno is in a multiline string.""" + """Checks if lineno is in a multiline string.""" return self._values[lineno - 1] # 0 indexed, but we number files 1 indexed @staticmethod diff --git a/ni_python_styleguide/config.ini b/ni_python_styleguide/config.ini index 5666dabf..18f0a9c4 100644 --- a/ni_python_styleguide/config.ini +++ b/ni_python_styleguide/config.ini @@ -65,6 +65,15 @@ ignore = F812 # flake8-docstrings + # Ignoring the requirement on imperative mood, as not all conventions agree on this + # and ultimately is up to the developer. If, in the future, the mood was enforced based on + # convention choice we can consider removing this supression as that would make documentation + # consistent within a standard (but maybe not a codebase) + # Developers are welcome to turn back on this error in their specific projects. + # The same goes for the "descriptive"-mood error, if one was to be added to pydocstyle. + D401 + # Conflicts with recommending Google style DocStrings + D406 # Section name should end with a newline -> forces a newline at end of DocString # Ignoring things enforced by black D200 # One-line docstring should fit on one line with quotes D206 # Docstring should be indented with spaces, not tabs @@ -76,7 +85,19 @@ ignore = D203 # 1 blank line required before class docstring D213 # Multi-line docstring summary should start at the second line D400 # First line should end with a period - + # Recommending Google, so these don't apply - http://www.pydocstyle.org/en/stable/error_codes.html#:~:text=The%20google%20convention%20added%20in%20v4.0.0 + D203 + D204 + D213 + D215 + D400 + D401 + D404 + D406 + D407 + D408 + D409 + D413 # flake8-import-order I101 # The names in your from import are in the wrong order. (Enforced by E401) diff --git a/tests/conftest.py b/tests/conftest.py index 05134893..c8fe912f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,14 +9,14 @@ def pytest_collection_modifyitems(items): - """Ignore deprecation warnings in all tests.""" + """Ignores deprecation warnings in all tests.""" for item in items: item.add_marker(pytest.mark.filterwarnings("ignore::DeprecationWarning")) @pytest.fixture def styleguide(monkeypatch, cli_runner): - """Fixture which runs the styleguide when executed. + """Runs the styleguide when executed. Args passed to the function are equivalent to CLI args, and are automatically stringified. @@ -55,7 +55,7 @@ def runner(*, base_args=[], command="", command_args=[]): @pytest.fixture def chdir(): - """Fixture which changes the current working directory when executed.""" + """Changes the current working directory when executed.""" cwd = os.getcwd() yield os.chdir os.chdir(cwd) diff --git a/tests/test_cli/test_acknowledge_existing_errors.py b/tests/test_cli/test_acknowledge_existing_errors.py index ed2a6b0f..9b2401fd 100644 --- a/tests/test_cli/test_acknowledge_existing_errors.py +++ b/tests/test_cli/test_acknowledge_existing_errors.py @@ -14,7 +14,7 @@ def test_given_bad_input_produces_expected_output_simple( test_dir, snapshot, tmp_path, styleguide_command ): - """Test that suppresion yields expected_output file.""" + """Tests that suppresion yields expected_output file.""" in_file = test_dir / "input.py" test_file = tmp_path / "input.py" shutil.copyfile(in_file, test_file) @@ -31,7 +31,7 @@ def test_given_bad_input_produces_expected_output_simple( def test_given_bad_input_produces_expected_output_aggressive( test_dir, snapshot, tmp_path, styleguide_command ): - """Test that suppresion yields expected_output file.""" + """Tests that suppresion yields expected_output file.""" in_file = test_dir / "input.py" test_file = tmp_path / "input.py" shutil.copyfile(in_file, test_file) @@ -60,7 +60,7 @@ def test_given_bad_input_produces_expected_output_aggressive( def test_given_suppressed_file_linter_does_not_error( test_dir, test_file, additional_args, styleguide_command, chdir ): - """Test linter does not error on output from suppresion.""" + """Tests linter does not error on output from suppresion.""" chdir(test_dir) output = styleguide_command(command="lint", command_args=[test_file, *additional_args]) diff --git a/tests/test_cli/test_bare.py b/tests/test_cli/test_bare.py index 23fe9650..91c90598 100644 --- a/tests/test_cli/test_bare.py +++ b/tests/test_cli/test_bare.py @@ -2,7 +2,7 @@ def test_no_args_prints_help(styleguide): - """Test that running the styleguide without any arguments prints the help info.""" + """Tests that running the styleguide without any arguments prints the help info.""" result = styleguide() assert result @@ -10,7 +10,7 @@ def test_no_args_prints_help(styleguide): def test_help_prints_help(styleguide): - """Test that running the styleguide with "--help" prints the help info.""" + """Tests that running the styleguide with "--help" prints the help info.""" result = styleguide("--help") assert result diff --git a/tests/test_cli/test_fix.py b/tests/test_cli/test_fix.py index e15a995e..d609c2a0 100644 --- a/tests/test_cli/test_fix.py +++ b/tests/test_cli/test_fix.py @@ -12,7 +12,7 @@ @pytest.fixture() def example_pyproject_file(tmp_path): - """Provide the current projects pyproject.toml file to tests as an example.""" + """Provides the current project's pyproject.toml file to tests as an example.""" in_file = next( ( parent / "pyproject.toml" @@ -30,7 +30,7 @@ def example_pyproject_file(tmp_path): def test_given_bad_input__fix__produces_expected_output_simple( test_dir, snapshot, tmp_path, styleguide_command, example_pyproject_file ): - """Test that suppresion yields expected_output file.""" + """Tests that suppresion yields expected_output file.""" in_file = test_dir / "input.py" test_file = tmp_path / "input.py" shutil.copyfile(in_file, test_file) @@ -47,7 +47,7 @@ def test_given_bad_input__fix__produces_expected_output_simple( def test_given_bad_input__fix__produces_expected_output_aggressive( test_dir, snapshot, tmp_path, styleguide_command, example_pyproject_file ): - """Test that suppresion yields expected_output file.""" + """Tests that suppresion yields expected_output file.""" in_file = test_dir / "input.py" test_file = tmp_path / "input.py" shutil.copyfile(in_file, test_file) diff --git a/tests/test_cli/test_lint.py b/tests/test_cli/test_lint.py index c27801dc..df476d0a 100644 --- a/tests/test_cli/test_lint.py +++ b/tests/test_cli/test_lint.py @@ -27,7 +27,7 @@ def runner(base_args=[], lint_args=[]): @pytest.fixture def config_write(tmp_path): - """Fixture which will write the specified data to a config file for the tool.""" + """Writes the specified data to a config file for the tool.""" def writer(**config_data): (tmp_path / "pyproject.toml").write_text( @@ -46,7 +46,7 @@ def writer(**config_data): ] ) def styleguide_lint_with_options(request, styleguide_lint, config_write, tmp_path): - """Fixture which will run the styleguide with the "lint" subcommand, given the provided options. + """Runs the styleguide with the "lint" subcommand, given the provided options. The options will be tested on the command line as well as in the config. `base_args` and `lint_args` are similar to the `styleguide_lint` fixture, with the exception of @@ -72,7 +72,7 @@ def runner(base_args={}, lint_args={}): def test_lint__help_arg_prints_help(styleguide): - """Test running the "lint" subcommand with "--help" prints help info.""" + """Tests running the "lint" subcommand with "--help" prints help info.""" result = styleguide("lint", "--help") assert result, result.output @@ -80,7 +80,7 @@ def test_lint__help_arg_prints_help(styleguide): def test_lint__ignores_local_flake8_config(styleguide_lint, tmp_path): - """Test that running lint ignores local flake8 config. + """Tests that running lint ignores local flake8 config. We test this by creating a local config with a smaller (80) max line length than our styleguide enforces (100) and asserting the command passes with a line of length between 80 and 100. @@ -101,7 +101,7 @@ def test_lint__ignores_local_flake8_config(styleguide_lint, tmp_path): def test_lint__with_one_file_arg(styleguide_lint, tmp_path): - """Test that we can specify the file on the cmd-line.""" + """Tests that we can specify the file on the cmd-line.""" (tmp_path / "spam.py").write_text(TOO_LONG_LINE) result = styleguide_lint(lint_args=[tmp_path / "spam.py"]) @@ -110,7 +110,7 @@ def test_lint__with_one_file_arg(styleguide_lint, tmp_path): def test_lint__with_one_multiple_file_args(styleguide_lint, tmp_path): - """Test that we can specify multiple files on the cmd-line.""" + """Tests that we can specify multiple files on the cmd-line.""" (tmp_path / "spam1.py").write_text(TOO_LONG_LINE) (tmp_path / "spam2.py").write_text(TOO_LONG_LINE) result = styleguide_lint(lint_args=[tmp_path / "spam1.py", tmp_path / "spam2.py"]) @@ -119,7 +119,7 @@ def test_lint__with_one_multiple_file_args(styleguide_lint, tmp_path): def test_lint__specifying_file_only_lints_file(styleguide_lint, tmp_path): - """Test that when we specify file(s) on the cmd line other files are not linted.""" + """Tests that when we specify file(s) on the cmd line other files are not linted.""" (tmp_path / "spam1.py").write_text(TOO_LONG_LINE) (tmp_path / "_spam2.py").write_text("") # empty result = styleguide_lint(lint_args=[tmp_path / "_spam2.py"]) @@ -128,7 +128,7 @@ def test_lint__specifying_file_only_lints_file(styleguide_lint, tmp_path): def test_lint__no_args_lints_dir(styleguide_lint, tmp_path): - """Test that when we specify no file(s) on the cmd line we lint the directory.""" + """Tests that when we specify no file(s) on the cmd line we lint the directory.""" (tmp_path / "spam.py").write_text(TOO_LONG_LINE) result = styleguide_lint() @@ -138,7 +138,7 @@ def test_lint__no_args_lints_dir(styleguide_lint, tmp_path): def test_lint__no_args_lints_subdirs(styleguide_lint, tmp_path): - """Test that when we specify no file(s) on the cmd line we lint subdirs.""" + """Tests that when we specify no file(s) on the cmd line we lint subdirs.""" (tmp_path / "subdir").mkdir() (tmp_path / "subdir" / "spam.py").write_text(TOO_LONG_LINE) @@ -149,7 +149,7 @@ def test_lint__no_args_lints_subdirs(styleguide_lint, tmp_path): def test_lint__lignores_venv_by_default(styleguide_lint, tmp_path): - """Test that we exclude ".venv" dir by default.""" + """Tests that we exclude ".venv" dir by default.""" (tmp_path / ".venv").mkdir() (tmp_path / ".venv" / "spam.py").write_text(TOO_LONG_LINE) @@ -159,7 +159,7 @@ def test_lint__lignores_venv_by_default(styleguide_lint, tmp_path): def test_lint__exclude__excludes_file(styleguide_lint_with_options, tmp_path): - """Test that exclude option excludes a file.""" + """Tests that exclude option excludes a file.""" (tmp_path / "spam.py").write_text(TOO_LONG_LINE) result = styleguide_lint_with_options(base_args=dict(exclude="spam.py")) @@ -178,7 +178,7 @@ def test_lint__exclude__excludes_dir(styleguide_lint_with_options, tmp_path): def test_lint__exclude__overrides_default(styleguide_lint_with_options, tmp_path): - """Test that specifying exclude option overrides the default exclude.""" + """Tests that specifying exclude option overrides the default exclude.""" (tmp_path / ".venv").mkdir() (tmp_path / ".venv" / "spam.py").write_text(TOO_LONG_LINE) @@ -189,7 +189,7 @@ def test_lint__exclude__overrides_default(styleguide_lint_with_options, tmp_path def test_lint__exclude__cmd_line_overrides_config(styleguide_lint, tmp_path, config_write): - """Test that specifying exclude option on the cmd-line overrides the exclude in config.""" + """Tests that specifying exclude option on the cmd-line overrides the exclude in config.""" (tmp_path / "dir1").mkdir() (tmp_path / "dir1" / "spam.py").write_text(TOO_LONG_LINE) (tmp_path / "dir2").mkdir() @@ -206,7 +206,7 @@ def test_lint__exclude__cmd_line_overrides_config(styleguide_lint, tmp_path, con def test_lint__extend_exclude__extends_exclude( styleguide_lint_with_options, tmp_path, config_write ): - """Test that extend-exclude adds to exclude.""" + """Tests that extend-exclude adds to exclude.""" (tmp_path / "dir1").mkdir() (tmp_path / "dir1" / "spam.py").write_text(TOO_LONG_LINE) (tmp_path / "dir2").mkdir() @@ -229,7 +229,7 @@ def test_lint__extend_exclude__extends_exclude( ], ) def test_lint__verbosity_args_allowed(styleguide_lint, verbosity_args): - """Test that using verbosity flags doesnt have any fatal side-effects.""" + """Tests that using verbosity flags doesnt have any fatal side-effects.""" result = styleguide_lint(base_args=[verbosity_args]) assert result, result.output diff --git a/tests/test_cli/test_lint_errors_parser.py b/tests/test_cli/test_lint_errors_parser.py index e7a29e38..6850b6af 100644 --- a/tests/test_cli/test_lint_errors_parser.py +++ b/tests/test_cli/test_lint_errors_parser.py @@ -28,7 +28,7 @@ @pytest.mark.parametrize("input_line", EXAMPLE_LINT_ERROR_LINES) def test_lint_errors_parser_handles_example_line_without_error(input_line): - """Test parser yields expected metadata.""" + """Tests the parser yields expected metadata.""" assert ni_python_styleguide._utils.lint.parse( input_line ), "should parse without error and return object" diff --git a/tests/test_convention_doc/conftest.py b/tests/test_convention_doc/conftest.py index 9a654dfd..643d72be 100644 --- a/tests/test_convention_doc/conftest.py +++ b/tests/test_convention_doc/conftest.py @@ -7,19 +7,19 @@ @pytest.fixture def sections(): - """Fixture with each convention section.""" + """All convention sections.""" return doctypes.SECTIONS @pytest.fixture def subsections(): - """Fixture with each convention subsection.""" + """All convention subsections.""" return doctypes.SUBSECTIONS @pytest.fixture def rules(): - """Fixture with each convention rule.""" + """All convention rules.""" return doctypes.RULES @@ -28,7 +28,7 @@ def rules(): params=[pytest.param(section, id=section.identifier) for section in doctypes.SECTIONS], ) def section(request): - """Parametrized fixture of each convention section.""" + """Each convention section.""" return request.param @@ -39,7 +39,7 @@ def section(request): ], ) def subsection(request): - """Parametrized fixture of each convention subsection.""" + """Each convention subsection.""" return request.param @@ -48,7 +48,7 @@ def subsection(request): params=[pytest.param(rule, id=rule.identifier) for rule in doctypes.RULES], ) def rule(request): - """Parametrized fixture of each convention rule.""" + """Each convention rule.""" return request.param @@ -61,7 +61,7 @@ def rule(request): ], ) def codeblock(request): - """Parametrized fixture of each convention codeblock.""" + """Each convention codeblock.""" return request.param @@ -75,7 +75,7 @@ def codeblock(request): ], ) def bad_codeblock(request): - """Parametrized fixture of each convention codeblock marked "Bad".""" + """Each convention codeblock marked "Bad".""" return request.param @@ -89,7 +89,7 @@ def bad_codeblock(request): ], ) def good_codeblock(request): - """Parametrized fixture of each convention codeblock marked "Good".""" + """Each convention codeblock marked "Good".""" return request.param @@ -103,5 +103,5 @@ def good_codeblock(request): ], ) def best_codeblock(request): - """Parametrized fixture of each convention codeblock marked "Best".""" + """Each convention codeblock marked "Best".""" return request.param diff --git a/tests/test_convention_doc/doctypes.py b/tests/test_convention_doc/doctypes.py index e0daa295..2930dccd 100644 --- a/tests/test_convention_doc/doctypes.py +++ b/tests/test_convention_doc/doctypes.py @@ -8,10 +8,12 @@ class _Region(object): @classmethod def from_text(cls, text, *, parent=None, header_depth=1): - """Return the region from the given convention text. + """Returns the region from the given convention text. - `parent` is forwarded to the constructor. - `header_depth` specifies which Markdown header depth to identify the section by. + Args: + text: (forwarded to the object constructor) + parent: (forwarded to the object constructor) + header_depth: specifies which Markdown header depth to identify the section by. """ header_marker = f"\\n{'#'* header_depth} \\[" @@ -25,9 +27,11 @@ def from_text(cls, text, *, parent=None, header_depth=1): ) def __init__(self, text, *, parent=None): - """Construct the region from the given convention text. + """Constructs the region from the given convention text. - `parent` can be optionally specified and should be a region which this region is a child of. + Args: + text: The textual contents of the region. + parent: Optional; A region which this region is a child of. """ if parent: self.parent = parent @@ -46,7 +50,7 @@ class Section(_Region): """ def __init__(self, text, **kwargs): - """Construct the section. + """Constructs the section. See help(_Region.__init__) for argument information. """ @@ -66,7 +70,7 @@ class SubSection(_Region): """ def __init__(self, text, **kwargs): - """Construct the subsection. + """Constructs the subsection. See help(_Region.__init__) for argument information. """ @@ -85,7 +89,7 @@ class Rule(_Region): """ def __init__(self, text, **kwargs): - """Construct the rule. + """Constructs the rule. See help(_Region.__init__) for argument information. """ @@ -100,7 +104,7 @@ def __init__(self, text, **kwargs): @staticmethod def _find_codeblocks(text): - r"""Find codeblocks in given text, yielding match objects. + r"""Finds codeblocks in given text, yielding match objects. >>> [match.groupdict() for match in Rule._find_codeblocks('```x=5```')] [{'language': None, 'description': None, 'body': 'x=5'}] @@ -118,6 +122,8 @@ def _find_codeblocks(text): >>> [match.groupdict() for match in Rule._find_codeblocks('```\n# Bad\nx=5```')] [{'language': None, 'description': 'Bad', 'body': 'x=5'}] + Args: + text: The text to find codeblocks in. """ yield from re.finditer( r"```((?P[a-z]+)\n)?(\n?# (?P.*?)\n)?(?P.*?)```", @@ -127,7 +133,7 @@ def _find_codeblocks(text): @property def error_codes(self): - """Return the error codes this rule is enforced by if any, None otherwise.""" + """Returns the error codes this rule is enforced by if any, None otherwise.""" match = re.search(r"\n> đŸ’ģ This rule is enforced by error codes? (.*?)\n", self.body_text) if match: return [error_code.strip("` ") for error_code in match[1].split(",")] @@ -138,7 +144,7 @@ class Codeblock(object): """A codeblock in the convention document.""" def __init__(self, rule, language, description, contents): - """Construct the codeblock. + """Constructs the codeblock. `rule` should be the Rule this codeblock is under. `language` should be the programming language specified for the codeblock. diff --git a/tests/test_convention_doc/test_codeblocks.py b/tests/test_convention_doc/test_codeblocks.py index bdd2e1cc..a7e97961 100644 --- a/tests/test_convention_doc/test_codeblocks.py +++ b/tests/test_convention_doc/test_codeblocks.py @@ -7,7 +7,7 @@ @pytest.fixture def lint_codeblock(styleguide, tmp_path): - """Fixture which runs the styleguide's `lint` subcommand when executed.""" + """Runs the styleguide's `lint` subcommand when executed.""" def run_linter( codeblock, @@ -42,17 +42,17 @@ def run_linter( def test_rule_codeblock_uses_python(codeblock): - """Test that the codeblock specifies "python" as its language.""" + """Tests that the codeblock specifies "python" as its language.""" assert codeblock.language == "python" def test_rule_codeblocks_documents_bad_good_best(codeblock): - """Test that the codeblock has a descriptor (first line comment) specifying Good/Bad/Best.""" + """Tests that the codeblock has a descriptor (first line comment) specifying Good/Bad/Best.""" assert codeblock.descriptor in ("Good", "Bad", "Best") def test_bad_codeblocks_document_lint_errors(lint_codeblock, bad_codeblock): - """Test that "bad" codeblocks fail to lint and documents the resulting error codes.""" + """Tests that "bad" codeblocks fail to lint and documents the resulting error codes.""" if bad_codeblock.rule.is_automatically_enforced: result = lint_codeblock( bad_codeblock, @@ -63,9 +63,11 @@ def test_bad_codeblocks_document_lint_errors(lint_codeblock, bad_codeblock): error_codes = set(code.strip("'") for code in result.output.splitlines()) assert error_codes + expected_error_codes = set(bad_codeblock.rule.error_codes) + error_codes_not_expected = error_codes - expected_error_codes assert error_codes.issubset( - set(bad_codeblock.rule.error_codes) - ), '"Bad" codeblock caused unexpected lint error' + expected_error_codes + ), f'"Bad" codeblock caused unexpected lint error - {error_codes_not_expected}' else: # "Bad" codeblock caused a lint error, but isn't marked as automatically enforced result = lint_codeblock(bad_codeblock) @@ -73,12 +75,12 @@ def test_bad_codeblocks_document_lint_errors(lint_codeblock, bad_codeblock): def test_good_codeblocks_have_no_lint_errors(lint_codeblock, good_codeblock): - """Test that "good" codeblocks do not fail to lint.""" + """Tests that "good" codeblocks do not fail to lint.""" result = lint_codeblock(good_codeblock) assert result, result.output def test_best_codeblocks_have_no_lint_errors(lint_codeblock, best_codeblock): - """Test that "best" codeblocks do not fail to lint.""" + """Tests that "best" codeblocks do not fail to lint.""" result = lint_codeblock(best_codeblock) assert result, result.output diff --git a/tests/test_convention_doc/test_rules.py b/tests/test_convention_doc/test_rules.py index b6cfd518..5150e9bc 100644 --- a/tests/test_convention_doc/test_rules.py +++ b/tests/test_convention_doc/test_rules.py @@ -16,24 +16,24 @@ ], ) def enumerated_rule(request): - """Parametrized fixture of each rule along with its index in the parent subsection.""" + """Each rule along with its index in the parent subsection.""" return request.param def test_rule_identifier_valid(rule): - """Test that the rule's identifier is a valid rule identifier and matches expectations.""" + """Tests that the rule's identifier is a valid rule identifier and matches expectations.""" assert re.match(r"[A-Z]+\.[1-9][0-9]*\.[1-9][0-9]*", rule.identifier) assert rule.identifier.startswith(rule.parent.identifier) def test_rule_identifiers_strictly_increasing(enumerated_rule): - """Test that the rules in a subsection use strictly incrementing identifiers.""" + """Tests that the rules in a subsection use strictly incrementing identifiers.""" index, rule = enumerated_rule assert rule.identifier.split(".")[-1] == str(index + 1) def test_rule_identifier_follows_prefix_convention(rule): - """Test that the rule title follows our prefix convention.""" + """Tests that the rule title follows our prefix convention.""" assert ( rule.header_text.startswith(" âœ”ī¸ **DO**") or rule.header_text.startswith(" âœ”ī¸ **CONSIDER**") @@ -43,13 +43,13 @@ def test_rule_identifier_follows_prefix_convention(rule): def test_rule_identifier_follows_case_convention(rule): - """Test that the rule header starts with an uppercase letter.""" + """Tests that the rule header starts with an uppercase letter.""" rule_title = ("**".join(rule.header_text.split("**")[2:])).strip() assert rule_title[0] == rule_title[0].upper(), "header should start with an uppercase letter" def test_rule_documents_enforcement_codes(rule): - """Test that if rule is marked as automatically enforced, it lists the relevant codes.""" + """Tests that if rule is marked as automatically enforced, it lists the relevant codes.""" if rule.is_automatically_enforced: assert rule.error_codes is not None else: diff --git a/tests/test_convention_doc/test_sections.py b/tests/test_convention_doc/test_sections.py index 61ce9115..588a38e1 100644 --- a/tests/test_convention_doc/test_sections.py +++ b/tests/test_convention_doc/test_sections.py @@ -5,12 +5,12 @@ def test_section_identifier_valid(section): - """Test that the section's identifier is alphabetic.""" + """Tests that the section's identifier is alphabetic.""" assert re.match(r"[A-Z]+", section.identifier) def test_section_identifiers_unique(sections): - """Test that the section's identifiers are unique.""" + """Tests that the section's identifiers are unique.""" section_identifier_counts = collections.defaultdict(int) for section in sections: section_identifier_counts[section.identifier] += 1 @@ -19,6 +19,6 @@ def test_section_identifiers_unique(sections): def test_section_identifier_follows_case_convention(section): - """Test that the section's header starts with an uppercase letter.""" + """Tests that the section's header starts with an uppercase letter.""" header_text = section.header_text.lstrip() assert header_text[0].isupper(), "header should start with an uppercase letter" diff --git a/tests/test_convention_doc/test_subsections.py b/tests/test_convention_doc/test_subsections.py index 8616619c..8c9367f0 100644 --- a/tests/test_convention_doc/test_subsections.py +++ b/tests/test_convention_doc/test_subsections.py @@ -16,24 +16,24 @@ ], ) def enumerated_subsections(request): - """Parametrized fixture of each subsection along with its index in the parent section.""" + """Each subsection along with its index in the parent section.""" return request.param def test_subsection_identifier_valid(subsection): - """Test that the section's identifier is a valid section identifier and matches expectations.""" + """Tests that the section's identifier is valid and matches expectations.""" assert re.match(r"[A-Z]+\.[1-9][0-9]*", subsection.identifier) assert subsection.identifier.startswith(subsection.parent.identifier) def test_subsection_identifiers_strictly_increasing(enumerated_subsections): - """Test that the subsections in a section use strictly incrementing identifiers.""" + """Tests that the subsections in a section use strictly incrementing identifiers.""" index, subsection = enumerated_subsections assert subsection.identifier.split(".")[-1] == str(index + 1) def test_subsection_isnt_rule(subsection): - """Test that we don't use subsections for rules.""" + """Tests that we don't use subsections for rules.""" assert not ( subsection.header_text.startswith(" âœ”ī¸ **DO**") or subsection.header_text.startswith(" âœ”ī¸ **CONSIDER**") @@ -43,6 +43,6 @@ def test_subsection_isnt_rule(subsection): def test_subsection_identifier_follows_case_convention(subsection): - """Test that the subsection header starts with an uppercase letter.""" + """Tests that the subsection header starts with an uppercase letter.""" header_text = subsection.header_text.lstrip() assert header_text[0].isupper(), "header should start with an uppercase letter"