Skip to content
Open
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
6 changes: 4 additions & 2 deletions python_client_generator/generate_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def get_references(model: Dict[str, Any]) -> List[str]:
union_keys = list(set(["allOf", "anyOf", "oneOf"]) & set(model.keys()))
if union_keys:
return _get_schema_references(model)
else:
elif "properties" in model:
# Must have properties
for p_schema in model["properties"].values():
refs += _get_schema_references(p_schema)
Expand All @@ -109,7 +109,7 @@ def get_fields(schema: Dict[str, Any]) -> List[Dict[str, Any]]:
if union_keys:
# Handle union cases by creating a __root__ defined model
return [{"name": "__root__", "type": resolve_type(schema)}]
else:
elif "properties" in schema:
return [
{
"name": k,
Expand All @@ -119,6 +119,8 @@ def get_fields(schema: Dict[str, Any]) -> List[Dict[str, Any]]:
}
for k, v in schema["properties"].items()
]
else:
return []


def _strip_nonexistant_refs(objects: List[Dict[str, Any]]) -> None:
Expand Down
21 changes: 17 additions & 4 deletions python_client_generator/generate_pyproject.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os

from pathlib import Path
from typing import Any, Dict
from typing import Any, Dict, Optional

import chevron

Expand All @@ -10,14 +10,27 @@
templates_path = dir_path / "templates"


def generate_pyproject(swagger: Dict[str, Any], out_file: Path, project_name: str) -> None:
def generate_pyproject(
swagger: Dict[str, Any],
out_file: Path,
project_name: str,
project_path_first: str,
author_name: Optional[str] = None,
author_email: Optional[str] = None,
) -> None:
"""
Generate `pyproject.toml` file.
"""
version = swagger["info"]["version"]
data = {
"version": swagger["info"]["version"],
"project_name": project_name,
"project_path_first": project_path_first,
"has_author": bool(author_name or author_email),
"author": [author_name, author_email],
}

with open(templates_path / "pyproject.toml.mustache", "r") as f:
toml_str = chevron.render(f, {"version": version, "project_name": project_name})
toml_str = chevron.render(f, data)

with open(out_file, "w+") as f:
f.write(toml_str)
18 changes: 16 additions & 2 deletions python_client_generator/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,18 @@ def main() -> None:
parser.add_argument("--open-api", type=str)
parser.add_argument("--package-name", type=str)
parser.add_argument("--project-name", type=str)
parser.add_argument("--author-name", type=str, required=False)
parser.add_argument("--author-email", type=str, required=False)
parser.add_argument("--outdir", type=str, default="clients/")
parser.add_argument("--group-by-tags", action="store_true")
parser.add_argument("--sync", action="store_true")

args = parser.parse_args()

if os.sep in args.package_name or (os.altsep is not None and os.altsep in args.package_name):
raise ValueError("package-name must not contain directory separators")
if "-" in args.package_name:
raise ValueError("package-name must not contain dashes")
with open(args.open_api, "r") as f:
swagger = json.load(f)

Expand All @@ -43,10 +49,18 @@ def main() -> None:
path = Path(args.outdir)
path.mkdir(parents=True, exist_ok=True)

generate_pyproject(dereferenced_swagger, path / "pyproject.toml", args.project_name)
project_path_first = args.package_name.split(".", maxsplit=1)[0]
generate_pyproject(
dereferenced_swagger,
path / "pyproject.toml",
args.project_name,
project_path_first,
args.author_name,
args.author_email,
)

# Create package directory
package_path = path / Path(args.package_name)
package_path = path / Path(args.package_name.replace(".", os.sep))
package_path.mkdir(parents=True, exist_ok=True)

# Generate package files
Expand Down
28 changes: 16 additions & 12 deletions python_client_generator/templates/pyproject.toml.mustache
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
[tool.poetry]
[project]
name = "{{project_name}}"
version = "{{version}}"
description = "Autogenerated httpx async client for {{project_name}}"
authors = ["Autogenerated Client <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.7"
httpx = ">=0.22, <1"
pydantic = "^1"

[tool.poetry.scripts]
poetry = "poetry.console:main"
{{#has_author}}
authors = [
{ {{#author.0}}name = "{{author.0}}"{{#author.1}}, {{/author.1}}{{/author.0}}{{#author.1}}email = "{{author.1}}"{{/author.1}} },
]
{{/has_author}}
requires-python = ">=3.8"
dependencies = [
"httpx>=0.22,<1",
"pydantic>=2,<3",
]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["{{project_path_first}}"]
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,14 @@ class FooEnum(str, Enum):
OPTION_2 = "option_2"


class EmptyObject(BaseModel):
pass


class Bar(BaseModel):
field_1: str
field_2: Optional[bool]
field_3: Optional[EmptyObject]


class Document(BaseModel):
Expand Down
23 changes: 11 additions & 12 deletions tests/expected/fastapi_app_client/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
[tool.poetry]
[project]
name = "fastapi-project"
version = "0.1.0"
description = "Autogenerated httpx async client for fastapi-project"
authors = ["Autogenerated Client <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.7"
httpx = ">=0.22, <1"
pydantic = "^1"

[tool.poetry.scripts]
poetry = "poetry.console:main"
requires-python = ">=3.8"
dependencies = [
"httpx>=0.22,<1",
"pydantic>=2,<3",
]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["fastapi_project"]
26 changes: 14 additions & 12 deletions tests/expected/swagger_petstore_client/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
[tool.poetry]
[project]
name = "test-project"
version = "1.0.11"
description = "Autogenerated httpx async client for test-project"
authors = ["Autogenerated Client <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.7"
httpx = ">=0.22, <1"
pydantic = "^1"

[tool.poetry.scripts]
poetry = "poetry.console:main"
authors = [
{ name = "Test User", email = "[email protected]" },
]
requires-python = ">=3.8"
dependencies = [
"httpx>=0.22,<1",
"pydantic>=2,<3",
]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["test_project"]
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,11 @@ class ApiResponse(BaseModel):
message: Optional[str]


class EmptyObjectWithEmptyProperties(BaseModel):
pass


class EmptyObjectWithNoProperties(BaseModel):
pass


5 changes: 5 additions & 0 deletions tests/inputs/fastapi_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,14 @@ class FooEnum(str, Enum):
OPTION_2 = "option_2"


class EmptyObject(BaseModel):
pass


class Bar(BaseModel):
field_1: str
field_2: Optional[bool]
field_3: Optional[EmptyObject]


class Foo(BaseModel):
Expand Down
7 changes: 7 additions & 0 deletions tests/inputs/swagger-petstore.json
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,13 @@
"xml": {
"name": "##default"
}
},
"EmptyObjectWithEmptyProperties": {
"type": "object",
"properties": {}
},
"EmptyObjectWithNoProperties": {
"type": "object"
}
},
"requestBodies": {
Expand Down
4 changes: 2 additions & 2 deletions tests/test_fastapi_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

from tests.utils import does_not_raise

from .expected.fastapi_app_client.apis import Api as FastApiAppClient
from .expected.fastapi_app_client.models import Document, Foo, PaginatedFoo
from .expected.fastapi_app_client.fastapi_project.apis import Api as FastApiAppClient
from .expected.fastapi_app_client.fastapi_project.models import Document, Foo, PaginatedFoo


client_base_url = "https://domain.tld"
Expand Down
27 changes: 23 additions & 4 deletions tests/test_fastapi_client_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,44 @@

def test_models(fastapi_app_openapi: Dict[str, Any], tmp_path: Path) -> None:
generate_models(fastapi_app_openapi, tmp_path / "models.py")
assert filecmp.cmp(EXPECTED_PATH / "models.py", tmp_path / "models.py", shallow=False) is True
assert (
filecmp.cmp(
EXPECTED_PATH / "fastapi_project" / "models.py",
tmp_path / "models.py",
shallow=False,
)
is True
)


def test_base_client(tmp_path: Path) -> None:
generate_base_client(tmp_path / "base_client.py", sync=False)
assert (
filecmp.cmp(EXPECTED_PATH / "base_client.py", tmp_path / "base_client.py", shallow=False)
filecmp.cmp(
EXPECTED_PATH / "fastapi_project" / "base_client.py",
tmp_path / "base_client.py",
shallow=False,
)
is True
)


def test_apis(fastapi_app_openapi: Dict[str, Any], tmp_path: Path) -> None:
generate_apis(fastapi_app_openapi, tmp_path / "apis.py", group_by_tags=False, sync=False)
assert filecmp.cmp(EXPECTED_PATH / "apis.py", tmp_path / "apis.py", shallow=False) is True
assert (
filecmp.cmp(
EXPECTED_PATH / "fastapi_project" / "apis.py", tmp_path / "apis.py", shallow=False
)
is True
)


def test_pyproject(fastapi_app_openapi: Dict[str, Any], tmp_path: Path) -> None:
generate_pyproject(
fastapi_app_openapi, tmp_path / "pyproject.toml", project_name="fastapi-project"
fastapi_app_openapi,
tmp_path / "pyproject.toml",
project_name="fastapi-project",
project_path_first="fastapi_project",
)
assert (
filecmp.cmp(EXPECTED_PATH / "pyproject.toml", tmp_path / "pyproject.toml", shallow=False)
Expand Down
31 changes: 27 additions & 4 deletions tests/test_swagger_file_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,48 @@

def test_models(swagger_petstore_openapi: Dict[str, Any], tmp_path: Path) -> None:
generate_models(swagger_petstore_openapi, tmp_path / "models.py")
assert filecmp.cmp(EXPECTED_PATH / "models.py", tmp_path / "models.py", shallow=False) is True
assert (
filecmp.cmp(
EXPECTED_PATH / "test_project" / "models.py",
tmp_path / "models.py",
shallow=False,
)
is True
)


def test_base_client(tmp_path: Path) -> None:
generate_base_client(tmp_path / "base_client.py", sync=False)
assert (
filecmp.cmp(EXPECTED_PATH / "base_client.py", tmp_path / "base_client.py", shallow=False)
filecmp.cmp(
EXPECTED_PATH / "test_project" / "base_client.py",
tmp_path / "base_client.py",
shallow=False,
)
is True
)


def test_apis(swagger_petstore_openapi: Dict[str, Any], tmp_path: Path) -> None:
generate_apis(swagger_petstore_openapi, tmp_path / "apis.py", group_by_tags=False, sync=False)
assert filecmp.cmp(EXPECTED_PATH / "apis.py", tmp_path / "apis.py", shallow=False) is True
assert (
filecmp.cmp(
EXPECTED_PATH / "test_project" / "apis.py",
tmp_path / "apis.py",
shallow=False,
)
is True
)


def test_pyproject(swagger_petstore_openapi: Dict[str, Any], tmp_path: Path) -> None:
generate_pyproject(
swagger_petstore_openapi, tmp_path / "pyproject.toml", project_name="test-project"
swagger_petstore_openapi,
tmp_path / "pyproject.toml",
project_name="test-project",
project_path_first="test_project",
author_name="Test User",
author_email="[email protected]",
)
assert (
filecmp.cmp(EXPECTED_PATH / "pyproject.toml", tmp_path / "pyproject.toml", shallow=False)
Expand Down