Skip to content

feat: Add custom templates for api init files #431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions end_to_end_tests/test_custom_templates/api_init.py.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Custom comment"""
2 changes: 2 additions & 0 deletions end_to_end_tests/test_custom_templates/package_init.py.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
""" Overriden comment """
from .client import AuthenticatedClient, Client
47 changes: 35 additions & 12 deletions end_to_end_tests/test_end_to_end.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,46 @@
import shutil
from filecmp import cmpfiles, dircmp
from filecmp import dircmp
from pathlib import Path
from typing import Dict, Optional
from typing import Dict, List, Optional

import pytest
from typer.testing import CliRunner

from openapi_python_client.cli import app


def _dircmp_recursive(dc: dircmp, *, base_path: Path, dc_info: Dict[str, List[Path]]) -> None:
for k, v in dc_info.items():
v.extend([base_path / f for f in getattr(dc, k)])

for sub_dir, sub_dc in dc.subdirs.items():
_dircmp_recursive(sub_dc, base_path=(base_path / sub_dir), dc_info=dc_info)


def _compare_directories(
record: Path,
test_subject: Path,
expected_differences: Optional[Dict[str, str]] = None,
expected_differences: Optional[Dict[Path, str]] = None,
):
first_printable = record.relative_to(Path.cwd())
second_printable = test_subject.relative_to(Path.cwd())
dc = dircmp(record, test_subject)
missing_files = dc.left_only + dc.right_only
dc_info = {
"left_only": [],
"right_only": [],
"diff_files": [],
"common_funny": [],
}
_dircmp_recursive(dc, base_path=Path(""), dc_info=dc_info)
missing_files = dc_info["left_only"] + dc_info["right_only"]
if missing_files:
pytest.fail(f"{first_printable} or {second_printable} was missing: {missing_files}", pytrace=False)
pytest.fail(
f"{first_printable} or {second_printable} was missing: {list(map(str, missing_files))}",
pytrace=False,
)

expected_differences = expected_differences or {}
_, mismatch, errors = cmpfiles(record, test_subject, dc.common_files, shallow=False)
mismatch = set(mismatch)
mismatch = set(dc_info["diff_files"])

for file_name in mismatch | set(expected_differences.keys()):
if file_name not in expected_differences:
Expand All @@ -36,14 +53,13 @@ def _compare_directories(
mismatch.remove(file_name)

if mismatch:
errors = list(map(str, dc_info["common_funny"]))
mismatch_printable = list(map(str, mismatch))
pytest.fail(
f"{first_printable} and {second_printable} had differing files: {mismatch}, and errors {errors}",
f"{first_printable} and {second_printable} had differing files: {mismatch_printable}, and errors {errors}",
pytrace=False,
)

for sub_path in dc.common_dirs:
_compare_directories(record / sub_path, test_subject / sub_path, expected_differences=expected_differences)


def run_e2e_test(extra_args=None, expected_differences=None):
runner = CliRunner()
Expand Down Expand Up @@ -75,7 +91,14 @@ def test_end_to_end():


def test_custom_templates():
expected_differences = {
"README.md": "my-test-api-client",
"my_test_api_client/__init__.py": (
'""" Overriden comment """\nfrom .client import AuthenticatedClient, Client\n'
),
"my_test_api_client/api/__init__.py": '"""Custom comment"""\n',
}
run_e2e_test(
extra_args=["--custom-template-path=end_to_end_tests/test_custom_templates"],
expected_differences={"README.md": "my-test-api-client"},
expected_differences={Path(k): v for k, v in expected_differences.items()},
)
14 changes: 11 additions & 3 deletions openapi_python_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,14 +241,22 @@ def _build_api(self) -> None:
# Generate endpoints
api_dir = self.package_dir / "api"
api_dir.mkdir()
api_init = api_dir / "__init__.py"
api_init.write_text('""" Contains methods for accessing the API """', encoding=self.file_encoding)
api_init_path = api_dir / "__init__.py"
api_init_template = self.env.get_template("api_init.py.jinja")
api_init_path.write_text(
api_init_template.render(endpoint_collections_by_tag=self.openapi.endpoint_collections_by_tag),
encoding=self.file_encoding,
)

tag_init_template = self.env.get_template("tag_init.py.jinja")
endpoint_template = self.env.get_template("endpoint_module.py.jinja")
for tag, collection in self.openapi.endpoint_collections_by_tag.items():
tag_dir = api_dir / tag
tag_dir.mkdir()
(tag_dir / "__init__.py").touch()
tag_init_path = tag_dir / "__init__.py"
tag_init_path.write_text(
tag_init_template.render(endpoint_collection=collection), encoding=self.file_encoding
)

for endpoint in collection.endpoints:
module_path = tag_dir / f"{snake_case(endpoint.name)}.py"
Expand Down
1 change: 1 addition & 0 deletions openapi_python_client/templates/api_init.py.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
""" Contains methods for accessing the API """
Empty file.