-
-
Notifications
You must be signed in to change notification settings - Fork 229
avoid misparsing references as other types using Pydantic discriminated unions #1216
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
Merged
dbanty
merged 13 commits into
openapi-generators:main
from
nkrishnaswami:use-discriminated-unions-for-references
Mar 15, 2025
Merged
Changes from 6 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
16836e9
Add tests for parsing ambiguous ref unions
nkrishnaswami 3a96f99
Parse ambiguous ref unions as refs
nkrishnaswami 0dd9f85
Fix errors after updating
nkrishnaswami cc4f8dc
Fix linter errors
nkrishnaswami 19898a4
fix: avoid misparsing references as other types using Pydantic discri…
nkrishnaswami 19a1725
Merge branch 'main' into use-discriminated-unions-for-references
nkrishnaswami 5799b25
Incorporate review comments:
ab4c085
Merge branch 'main' into use-discriminated-unions-for-references
f367649
chore: Type checking and formatting
dbanty 485b64e
Update minimum Pydantic version to 2.10
dbanty db1f6b4
Add changeset
dbanty 932abf0
Remove unused line in discriminator
dbanty 54dc8c5
Update pdm.lock
dbanty File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 2 additions & 3 deletions
5
openapi_python_client/schema/openapi_schema_pydantic/responses.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
# If a field may be reference (`Union[Reference, OtherType]`) and the dictionary | ||
# being processed for it contains "$ref", it seems like it should preferentially | ||
# be parsed as a `Reference`[1]. Since the models are defined with | ||
# `extra="allow"`, Pydantic won't guarantee this parse if the dictionary is in | ||
# an unspecified sense a "better match" for `OtherType`[2], e.g., perhaps if it | ||
# has several more fields matching that type versus the single match for `$ref`. | ||
# | ||
# We can use a discriminated union to force parsing these dictionaries as | ||
# `Reference`s. | ||
# | ||
# References: | ||
# [1] https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#reference-object | ||
# [2] https://docs.pydantic.dev/latest/concepts/unions/#smart-mode | ||
import json | ||
from typing import Annotated, TypeVar, Union, get_args, get_origin | ||
|
||
import pytest | ||
from pydantic import TypeAdapter | ||
|
||
from openapi_python_client.schema.openapi_schema_pydantic import ( | ||
Callback, | ||
Example, | ||
Header, | ||
Link, | ||
Parameter, | ||
PathItem, | ||
Reference, | ||
RequestBody, | ||
Response, | ||
Schema, | ||
SecurityScheme, | ||
) | ||
|
||
try: | ||
from openapi_python_client.schema.openapi_schema_pydantic.reference import ReferenceOr | ||
except ImportError: | ||
T = TypeVar("T") | ||
ReferenceOr = Union[Reference, T] | ||
|
||
|
||
def get_example(base_type): | ||
schema = base_type.model_json_schema() | ||
print(json.dumps(schema.get("examples", []), indent=4)) | ||
if "examples" in schema: | ||
return schema["examples"][0] | ||
if "$defs" in schema: | ||
return schema["$defs"][base_type.__name__]["examples"][0] | ||
raise TypeError(f"No example found for {base_type.__name__}") | ||
|
||
|
||
def deannotate_type(t): | ||
while get_origin(t) is Annotated: | ||
t = get_args(t)[0] | ||
return t | ||
|
||
|
||
# The following types occur in various models, so we want to make sure they | ||
# parse properly. They are verified to /fail/ to parse as of commit 3bd12f86. | ||
|
||
@pytest.mark.parametrize(("ref_or_type", "get_example_fn"), [ | ||
(ReferenceOr[Callback], lambda t: {"test1": get_example(PathItem), | ||
"test2": get_example(PathItem)}), | ||
(ReferenceOr[Example], get_example), | ||
(ReferenceOr[Header], get_example), | ||
(ReferenceOr[Link], get_example), | ||
(ReferenceOr[Parameter], get_example), | ||
(ReferenceOr[RequestBody], get_example), | ||
(ReferenceOr[Response], get_example), | ||
(ReferenceOr[Schema], get_example), | ||
(ReferenceOr[SecurityScheme], get_example), | ||
]) | ||
def test_type(ref_or_type, get_example_fn): | ||
base_type = None | ||
print(deannotate_type(ref_or_type)) | ||
dbanty marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for maybe_annotated_type in get_args(deannotate_type(ref_or_type)): | ||
each_type = deannotate_type(maybe_annotated_type) | ||
if each_type is not Reference: | ||
base_type = each_type | ||
break | ||
assert base_type is not None | ||
|
||
example = get_example_fn(base_type) | ||
|
||
parsed = TypeAdapter(ref_or_type).validate_python(example) | ||
assert type(parsed) is get_origin(base_type) or base_type | ||
|
||
example["$ref"] = "ref" | ||
parsed = TypeAdapter(ref_or_type).validate_python(example) | ||
assert type(parsed) is Reference |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.