diff --git a/README.md b/README.md index bdaf6bfce..ffea3183b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/end_to_end_tests/functional_tests/generated_code_execution/test_conflicting_module_names.py b/end_to_end_tests/functional_tests/generated_code_execution/test_conflicting_module_names.py new file mode 100644 index 000000000..af1b9b537 --- /dev/null +++ b/end_to_end_tests/functional_tests/generated_code_execution/test_conflicting_module_names.py @@ -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")), + ) diff --git a/openapi_python_client/parser/properties/enum_property.py b/openapi_python_client/parser/properties/enum_property.py index 573d5f0d8..2b0f2d255 100644 --- a/openapi_python_client/parser/properties/enum_property.py +++ b/openapi_python_client/parser/properties/enum_property.py @@ -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 @@ -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) diff --git a/openapi_python_client/parser/properties/literal_enum_property.py b/openapi_python_client/parser/properties/literal_enum_property.py index 0388fe04e..5b71bf690 100644 --- a/openapi_python_client/parser/properties/literal_enum_property.py +++ b/openapi_python_client/parser/properties/literal_enum_property.py @@ -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 @@ -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: diff --git a/openapi_python_client/parser/properties/model_property.py b/openapi_python_client/parser/properties/model_property.py index 3f6548e77..43807ba19 100644 --- a/openapi_python_client/parser/properties/model_property.py +++ b/openapi_python_client/parser/properties/model_property.py @@ -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 @@ -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 diff --git a/openapi_python_client/parser/properties/schemas.py b/openapi_python_client/parser/properties/schemas.py index 49e278437..d172c21bc 100644 --- a/openapi_python_client/parser/properties/schemas.py +++ b/openapi_python_client/parser/properties/schemas.py @@ -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 @@ -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: diff --git a/tests/test_parser/test_properties/test_schemas.py b/tests/test_parser/test_properties/test_schemas.py index 8433404d2..89c01decf 100644 --- a/tests/test_parser/test_properties/test_schemas.py +++ b/tests/test_parser/test_properties/test_schemas.py @@ -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" @@ -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"