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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ class_overrides:

The easiest way to find what needs to be overridden is probably to generate your client and go look at everything in the `models` folder.

Model and enum modules are named after their class names, so two schemas whose class names only differ by
capitalization or punctuation would end up in the same module (for example, `VLAN` and `Vlan` would both be generated
into `vlan.py`). The conflicting class is generated into a module with a numeric suffix instead (such as `vlan_1.py`)
and a warning is emitted. You can use `class_overrides` to choose a more meaningful module name in that case.

### docstrings_on_attributes

By default, when `openapi-python-client` generates a model class, it includes a list of attributes and their
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from end_to_end_tests.functional_tests.helpers import (
assert_model_decode_encode,
with_generated_client_fixture,
with_generated_code_imports,
)


@with_generated_client_fixture(
"""
components:
schemas:
VLAN:
type: object
properties:
vlanId: {"type": "integer"}
required: ["vlanId"]
Vlan:
type: object
properties:
name: {"type": "string"}
required: ["name"]
Container:
type: object
properties:
upper: {"$ref": "#/components/schemas/VLAN"}
lower: {"$ref": "#/components/schemas/Vlan"}
required: ["upper", "lower"]
"""
)
@with_generated_code_imports(
".models.VLAN",
".models.Vlan",
".models.Container",
)
class TestConflictingModuleNames:
def test_both_models_are_generated(self, VLAN, Vlan, Container):
assert_model_decode_encode(VLAN, {"vlanId": 1}, VLAN(vlan_id=1))
assert_model_decode_encode(Vlan, {"name": "a"}, Vlan(name="a"))
assert_model_decode_encode(
Container,
{"upper": {"vlanId": 1}, "lower": {"name": "a"}},
Container(upper=VLAN(vlan_id=1), lower=Vlan(name="a")),
)
3 changes: 2 additions & 1 deletion openapi_python_client/parser/properties/enum_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from ..errors import PropertyError
from .none import NoneProperty
from .protocol import PropertyProtocol, Value, convert_example
from .schemas import Class, Schemas
from .schemas import Class, Schemas, ensure_unique_module_name
from .union import UnionProperty

ValueType = str | int
Expand Down Expand Up @@ -119,6 +119,7 @@ def build( # noqa: PLR0911
if parent_name:
class_name = f"{strings.pascal_case(parent_name)}{strings.pascal_case(class_name)}"
class_info = Class.from_string(string=class_name, config=config)
class_info = ensure_unique_module_name(class_info=class_info, schemas=schemas, config=config)
var_names = data.model_extra.get("x-enum-varnames", []) if data.model_extra else []
values = EnumProperty.values_from_list(value_list, class_info, var_names)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from ..errors import PropertyError
from .none import NoneProperty
from .protocol import PropertyProtocol, Value, convert_example
from .schemas import Class, Schemas
from .schemas import Class, Schemas, ensure_unique_module_name
from .union import UnionProperty

ValueType = str | int
Expand Down Expand Up @@ -118,6 +118,7 @@ def build( # noqa: PLR0911
if parent_name:
class_name = f"{strings.pascal_case(parent_name)}{strings.pascal_case(class_name)}"
class_info = Class.from_string(string=class_name, config=config)
class_info = ensure_unique_module_name(class_info=class_info, schemas=schemas, config=config)
values: set[str | int] = set(value_list)

if class_info.name in schemas.classes_by_name:
Expand Down
3 changes: 2 additions & 1 deletion openapi_python_client/parser/properties/model_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from ..errors import ParseError, PropertyError
from .any import AnyProperty
from .protocol import PropertyProtocol, Value, convert_example
from .schemas import Class, ReferencePath, Schemas, parse_reference_path
from .schemas import Class, ReferencePath, Schemas, ensure_unique_module_name, parse_reference_path


@define
Expand Down Expand Up @@ -75,6 +75,7 @@ def build(
else:
class_string = title
class_info = Class.from_string(string=class_string, config=config)
class_info = ensure_unique_module_name(class_info=class_info, schemas=schemas, config=config)
model_roots = {*roots, class_info.name}
required_properties: list[Property] | None = None
optional_properties: list[Property] | None = None
Expand Down
45 changes: 45 additions & 0 deletions openapi_python_client/parser/properties/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ class Schemas:
classes_by_name: dict[ClassName, Property] = field(factory=dict)
models_to_process: list[ModelProperty] = field(factory=list)
errors: list[ParseError] = field(factory=list)
# Module names of the models and enums generated so far, see `ensure_unique_module_name`.
used_module_names: set[str] = field(factory=set)

def add_dependencies(self, ref_path: ReferencePath, roots: set[ReferencePath | ClassName]) -> None:
"""Record new dependencies on the given ReferencePath
Expand All @@ -102,6 +104,49 @@ def add_dependencies(self, ref_path: ReferencePath, roots: set[ReferencePath | C
self.dependencies[ref_path].update(roots)


def ensure_unique_module_name(*, class_info: Class, schemas: Schemas, config: Config) -> Class:
"""Give a class a module name that no other schema in this document is using.

Different class names can be turned into the same module name, since module names are snake_case versions of
class names (`VLAN` and `Vlan` both become `vlan`). Without this, both classes would be generated into the same
module, where the second one silently overwrites the first one and the `models` package fails to import.

Args:
class_info: The class for which a module name is needed.
schemas: Existing Schemas which have already been processed (to check module name conflicts).
config: Config data for this run of the generator, used for renaming.

Returns:
Either `class_info` unchanged, or a copy of it with a unique module name.
"""
if class_info.name in schemas.classes_by_name:
# Classes with the same name conflict in a more fundamental way, which the callers already report;
# renaming their module would not help and would make the error messages harder to understand.
return class_info

used_module_names = schemas.used_module_names
module_name = class_info.module_name
if module_name not in used_module_names:
used_module_names.add(module_name)
return class_info

suffix = 1
while f"{module_name}_{suffix}" in used_module_names:
suffix += 1
new_module_name = PythonIdentifier(f"{module_name}_{suffix}", config.field_prefix)
used_module_names.add(new_module_name)
schemas.errors.append(
ParseError(
header="Renamed a conflicting module",
detail=(
f"The module name `{module_name}` is already used by another schema, so `{class_info.name}` "
f"will be generated in `{new_module_name}.py` instead of overwriting it."
),
)
)
return evolve(class_info, module_name=new_module_name)


def update_schemas_with_data(
*, ref_path: ReferencePath, data: oai.Schema, schemas: Schemas, config: Config
) -> Schemas | PropertyError:
Expand Down
63 changes: 62 additions & 1 deletion tests/test_parser/test_properties/test_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
from openapi_python_client.parser.properties import Class, Parameters
from openapi_python_client.parser.properties.schemas import (
ReferencePath,
Schemas,
ensure_unique_module_name,
parameter_from_data,
parameter_from_reference,
)
from openapi_python_client.schema import Parameter, ParameterLocation, Reference, Schema
from openapi_python_client.schema.ref import Ref
from openapi_python_client.schema.untrusted_string import UntrustedString
from openapi_python_client.strings import ClassName
from openapi_python_client.strings import ClassName, PythonIdentifier

MODULE_NAME = "openapi_python_client.parser.properties.schemas"

Expand Down Expand Up @@ -106,3 +108,62 @@ def test_returns_reference_from_registry(self):
param_by_ref = Reference.model_construct(ref=Ref("#/components/parameters/a_param"))
param_or_error = parameter_from_reference(param=param_by_ref, parameters=params)
assert param_or_error == existing_param


class TestEnsureUniqueModuleName:
def test_keeps_module_name_when_there_is_no_conflict(self, config):
class_info = Class.from_string(string="/components/schemas/PingResponse", config=config)
schemas = Schemas(used_module_names={"other_model"})

result = ensure_unique_module_name(class_info=class_info, schemas=schemas, config=config)

assert result is class_info
assert schemas.used_module_names == {"other_model", "ping_response"}
assert schemas.errors == []

def test_keeps_module_name_when_the_class_name_already_exists(self, config, model_property_factory):
existing = model_property_factory(
class_info=Class(name=ClassName(UntrustedString("Vlan"), ""), module_name=PythonIdentifier("vlan", ""))
)
schemas = Schemas(
classes_by_name={existing.class_info.name: existing}, used_module_names={existing.class_info.module_name}
)
class_info = Class.from_string(string="/components/schemas/Vlan", config=config)

result = ensure_unique_module_name(class_info=class_info, schemas=schemas, config=config)

assert result is class_info
assert schemas.errors == []

def test_renames_a_conflicting_module_name(self, config, model_property_factory):
existing = model_property_factory(
class_info=Class(name=ClassName(UntrustedString("VLAN"), ""), module_name=PythonIdentifier("vlan", ""))
)
schemas = Schemas(
classes_by_name={existing.class_info.name: existing}, used_module_names={existing.class_info.module_name}
)
class_info = Class.from_string(string="/components/schemas/Vlan", config=config)

result = ensure_unique_module_name(class_info=class_info, schemas=schemas, config=config)

assert result.name == "Vlan"
assert result.module_name == "vlan_1"
assert len(schemas.errors) == 1
assert "will be generated in `vlan_1.py`" in schemas.errors[0].detail

def test_keeps_looking_until_it_finds_an_unused_suffix(self, config, model_property_factory):
class_infos = (
Class(name=ClassName(UntrustedString("VLAN"), ""), module_name=PythonIdentifier("vlan", "")),
Class(name=ClassName(UntrustedString("Vlan1"), ""), module_name=PythonIdentifier("vlan_1", "")),
)
schemas = Schemas(
classes_by_name={
class_info.name: model_property_factory(class_info=class_info) for class_info in class_infos
},
used_module_names={class_info.module_name for class_info in class_infos},
)
class_info = Class.from_string(string="/components/schemas/Vlan", config=config)

result = ensure_unique_module_name(class_info=class_info, schemas=schemas, config=config)

assert result.module_name == "vlan_2"