39 Commits
Author SHA1 Message Date
jakob.scheid b2a8e54766 Merge pull request 'Chore: prepare release 0.2.0' (#49) from chore/prepare-0-2-0 into main
Release package / Build package (release) Successful in 24s
Release package / Prepare release asset upload (release) Successful in 14s
Release package / Publish package to package registry (release) Successful in 16s
Release package / Upload release asset (${{ fromJSON(needs.prepare_upload_release_asset.outputs.files) }}) (release) Successful in 23s
Reviewed-on: #49
2026-09-28 00:40:29 +02:00
jakob.scheid 773294f3d9 docs(changelog): move unreleased section to 0.2.0 2026-09-28 00:35:43 +02:00
jakob.scheid 200221e324 chore: update version in pyproject.toml to 0.2.0 2026-09-28 00:34:39 +02:00
jakob.scheid e8bcf4feb1 Merge pull request 'Fix(ci): spelling error in API reference workflow' (#48) from fix/fix-api-reference-spelling into main
Reviewed-on: #48
2026-09-28 00:31:45 +02:00
jakob.scheid ff3bddd366 fix(ci): fix spelling in API reference workflow
Replaced '--chached' with '--cached' and replaced '--quit' with
'--quiet'.
2026-09-28 00:29:11 +02:00
jakob.scheid e94365faf8 Merge pull request 'Chore(ci): adapt API reference workflow to the new API' (#45) from feature/adapt-api-reference-workflow-to-new-cli into main
Reviewed-on: #45
2026-09-28 00:22:39 +02:00
jakob.scheid 95da53898c chore(ci): adapt API reference workflow to new API
Adapted the API reference generation workflow to the new API, which no
longer requires the src/ structure.
2026-09-28 00:18:44 +02:00
jakob.scheid 4d2e63d560 refactor(ci): use force overwriting feature 2026-09-28 00:17:30 +02:00
jakob.scheid 2187590468 Merge pull request 'Refactor: lint code' (#43) from refactor/lint into main
Reviewed-on: #43
2026-09-28 00:08:30 +02:00
jakob.scheid 37308227d9 chore: add noqa comments to wildcard imports
Added noqa comments to suppress linting warnings for wildcard imports.
2026-09-28 00:04:53 +02:00
jakob.scheid f796263c0e fix: fix syntax errors (target version)
Fixed all lines which were syntax errors in the target version (only
multi-line f-strings).
2026-09-28 00:04:53 +02:00
jakob.scheid 896bfcc2dd style: use target version practices 2026-09-28 00:04:53 +02:00
jakob.scheid b2a7c9a0e3 style: fix lines which exceed the line length limit 2026-09-28 00:04:44 +02:00
jakob.scheid ac72eb283c style: organize imports
Organized imports according to Ruff (I001).
2026-09-27 22:23:58 +02:00
jakob.scheid 21c5c20cb5 Merge pull request 'Fix(python-generator): Python namespaces comparision type check' (#41) from fix/python-namespace-comparision-type-check into main
Reviewed-on: #41
2026-09-27 22:17:15 +02:00
jakob.scheid 3865db7919 test(python-generator): add test cases for package namespace comparision
Added test cases with different types for Python package namespace
comparision test.
2026-09-27 22:16:15 +02:00
jakob.scheid ec262ef99e feat(python-generator): check type at package namespace comparision
Added type check to the Python package namespace comparision function.
2026-09-27 22:15:57 +02:00
jakob.scheid f102fa80ce test(python-generator): add test cases for module namespace comparision
Added test cases with different types for Python module namespace
comparision test.
2026-09-27 22:15:55 +02:00
jakob.scheid 6d2b32a736 feat(python-generator): check type at module namespace comparision
Added type check to the Python module namespace comparision function.
2026-09-27 22:01:19 +02:00
jakob.scheid 934624fce3 Merge pull request 'Feat(python-generator): protection against accidental overwriting of the output directory' (#40) from feature/protect-against-accidental-overwriting into main
Reviewed-on: #40
2026-09-27 21:56:40 +02:00
jakob.scheid b043a4ea17 docs(changelog): add accidental overwriting protection entry
Added a changelog entry for the protection against accidental
overwriting of the output directory.
2026-09-27 17:37:51 +02:00
jakob.scheid f2b9f47e09 test(cli): add tests for Python force overwriting
Added a test to the CLI test file for the documentation generation
error.
2026-09-27 17:36:04 +02:00
jakob.scheid f0c271f8fd feat(cli): add Python generator force argument 2026-09-27 15:09:35 +02:00
jakob.scheid d8508e0fa3 test(python-generator): add tests for force overwriting
Added tests to test new output directory deletion behavior:
  - output directory overwriting (not empty; force)
  - error (not empty; not force)
  - nothing (empty; force)
  - nothing (empty; not force)
One test was adapted to output directory emptiness check because the
.gitkeep file which is required for Git to track the directory makes it
non-empty.
2026-09-27 15:09:17 +02:00
jakob.scheid 5791358b41 feat(python-generator): add force argument to generator
Added a force argument to
PythonDocumentationGenerator.generate_documentation to control whether
the content of the output directory should be overwritten or not, if it
is not empty. If the force argument is True, the output directory
content will first be deleted recursively. If it is False and the output
directory is not empty, a DirectoryNotEmptyError will be raised.
2026-09-27 14:59:28 +02:00
jakob.scheid 0261a7b3a6 feat(exceptions): add DirectoryNotEmptyError
Added an OSError subclass for indicating that the directory is not
empty. This exception is explicitly handled by the CLI now.
2026-09-26 16:28:40 +02:00
jakob.scheid 2fe342cbc6 Merge pull request 'Feat(python-generator): remove implicit assumptions of project directory structure' (#39) from feature/no-src-dir-need into main
Reviewed-on: #39
2026-09-22 19:28:50 +02:00
jakob.scheid 53ab0e3829 docs(changelog): add project directory structure entry
Added an entry that the implicit Python project directory
structure assumptions have been removed to the changelog.
2026-09-22 19:28:34 +02:00
jakob.scheid c40e965d8d test(python-generator): update tests to do not assume src/ directories
Updated tests to do not implicitly assume a 'src/' directory structure
and removed all 'src/' subdirectory structures in test project
directories (if possible).
2026-09-22 19:26:55 +02:00
jakob.scheid 0fbfe84657 feat(python-generator)!: do not require specific structure
Removed all implicit assumptions of a project structure:
  - no 'src/' directory is required
  - top-level modules are no longer ignored
2026-09-22 18:28:35 +02:00
jakob.scheid d0ea392f62 Merge pull request 'Feature(python-generator): output directory creation' (#37) from feature/ensure-output-dir-exists into main
Reviewed-on: #37
2026-09-22 17:11:04 +02:00
jakob.scheid 717a8c446e docs(changelog): add docs directory creation entry
Added a changelog entry for the creation of the documentation directory
at the Python documentation generator.
2026-09-22 17:08:15 +02:00
jakob.scheid ec156a538e test(python-generator): add test for directory creation
Added a testing function which tests whether the documentation directory
is created when the documentation is generated.
2026-09-22 17:04:56 +02:00
jakob.scheid e2264696e8 feat(python-generator): create output directory
Now, the output directory and its parents are created when generating
the documentation.
2026-09-22 17:00:34 +02:00
jakob.scheid 6cf3de156d Merge pull request 'Test(python-generator): name testing function correctly' (#36) from test/name-testing-functions-correctly into main
Reviewed-on: #36
2026-09-22 16:49:28 +02:00
jakob.scheid b6d2fa7db8 test(python-generator): name testing function correctly 2026-09-22 16:47:18 +02:00
jakob.scheid 63cef6f641 Merge pull request 'Fix(python-generator): make generated signatures compliant with PEP 8' (#35) from fix/python-signatures-pep-8-compliance into main
Reviewed-on: #35
2026-09-22 16:15:35 +02:00
jakob.scheid 06802c96f6 docs(changelog): add Python signatures PEP 8 compliance entry
Added a changelog entry for the PEP 8 compliance of Python function
signatures default values.
2026-09-22 16:13:43 +02:00
jakob.scheid 17c5e4938f test(python-generator): update tests for PEP 8 compliance
Updated test cases to the new default value PEP 8 compliance and added
new test cases to test the new behavior.
2026-09-22 16:13:23 +02:00
33 changed files with 605 additions and 110 deletions

No files matched your search

+2 -3
View File
@@ -39,8 +39,7 @@ jobs:
- name: Generate documentation
run: |
rm -rf docs/reference
jcloud-docsgen python -T -o docs/reference .
jcloud-docsgen python -T -f -o docs/reference ./src
- name: Commit and push
run: |
@@ -49,7 +48,7 @@ jobs:
git add docs/reference
if git diff --chached --quit; then
if git diff --cached --quiet; then
echo "No changes"
exit 0
fi
+5 -1
View File
@@ -1,15 +1,19 @@
# Changelog
## [Unreleased]
## [0.2.0] - 2026-09-28
### Added
- CLI for `jcloud-docsgen` that can be called without `python3 -m ...`
- CI pipeline to generate API reference on every push or merge on `main`
- Python generator output directory creation
- Protection against accidental overwriting of the output directory
### Changed
- Replaced the installation instructions, which used the old registry, with a reference to the Gitea Package Registry in README
- Made Python function signatures (argument default values) compliant with PEP 8
- Removed implicit Python project directory structure assumptions
### Deprecated
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
[project]
name = "jcloud-docsgen"
version = "0.1.0"
version = "0.2.0"
description = "A tool that generates Markdown documentation for software project source code"
dependencies = ["docstring-parser"]
requires-python = ">=3.10"
+1 -1
View File
@@ -13,7 +13,7 @@
# limitations under the License.
from . import cli
from .core import *
from .core import * # noqa: F403
from .core import __all__ as _core__all__
__all__ = [
+14 -3
View File
@@ -20,6 +20,7 @@ import argparse
import pathlib
import sys
from ..exceptions import DirectoryNotEmptyError
from .languages.python import VALID_SECTIONS as VALID_PYTHON_SECTIONS
__all__ = [
@@ -78,8 +79,18 @@ def create_argument_parser() -> argparse.ArgumentParser:
'-o',
'--output-dir',
type=pathlib.Path,
default='docs/reference',
help='the output directory the documentation will be written to',
)
common_parser.add_argument(
'-f',
'--force',
action='store_true',
help=(
'generate documentation even if the output directory is not '
'empty. Warning: data can be lost when setting this flag.'
),
)
argument_parser = argparse.ArgumentParser()
@@ -138,9 +149,6 @@ def main(argv=None) -> int:
argument_parser = create_argument_parser()
args = argument_parser.parse_args(argv)
if args.output_dir is None:
args.output_dir = args.project_directory / 'docs/reference'
try:
if args.language == _LANG_PYTHON:
from .languages.python import generate
@@ -152,6 +160,7 @@ def main(argv=None) -> int:
exclude_sections=args.sections_exclude,
allow_html=args.allow_html,
allow_tables=args.allow_tables,
force=args.force,
)
except FileNotFoundError as exc:
return error(f'{exc.filename}: no such file or directory')
@@ -159,6 +168,8 @@ def main(argv=None) -> int:
return error(f'{exc.filename}: not a directory')
except IsADirectoryError as exc:
return error(f'{exc.filename}: is a directory')
except DirectoryNotEmptyError as exc:
return error(f'{exc.filename}: directory not empty')
except FileExistsError as exc:
return error(f'{exc.filename}: file already exists')
except PermissionError as exc:
+10 -1
View File
@@ -78,6 +78,7 @@ def _generate(
),
allow_html: bool = False,
allow_tables: bool = False,
force: bool = False,
) -> None:
"""
Generates the documentation for a Python project.
@@ -94,6 +95,9 @@ def _generate(
:type allow_html: bool
:param allow_tables: Indicates whether Markdown tables are allowed.
Warning: Markdown tables are not CommonMark.
:param force: Indicates whether the output directory shall be
overwritten if it is not empty.
:type force: bool
"""
docs_generator = PythonDocumentationGenerator(
@@ -103,7 +107,7 @@ def _generate(
allow_html=allow_html,
allow_tables=allow_tables,
)
docs_generator.generate_documentation()
docs_generator.generate_documentation(force)
def generate(
@@ -114,6 +118,7 @@ def generate(
exclude_sections: list[str] = [],
allow_html: bool = False,
allow_tables: bool = False,
force: bool = False,
) -> None:
"""
Generates the documentation for a Python project.
@@ -133,6 +138,9 @@ def generate(
:type allow_html: bool
:param allow_tables: Indicates whether Markdown tables are allowed.
Warning: Markdown tables are not CommonMark.
:param force: Indicates whether the output directory shall be
overwritten if it is not empty.
:type force: bool
"""
sections = parse_sections_list(include_sections, exclude_sections)
@@ -143,4 +151,5 @@ def generate(
include_sections=sections,
allow_html=allow_html,
allow_tables=allow_tables,
force=force,
)
+1 -1
View File
@@ -13,7 +13,7 @@
# limitations under the License.
from . import namespaces
from ._core import *
from ._core import * # noqa: F403
from ._core import __all__ as _core__all__
__all__ = [
+40 -23
View File
@@ -16,13 +16,18 @@ from __future__ import annotations
import ast
import pathlib
import shutil
from collections.abc import Iterator
from dataclasses import dataclass
from typing import TypeAlias
import docstring_parser
from ...exceptions import InvalidNamespaceError, PythonArgumentStructureError
from ...exceptions import (
DirectoryNotEmptyError,
InvalidNamespaceError,
PythonArgumentStructureError,
)
from ...utils import get_relative_path_segments, non_empty_str
from .arguments import PythonArgumentKind, PythonFunctionArgument
from .definitions import (
@@ -244,9 +249,8 @@ def _markdown_table(
if len(row) != header_len:
if force_row_lengths:
raise ValueError(
f'expected {header_len} value{
"s" if header_len > 1 else ""
}, got {len(row)}',
f'expected {header_len} value'
f'{"s" if header_len > 1 else ""}, got {len(row)}'
)
else:
row = _fit_row_length(header_len, row)
@@ -272,9 +276,8 @@ def _markdown_table(
if len(row) != header_len:
if force_row_lengths:
raise ValueError(
f'expected {header_len} value{
"s" if header_len > 1 else ""
}, got {len(row)}',
f'expected {header_len} value'
f'{"s" if header_len > 1 else ""}, got {len(row)}'
)
else:
row = _fit_row_length(header_len, row)
@@ -596,11 +599,10 @@ class PythonDefinitionDocumentationGenerator:
if _is_docstring(self.definition.doc) or not self.skip_empty_sections:
if self.allow_html:
md += f'<details><summary><h{
str(self.level + 1)
} style="display:inline">Docstring</h{
str(self.level + 1)
}></summary>'
md += (
f'<details><summary><h{str(self.level + 1)} style="displa'
f'y:inline">Docstring</h{str(self.level + 1)}></summary>'
)
else:
md += self.level * '#' + '# Docstring\n\n'
@@ -1104,31 +1106,46 @@ class PythonDocumentationGenerator:
return namespace
def namespace(self) -> list[PythonPackageNamespace]:
def namespace(self) -> PythonPackageNamespace:
"""
Returns the project as a namespace.
:return: The project as a namespace.
:rtype: list[PythonPackageNamespace]
:rtype: PythonPackageNamespace:
"""
src_dir = self.project_directory / 'src'
return self._namespace(self.project_directory)
return [
self._namespace(dir) for dir in src_dir.iterdir() if dir.is_dir()
]
def generate_documentation(self) -> None:
def generate_documentation(self, force: bool = False) -> None:
"""
Generates the full project documentation and writes it to the
documentation directory.
:param force: Indicates whether existing contents of the output
directory shall be overwritten. If ``True``, all
contents of the output directory will be deleted
first.
:type force: bool
:raises DirectoryNotEmptyError: If ``force`` is ``False`` and
the output directory is not
empty.
"""
if self.docs_directory.exists() and list(
self.docs_directory.iterdir()
):
if force:
shutil.rmtree(self.docs_directory)
else:
raise DirectoryNotEmptyError(str(self.docs_directory))
self.docs_directory.mkdir(parents=True, exist_ok=True)
_generate_package_namespace_documentation(
PythonPackageNamespace('src', self.namespace()),
self.namespace(),
self.docs_directory,
self.project_directory / 'src',
self.project_directory / 'src',
self.project_directory,
self.project_directory,
self.include_sections,
self.kwargs,
)
+2 -2
View File
@@ -156,7 +156,7 @@ class PythonPackageNamespace(PythonNamespace):
# For performance reasons, is not called self.sub_namespace_names
# if the name attribute does not match, which can be quickly
# verified
if self.name != value.name:
if not (isinstance(value, type(self)) and self.name == value.name):
return False
return value.sub_namespace_names() == self.sub_namespace_names()
@@ -223,4 +223,4 @@ class PythonModuleNamespace(PythonNamespace):
super().__init__(name)
def __eq__(self, value: PythonModuleNamespace) -> bool:
return self.name == value.name
return isinstance(value, type(self)) and self.name == value.name
+31 -12
View File
@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import errno
class NamespaceError(ValueError):
"""
@@ -26,9 +28,11 @@ class NamespaceError(ValueError):
if not self.args:
return ''
else:
return f'{self.args[0]}{
": " if self.namespace_identifier and self.args[0] else ""
}{self.namespace_identifier if self.args[0] else ""}'
return (
self.args[0]
+ (': ' if self.namespace_identifier and self.args[0] else '')
+ (self.namespace_identifier if self.args[0] else '')
)
class InvalidNamespaceError(NamespaceError): ...
@@ -53,9 +57,11 @@ class PythonIdentifierError(ValueError):
if not self.args:
return ''
else:
return f'{self.args[0]}{
": " if self.identifier and self.args[0] else ""
}{self.identifier if self.args[0] else ""}'
return (
self.args[0]
+ (': ' if self.identifier and self.args[0] else '')
+ (self.identifier if self.args[0] else '')
)
class InvalidPythonIdentifierError(PythonIdentifierError): ...
@@ -74,9 +80,11 @@ class PythonAnnotationError(ValueError):
if not self.args:
return ''
else:
return f'{self.args[0]}{
": " if self.annotation and self.args[0] else ""
}{self.annotation if self.args[0] else ""}'
return (
self.args[0]
+ (': ' if self.annotation and self.args[0] else '')
+ (self.annotation if self.args[0] else '')
)
class InvalidPythonAnnotationError(PythonAnnotationError): ...
@@ -95,9 +103,20 @@ class PythonDefinitionError(ValueError):
if not self.args:
return ''
else:
return f'{self.args[0]}{
": " if self.definition and self.args[0] else ""
}{self.definition if self.args[0] else ""}'
return (
self.args[0]
+ (': ' if self.definition and self.args[0] else '')
+ (self.definition if self.args[0] else '')
)
class PythonArgumentStructureError(PythonDefinitionError): ...
class DirectoryNotEmptyError(OSError):
"""
Directory is not empty.
"""
def __init__(self, filename: str | None = None) -> None:
super().__init__(errno.ENOTEMPTY, 'Directory not empty', filename)
+5 -7
View File
@@ -20,7 +20,6 @@ import errno
import os
import pathlib
import types
from typing import Union
try:
from warnings import deprecated
@@ -154,10 +153,10 @@ def assert_that_is_instance(
obj: object,
class_or_tuple: type | types.UnionType | tuple[type, ...],
) -> None:
if not isinstance(class_or_tuple, Union[type, types.UnionType, tuple]):
if not isinstance(class_or_tuple, (type, types.UnionType, tuple)):
raise TypeError(
f"class_or_tuple: expected 'Union[type, types.UnionType, "
f"tuple[type, ...]]', 'got {type(class_or_tuple).__name__}'",
f"class_or_tuple: expected 'type | types.UnionType, tupl"
f"e[type, ...]', 'got {type(class_or_tuple).__name__}'",
)
if not isinstance(obj, class_or_tuple):
if isinstance(class_or_tuple, (tuple, types.UnionType)):
@@ -175,9 +174,8 @@ def assert_that_is_instance(
else:
exception_message_expected = "'" + class_or_tuple.__name__ + "'"
raise TypeError(
f"expected {exception_message_expected}, got '{
type(obj).__name__
}'",
f'expected {exception_message_expected}'
f", got '{type(obj).__name__}'"
)
+26
View File
@@ -13,6 +13,7 @@
# limitations under the License.
import pathlib
import tempfile
import pytest
@@ -174,7 +175,30 @@ def test_sections_success():
def test_docs_generation(expectdir):
with expectdir('python_project') as output_dir:
output_dir: pathlib.Path
(output_dir / 'test_dir').mkdir()
input_dir = pathlib.Path(__file__).parent / 'python_project/project'
assert (
cli_main(
[
'python',
'-s',
'params',
'docstring',
'-HTfo',
str(output_dir),
str(input_dir),
]
)
== 0
)
def test_docs_generation_error():
with tempfile.TemporaryDirectory() as output_dir:
output_dir = pathlib.Path(output_dir)
(output_dir / 'test_dir').mkdir()
input_dir = pathlib.Path(__file__).parent / 'python_project/project'
assert (
cli_main(
[
'python',
@@ -186,3 +210,5 @@ def test_docs_generation(expectdir):
str(input_dir),
]
)
== 1
)
@@ -131,7 +131,7 @@ def _signature_section(signature: str) -> str:
[],
),
),
"a(a = '42') -> str",
"a(a='42') -> str",
),
(
PythonDefinitionDocumentationGenerator(
@@ -249,6 +249,46 @@ def _signature_section(signature: str) -> str:
'allow_html: bool = True, level: int = 1) -> None'
),
),
(
PythonDefinitionDocumentationGenerator(
PythonFunctionDefinition(
'__init__',
[
PythonFunctionArgument(
'self',
PythonArgumentKind.NORMAL,
None,
None,
),
PythonFunctionArgument(
'definition',
PythonArgumentKind.NORMAL,
None,
'PythonDefinition',
),
PythonFunctionArgument(
'allow_html',
PythonArgumentKind.KEYWORD_ONLY,
'True',
'bool',
),
PythonFunctionArgument(
'level',
PythonArgumentKind.KEYWORD_ONLY,
'1',
None,
),
],
'None',
None,
[],
),
),
(
'__init__(self, definition: PythonDefinition, *, '
'allow_html: bool = True, level=1) -> None'
),
),
],
)
def test_PythonDefinitionDocumentationGenerator_generate_signature(
@@ -371,7 +411,7 @@ def test_PythonDefinitionDocumentationGenerator_generate_signature_exceptions(
[],
),
),
"a(a = '42') -> str",
"a(a='42') -> str",
),
(
PythonDefinitionDocumentationGenerator(
@@ -1796,7 +1836,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -1938,7 +1978,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -2081,7 +2121,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -2191,7 +2231,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -2301,7 +2341,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -2446,7 +2486,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -2592,7 +2632,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -2705,7 +2745,7 @@ Very long ...
## Function signature
```python
a(hello: int, /, world = 1, *, something: str = 'something', **value) -> bool
a(hello: int, /, world=1, *, something: str = 'something', **value) -> bool
```
## Returns
@@ -13,6 +13,7 @@
# limitations under the License.
import pathlib
import tempfile
import pytest
@@ -21,6 +22,7 @@ from src.jcloud_docsgen.core.python.namespaces import (
PythonModuleNamespace,
PythonPackageNamespace,
)
from src.jcloud_docsgen.exceptions import DirectoryNotEmptyError
@pytest.mark.parametrize(
@@ -29,7 +31,7 @@ from src.jcloud_docsgen.core.python.namespaces import (
(
PythonDocumentationGenerator(
pathlib.Path(
'tests/unit/core/python/_core/test_project_dirs/pdir_1'
'tests/unit/core/python/_core/test_project_dirs/pdir_1/src'
),
pathlib.Path(
'tests/unit/core/python/_core/test_project_dirs/pdir_1/docs'
@@ -40,7 +42,7 @@ from src.jcloud_docsgen.core.python.namespaces import (
(
PythonDocumentationGenerator(
pathlib.Path(
'tests/unit/core/python/_core/test_project_dirs/pdir_2'
'tests/unit/core/python/_core/test_project_dirs/pdir_2/src'
),
pathlib.Path(
'tests/unit/core/python/_core/test_project_dirs/pdir_2/docs'
@@ -56,7 +58,7 @@ from src.jcloud_docsgen.core.python.namespaces import (
(
PythonDocumentationGenerator(
pathlib.Path(
'tests/unit/core/python/_core/test_project_dirs/pdir_3'
'tests/unit/core/python/_core/test_project_dirs/pdir_3/src'
),
pathlib.Path(
'tests/unit/core/python/_core/test_project_dirs/pdir_3/docs'
@@ -83,7 +85,9 @@ def test_PythonDocumentationGenerator_collect_modules(
python_documentation_generator: PythonDocumentationGenerator,
expected,
):
assert python_documentation_generator.namespace() == expected
assert (
python_documentation_generator.namespace().sub_namespaces
) == expected
@pytest.mark.parametrize(
@@ -118,4 +122,75 @@ def test_generate_documentation(dir, expectdir):
pathlib.Path(str(d)),
allow_tables=True,
allow_html=False,
).generate_documentation() # simplify the tests
).generate_documentation(True) # simplify the tests
def test_creates_directory():
with tempfile.TemporaryDirectory() as output_dir:
output_dir = pathlib.Path(output_dir)
with tempfile.TemporaryDirectory() as project_dir:
project_dir = pathlib.Path(project_dir)
# The directory of the package
package_dir = project_dir / 'pkg'
assert not package_dir.exists()
package_dir.mkdir(parents=True, exist_ok=True)
# The actual output directory directory
docs_dir = output_dir / 'docs' / 'reference'
# It should not exist
assert not docs_dir.exists()
docs_generator = PythonDocumentationGenerator(
project_dir, docs_dir
)
docs_generator.generate_documentation()
assert docs_dir.exists()
class TestForce:
def _prepare(self, directory):
directory = pathlib.Path(directory)
src_directory = directory / 'src'
src_directory.mkdir()
docs_directory = directory / 'docs'
docs_directory.mkdir()
return directory, src_directory, docs_directory
def test_overwrites_output_directory(self):
with tempfile.TemporaryDirectory() as directory:
directory, src_directory, docs_directory = self._prepare(directory)
test_dir = docs_directory / 'test_dir'
test_dir.mkdir()
documentation_generator = PythonDocumentationGenerator(
src_directory, docs_directory
)
documentation_generator.generate_documentation(True)
assert not test_dir.exists()
def test_error(self):
with tempfile.TemporaryDirectory() as directory:
directory, src_directory, docs_directory = self._prepare(directory)
(docs_directory / 'test_dir').mkdir()
documentation_generator = PythonDocumentationGenerator(
src_directory, docs_directory
)
with pytest.raises(DirectoryNotEmptyError) as exc_info:
documentation_generator.generate_documentation()
assert exc_info.value.filename == str(docs_directory)
def test_nothing_force(self):
with tempfile.TemporaryDirectory() as directory:
directory, src_directory, docs_directory = self._prepare(directory)
documentation_generator = PythonDocumentationGenerator(
src_directory, docs_directory
)
documentation_generator.generate_documentation(True)
def test_nothing_not_force(self):
with tempfile.TemporaryDirectory() as directory:
directory, src_directory, docs_directory = self._prepare(directory)
documentation_generator = PythonDocumentationGenerator(
src_directory, docs_directory
)
documentation_generator.generate_documentation(True)
@@ -7,3 +7,33 @@
```python
func()
```
## Function `func2`
### Function signature
```python
func2(a: int, b: int = 42, c=42, d=42)
```
### Parameters
| Parameter | Type | Kind | Default value | Description |
| --- | --- | --- | --- | --- |
| `a` | `int` | normal | -- | -- |
| `b` | `int` | normal | `42` | -- |
| `c` | `int` | normal | `42` | -- |
| `d` | -- | normal | `42` | -- |
### Docstring
:param c:
:type c: int
@@ -0,0 +1,8 @@
def func(): ...
def func2(a: int, b: int = 42, c=42, d=42):
"""
:param c:
:type c: int
"""
@@ -125,12 +125,12 @@ Returns all users.
##### Method signature
```python
list_all(self) -> List[User]
list_all(self) -> list[User]
```
##### Returns
Return type: `List[User]`
Return type: `list[User]`
##### Parameters
@@ -1,5 +1,4 @@
from dataclasses import dataclass
from typing import Optional
@dataclass
@@ -11,4 +10,4 @@ class User:
id: str
name: str
email: str
age: Optional[int] = None
age: int | None = None
@@ -1,6 +1,6 @@
from .exceptions import InvalidEmailError, UserNotFoundError
from .models import User
from .storage import InMemoryUserStorage
from .exceptions import UserNotFoundError, InvalidEmailError
from .utils import is_valid_email, normalize_name
@@ -1,4 +1,3 @@
from typing import Dict, List
from .models import User
@@ -9,7 +8,7 @@ class InMemoryUserStorage:
"""
def __init__(self):
self._users: Dict[str, User] = {}
self._users: dict[str, User] = {}
def add(self, user: User) -> None:
"""Adds a user."""
@@ -23,6 +22,6 @@ class InMemoryUserStorage:
"""Deletes a user."""
del self._users[user_id]
def list_all(self) -> List[User]:
def list_all(self) -> list[User]:
"""Returns all users."""
return list(self._users.values())
@@ -241,6 +241,36 @@ def test_PythonModuleDocumentationGenerator_exceptions(
A test module.
## Function `fn`
### Function signature
```python
fn(a: int, b: int = 42, c=42, d=42)
```
### Parameters
| Parameter | Type | Kind | Default value | Description |
| --- | --- | --- | --- | --- |
| `a` | `int` | normal | -- | -- |
| `b` | `int` | normal | `42` | -- |
| `c` | `int` | normal | `42` | -- |
| `d` | -- | normal | `42` | -- |
### Docstring
:param c:
:type c: int
## Function `add`
Adds two numbers.
@@ -422,6 +452,36 @@ A dog.""",
A test module.
## Function `fn`
### Function signature
```python
fn(a: int, b: int = 42, c=42, d=42)
```
### Parameters
| Parameter | Type | Kind | Default value | Description |
| --- | --- | --- | --- | --- |
| `a` | `int` | normal | -- | -- |
| `b` | `int` | normal | `42` | -- |
| `c` | `int` | normal | `42` | -- |
| `d` | -- | normal | `42` | -- |
### Docstring
:param c:
:type c: int
## Function `add`
Adds two numbers.
@@ -604,6 +664,35 @@ A dog.""",
A test module.
## Function `fn`
### Function signature
```python
fn(a: int, b: int = 42, c=42, d=42)
```
### Parameters
| Parameter | Type | Kind | Default value | Description |
| --- | --- | --- | --- | --- |
| `a` | `int` | normal | -- | -- |
| `b` | `int` | normal | `42` | -- |
| `c` | `int` | normal | `42` | -- |
| `d` | -- | normal | `42` | -- |
<details><summary><h3 style="display:inline">Docstring</h3></summary>"""
""":param c:
:type c: int</details>
## Function `add`
Adds two numbers.
@@ -782,6 +871,68 @@ Return type: `None`
A test module.
## Function `fn`
### Function signature
```python
fn(a: int, b: int = 42, c=42, d=42)
```
### Parameters
- Parameter: `a`
Type: `int`
Kind: normal
Default value: --
Description: --
- Parameter: `b`
Type: `int`
Kind: normal
Default value: `42`
Description: --
- Parameter: `c`
Type: `int`
Kind: normal
Default value: `42`
Description: --
- Parameter: `d`
Type: --
Kind: normal
Default value: `42`
Description: --
<details><summary><h3 style="display:inline">Docstring</h3></summary>"""
""":param c:
:type c: int</details>
## Function `add`
Adds two numbers.
@@ -1001,6 +1152,69 @@ Return type: `None`
A test module.
## Function `fn`
### Function signature
```python
fn(a: int, b: int = 42, c=42, d=42)
```
### Parameters
- Parameter: `a`
Type: `int`
Kind: normal
Default value: --
Description: --
- Parameter: `b`
Type: `int`
Kind: normal
Default value: `42`
Description: --
- Parameter: `c`
Type: `int`
Kind: normal
Default value: `42`
Description: --
- Parameter: `d`
Type: --
Kind: normal
Default value: `42`
Description: --
### Docstring
:param c:
:type c: int
## Function `add`
Adds two numbers.
@@ -1210,7 +1424,7 @@ A dog.""",
),
],
)
def test_PythonModuleDocumentationGenerator_exceptions(
def test_PythonModuleDocumentationGenerator_generate_documentation(
module_documentation_generator,
expected,
):
@@ -292,22 +292,25 @@ def test_PythonDocumentationGenerator_collect_modules(
None,
[
(
"""pytest.mark.parametrize('python_documentation_gener"""
"""ator,expected', [(PythonDocumentationGenerator(path"""
"""lib.Path('tests/unit/core/python/_core/test_project"""
"""_dirs/pdir_1'), pathlib.Path('tests/unit/core/pytho"""
"""n/_core/test_project_dirs/pdir_1/docs')), []), (Pyt"""
"""honDocumentationGenerator(pathlib.Path('tests/unit/"""
"""core/python/_core/test_project_dirs/pdir_2'), pathl"""
"""ib.Path('tests/unit/core/python/_core/test_project_"""
"""dirs/pdir_2/docs')), [PythonPackageNamespace('pkg',"""
""" [PythonModuleNamespace('module')])]), (PythonDocum"""
"""entationGenerator(pathlib.Path('tests/unit/core/pyt"""
"""hon/_core/test_project_dirs/pdir_3'), pathlib.Path("""
"""'tests/unit/core/python/_core/test_project_dirs/pdi"""
"""r_3/docs')), [PythonPackageNamespace('pkg', [Python"""
"""ModuleNamespace(\'module'), PythonPackageNamespace("""
"""\'pkg\', [PythonModuleNamespace(\'module2')])])])])"""
"pytest.mark.parametrize('python_documentatio"
"n_generator,expected', [(PythonDocumentation"
"Generator(pathlib.Path('tests/unit/core/pyth"
"on/_core/test_project_dirs/pdir_1'), pathlib"
".Path('tests/unit/core/python/_core/test_pro"
"ject_dirs/pdir_1/docs')), []), (PythonDocume"
"ntationGenerator(pathlib.Path('tests/unit/co"
"re/python/_core/test_project_dirs/pdir_2'), "
"pathlib.Path('tests/unit/core/python/_core/t"
"est_project_dirs/pdir_2/docs')), [PythonPack"
"ageNamespace('pkg', [PythonModuleNamespace('"
"module')])]), (PythonDocumentationGenerator("
"pathlib.Path('tests/unit/core/python/_core/t"
"est_project_dirs/pdir_3'), pathlib.Path('tes"
'ts/unit/core/python/_core/test_project_dirs/'
"pdir_3/docs')), [PythonPackageNamespace('pkg"
"', [PythonModuleNamespace('module'), Python"
"PackageNamespace('pkg', [PythonModuleNames"
"pace('module2')])])])])"
)
],
),
@@ -341,6 +341,17 @@ from src.jcloud_docsgen.core.python.arguments import (
],
['a: int = 1'],
),
(
[
PythonFunctionArgument(
'a',
PythonArgumentKind.NORMAL,
'1',
None,
),
],
['a=1'],
),
],
)
def test__signature_argument_list(argument_list, expected):
@@ -3,6 +3,13 @@ A test module.
"""
def fn(a: int, b: int = 42, c=42, d=42):
"""
:param c:
:type c: int
"""
def add(a: int | float, b: int | float) -> int | float:
"""
Adds two numbers.
@@ -685,7 +685,7 @@ def argument_list(argument_list: str) -> ast.arguments:
),
(
argument_list(
"a = 1, b = 'a', /, *args, c = None, d = True, **kwargs",
"a=1, b='a', /, *args, c=None, d=True, **kwargs",
),
[
PythonFunctionArgument(
@@ -727,9 +727,7 @@ def argument_list(argument_list: str) -> ast.arguments:
],
),
(
argument_list(
"a, b = 'a', /, *args, c = None, d = True, **kwargs"
),
argument_list("a, b='a', /, *args, c=None, d=True, **kwargs"),
[
PythonFunctionArgument(
'a',
@@ -767,7 +765,7 @@ def argument_list(argument_list: str) -> ast.arguments:
],
),
(
argument_list('a, b , /, *args, c = None, d = True, **kwargs'),
argument_list('a, b , /, *args, c=None, d=True, **kwargs'),
[
PythonFunctionArgument(
'a',
@@ -808,7 +806,7 @@ def argument_list(argument_list: str) -> ast.arguments:
],
),
(
argument_list('a, b , /, *args, c, d = True, **kwargs'),
argument_list('a, b , /, *args, c, d=True, **kwargs'),
[
PythonFunctionArgument(
'a',
@@ -890,7 +888,7 @@ def argument_list(argument_list: str) -> ast.arguments:
],
),
(
argument_list('a, b , /, *args, c = None, d, **kwargs'),
argument_list('a, b , /, *args, c=None, d, **kwargs'),
[
PythonFunctionArgument(
'a',
@@ -931,7 +929,7 @@ def argument_list(argument_list: str) -> ast.arguments:
],
),
(
argument_list('a = 1'),
argument_list('a=1'),
[
PythonFunctionArgument(
'a',
@@ -362,7 +362,7 @@ from src.jcloud_docsgen.exceptions import (
'1',
None,
PythonArgumentStructureError,
'* or ** arguments cannot have default values: *a = 1',
'* or ** arguments cannot have default values: *a=1',
),
(
'a',
@@ -370,7 +370,7 @@ from src.jcloud_docsgen.exceptions import (
'1',
None,
PythonArgumentStructureError,
'* or ** arguments cannot have default values: **a = 1',
'* or ** arguments cannot have default values: **a=1',
),
],
)
@@ -498,7 +498,7 @@ def test_PythonFunctionArgument_asterik(name, kind, annotation):
'1',
None,
),
'a = 1',
'a=1',
),
(
PythonFunctionArgument(
@@ -531,7 +531,7 @@ def test_PythonFunctionArgument_asterik(name, kind, annotation):
'1',
None,
),
'a = 1',
'a=1',
),
(
PythonFunctionArgument(
@@ -567,7 +567,7 @@ def test_PythonFunctionArgument_asterik(name, kind, annotation):
'1',
None,
),
'a = 1',
'a=1',
),
(
PythonFunctionArgument(
@@ -14,7 +14,11 @@
import pytest
from src.jcloud_docsgen.core.python.namespaces import PythonModuleNamespace
from src.jcloud_docsgen.core.python.namespaces import (
PythonModuleNamespace,
PythonNamespace,
PythonPackageNamespace,
)
class StrSubclass(str): ...
@@ -42,6 +46,10 @@ def test_PythonModuleNamespace_name_attribute(namespace, expected_name):
(PythonModuleNamespace('a'), PythonModuleNamespace('b'), False),
(PythonModuleNamespace('0'), PythonModuleNamespace('-0'), False),
(PythonModuleNamespace('1'), PythonModuleNamespace('a'), False),
(PythonModuleNamespace('a'), 'a', False),
(PythonModuleNamespace('a'), 'b', False),
(PythonModuleNamespace('a'), PythonPackageNamespace('a', []), False),
(PythonModuleNamespace('a'), PythonNamespace('a'), False),
],
)
def test_PythonModuleNamespace___eq__(namespace1, namespace2, expected):
@@ -16,6 +16,7 @@ import pytest
from src.jcloud_docsgen.core.python.namespaces import (
PythonModuleNamespace,
PythonNamespace,
PythonPackageNamespace,
)
from src.jcloud_docsgen.exceptions import (
@@ -256,6 +257,26 @@ def test_PythonPackageNamespace_sub_namespace_names(namespace, expected):
PythonPackageNamespace('b', []),
False,
),
(
PythonPackageNamespace('a', []),
'a',
False,
),
(
PythonPackageNamespace('a', []),
'b',
False,
),
(
PythonPackageNamespace('a', []),
PythonModuleNamespace('a'),
False,
),
(
PythonPackageNamespace('a', []),
PythonNamespace('a'),
False,
),
],
)
def test_PythonPackageNamespace___eq__(namespace1, namespace2, expected):