Skip to content
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

[BUG] [python] Discriminator imports are wrong #16848

Closed
5 tasks done
OliverTetzTT opened this issue Oct 17, 2023 · 1 comment
Closed
5 tasks done

[BUG] [python] Discriminator imports are wrong #16848

OliverTetzTT opened this issue Oct 17, 2023 · 1 comment

Comments

@OliverTetzTT
Copy link
Contributor

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
Description

When generating a python client using the current release of the openapi generator, the discriminator class imports are wrong.

(To get to this point, I already fixed the circular import by moving the petstore.models.pet import Pet line to the top of the import block in __init__.py files in the apiclient and models packages. (Can be automated by isort's force_to_top option. And is therefore currently fixable in an automated way. So not perfect but fixable for now))

pytest results in:

api-clients/testing/test/test_cat.py:None (api-clients/testing/test/test_cat.py)
ImportError while importing test module '***\api-clients\testing\test\test_cat.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
***\pypoetry\Cache\virtualenvs\petstore-NEbAbLrb-py3.11\Lib\site-packages\_pytest\python.py:617: in _importtestmodule
    mod = import_path(self.path, mode=importmode, root=self.config.rootpath)
***\pypoetry\Cache\virtualenvs\petstore-NEbAbLrb-py3.11\Lib\site-packages\_pytest\pathlib.py:567: in import_path
    importlib.import_module(module_name)
***\Lib\importlib\__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
<frozen importlib._bootstrap>:1206: in _gcd_import
    ???
<frozen importlib._bootstrap>:1178: in _find_and_load
    ???
<frozen importlib._bootstrap>:1149: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:690: in _load_unlocked
    ???
***\Cache\virtualenvs\petstore-NEbAbLrb-py3.11\Lib\site-packages\_pytest\assertion\rewrite.py:178: in exec_module
    exec(co, module.__dict__)
test_cat.py:18: in <module>
    from petstore.models.cat import Cat  # noqa: E501
..\petstore\__init__.py:20: in <module>
    from petstore.api.default_api import DefaultApi
..\petstore\api\__init__.py:4: in <module>
    from petstore.api.default_api import DefaultApi
..\petstore\api\default_api.py:22: in <module>
    from petstore.models.catkiller import Catkiller
..\petstore\models\__init__.py:17: in <module>
    from petstore.models.pet import Pet
..\petstore\models\pet.py:106: in <module>
    from petstore.models.dog import dog
E   ModuleNotFoundError: No module named 'petstore.models.dog'

This is because the generated file for Pet looks like this (shortened):

# shortened header for bug ticket

class Pet(BaseModel):
    """
    Pet
    """
    pet_type: StrictStr = Field(alias="petType")
    __properties: ClassVar[List[str]] = ["petType"]

    model_config = {
        "populate_by_name": True,
        "validate_assignment": True
    }


    # JSON field name that stores the object type
    __discriminator_property_name: ClassVar[List[str]] = 'petType'

    # discriminator mappings
    __discriminator_value_class_map: ClassVar[Dict[str, str]] = {
        'dog': 'Catkiller','Cat': 'Cat','Lizard': 'Lizard'   # <--- here the mapping states that dog should be mapped to Catkiller
    }

# shortened class for bug ticket

from petstore.models.cat import Cat
from petstore.models.dog import dog  # <--- this line is the problem. It should import Catkiller instead of Dog here
from petstore.models.lizard import Lizard
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    # TODO: pydantic v2
    # Pet.model_rebuild()
    pass

The problem line at the bottom should be:

from petstore.models.catkiller import Catkiller

After that all tests are successful

openapi-generator version
docker run --rm -v .:/local openapitools/openapi-generator-cli --version                                                                                                                                                     
openapi-generator-cli 7.1.0-SNAPSHOT
  commit : 1fc0cec
  built  : -999999999-01-01T00:00:00+18:00
  source : https://github.com/openapitools/openapi-generator
  docs   : https://openapi-generator.tech/
OpenAPI declaration file content
openapi: 3.0.0
info:
  title: Test Inheritance
  version: 1.0.0
servers:
  - url: /
paths:
  /test:
    get:
      operationId: test
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Catkiller"
        required: true
      responses:
        "200":
          description: Success
        default:
          description: Unexpected Error

components:
  schemas:
    Pet:
      type: object
      required:
        - petType
      properties:
        petType:
          type: string
      discriminator:
        propertyName: petType
        mapping:
          dog: '#/components/schemas/Catkiller'
    Cat:
      allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            name:
              type: string
    Catkiller:
      allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            bark:
              type: string
    Lizard:
      allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            lovesRocks:
              type: boolean
Generation Details
docker run --rm -v .:/local openapitools/openapi-generator-cli generate -i /local/testing.yaml -g python -o /local/api-clients/testing --additional-properties=packageName=petstore
Steps to reproduce
  1. Generate python client
  2. CD to folder of client
  3. Run poetry install
  4. Fix circle import by moving Pet import to the top in __init__.py files
  5. run pytest .
Related issues/PRs

I could not find one.

@OliverTetzTT
Copy link
Contributor Author

This was resolved in the linked Pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant