diff --git a/docs/Coding-Conventions.md b/docs/Coding-Conventions.md index eaefca95..7510af8d 100644 --- a/docs/Coding-Conventions.md +++ b/docs/Coding-Conventions.md @@ -861,6 +861,10 @@ 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. + ### [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) diff --git a/ni_python_styleguide/_cli.py b/ni_python_styleguide/_cli.py index 825f1abe..c4a0145d 100644 --- a/ni_python_styleguide/_cli.py +++ b/ni_python_styleguide/_cli.py @@ -38,7 +38,7 @@ class AllowConfigGroup(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/config.ini b/ni_python_styleguide/config.ini index 6d5e0596..ca744375 100644 --- a/ni_python_styleguide/config.ini +++ b/ni_python_styleguide/config.ini @@ -65,6 +65,13 @@ 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 # 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 diff --git a/tests/conftest.py b/tests/conftest.py index bf2b63c8..07b36cc6 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,14 +10,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. @@ -40,7 +40,7 @@ def runner(*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_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_lint.py b/tests/test_cli/test_lint.py index db2dceae..44ad8816 100644 --- a/tests/test_cli/test_lint.py +++ b/tests/test_cli/test_lint.py @@ -11,7 +11,7 @@ @pytest.fixture def styleguide_lint(styleguide, tmp_path, chdir): - """Fixture which will run the styleguide with the "lint" subcommand. + """Runs the styleguide with the "lint" subcommand. Both `base_args` and `lint_args` must be iterables which will be transformed into strings and passed on the cmd line in the following order: ` lint . @@ -29,7 +29,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( @@ -48,7 +48,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 @@ -74,7 +74,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 @@ -82,7 +82,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. @@ -103,7 +103,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"]) @@ -112,7 +112,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"]) @@ -121,7 +121,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"]) @@ -130,7 +130,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() @@ -140,7 +140,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) @@ -151,7 +151,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) @@ -161,7 +161,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")) @@ -180,7 +180,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) @@ -191,7 +191,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() @@ -208,7 +208,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() @@ -231,7 +231,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_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..c5d782a0 100644 --- a/tests/test_convention_doc/doctypes.py +++ b/tests/test_convention_doc/doctypes.py @@ -8,10 +8,13 @@ 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. + + 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. - `parent` is forwarded to the constructor. - `header_depth` specifies which Markdown header depth to identify the section by. """ header_marker = f"\\n{'#'* header_depth} \\[" @@ -25,9 +28,12 @@ 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. + + Args: + text: The textual contents of the region. + parent: Optional; A region which this region is a child of. - `parent` can be optionally specified and should be a region which this region is a child of. """ if parent: self.parent = parent @@ -46,7 +52,7 @@ class Section(_Region): """ def __init__(self, text, **kwargs): - """Construct the section. + """Constructs the section. See help(_Region.__init__) for argument information. """ @@ -66,7 +72,7 @@ class SubSection(_Region): """ def __init__(self, text, **kwargs): - """Construct the subsection. + """Constructs the subsection. See help(_Region.__init__) for argument information. """ @@ -85,7 +91,7 @@ class Rule(_Region): """ def __init__(self, text, **kwargs): - """Construct the rule. + """Constructs the rule. See help(_Region.__init__) for argument information. """ @@ -100,7 +106,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 +124,9 @@ 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 +136,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 +147,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 614cfddc..7e36f068 100644 --- a/tests/test_convention_doc/test_codeblocks.py +++ b/tests/test_convention_doc/test_codeblocks.py @@ -5,7 +5,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, @@ -35,17 +35,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, @@ -66,12 +66,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"