openapi-generators / openapi-generators/openapi-python-client

Client generation error when property names differ only by underscore prefix / suffix

Abierto
#602 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

🐞bug 🥚breaking
Lenguaje dominante
Python
Estrellas
2k
Forks
293
Merge medio
34 min
PR fusionados (30 d)
1

Descripción

Originally predicted in https://github.com/openapi-generators/openapi-python-client/issues/383#issuecomment-830839559

Since re.findall(rf"[^{DELIMITERS}]+", value) trims prefix and suffix _ characters while generating python property identifiers, 2+ schema properties on a single model that differ only by such underscores causes CLI generate and update commands to fail.

Given it would be problematic to carry through those untrimmed identifiers due to the semantic meaning of prefix and suffix _ on identifiers in python, it makes sense to have a fallback value to use like a title property or a configurable prefix.

Resulting error:

$ openapi-python-client generate --path schema-underscore-collision.yaml --fail-on-warning

Generating schema-underscore-collision-client
Error(s) encountered while generating, client was not created

black failed

reformatted schema_underscore_collision_client/api/__init__.py
reformatted schema_underscore_collision_client/__init__.py
reformatted schema_underscore_collision_client/types.py
error: cannot format schema_underscore_collision_client/models/get_response_200.py: cannot use --safe with this file; failed to parse source file AST: keyword argument repeated (<unknown>, line 55)
This could be caused by running Black with an older Python version that does not support new syntax used in your source file.
reformatted schema_underscore_collision_client/client.py
reformatted schema_underscore_collision_client/api/default/get.py

Oh no! 💥 💔 💥
5 files reformatted, 2 files left unchanged, 1 file failed to reformat.

Using an example schema-underscore-collision.yaml:

openapi: 3.0.2
info:
  title: schema-underscore-collision 
  version: 1.0.0
paths:
  /:
    get:
      description: 
      responses:
        '200':
          description: test
          content:
            application/json:
              schema:
                type: object
                properties:
                  _a: {}
                  a: {}
                  a_: {}

The problematic schema_underscore_collision_client/models/get_response_200.py file, reported error is in the from_dict method but to_dict also suffers from the ambiguity:

from typing import Any, BinaryIO, Dict, List, Optional, TextIO, Tuple, Type, TypeVar, Union

import attr

from ..types import UNSET, Unset

T = TypeVar("T", bound="GetResponse200")

@attr.s(auto_attribs=True)
class GetResponse200:
    """
    Attributes:
        a (Union[Unset, Any]):
        a (Union[Unset, Any]):
        a (Union[Unset, Any]):
    """

    a: Union[Unset, Any] = UNSET
    a: Union[Unset, Any] = UNSET
    a: Union[Unset, Any] = UNSET
    additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)


    def to_dict(self) -> Dict[str, Any]:
        a = self.a
        a = self.a
        a = self.a

        field_dict: Dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update({
        })
        if a is not UNSET:
            field_dict["_a"] = a
        if a is not UNSET:
            field_dict["a"] = a
        if a is not UNSET:
            field_dict["a_"] = a

        return field_dict



    @classmethod
    def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
        d = src_dict.copy()
        a = d.pop("_a", UNSET)

        a = d.pop("a", UNSET)

        a = d.pop("a_", UNSET)

        get_response_200 = cls(
            a=a,
            a=a,
            a=a,
        )

        get_response_200.additional_properties = d
        return get_response_200

    @property
    def additional_keys(self) -> List[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties

Versions

  • Python: 3.7.12
  • openapi-python-client: 0.11.1

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza en openapi_python_client/utils.py, alrededor de la llamada findall enlazada, y sigue después los puntos de entrada de la CLI generate y update. Reproduce la colisión con schema-underscore-collision.yaml e inspecciona los métodos to_dict y from_dict del modelo generado. Se considera terminado cuando se generan identificadores de Python válidos y distintos para propiedades como a, a y a, sin campos ni argumentos de palabra clave duplicados.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
openapi, python
Área
api, tooling
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.