Fix oneOf handling for lists of primitives in model_utils #2880
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.
Context
PR https://github.com/DataDog/datadog-api-spec/pull/4191 introduced a new model
CustomAttributeValuesUnion
with a oneOf schema containing primitive list types:This caused test failures in the generated Python client (#2759):
test_update_case_custom_attribute_returns_not_found_response
The issue was that the generator tried to instantiate primitive types using dict unpacking (
str(**arg, **kwargs)
), which fails with aTypeError
.This is because of two bugs in the
model_utils.j2
template:get_oneof_instance
function: When handling list types in oneOf schemas, the code didn't distinguish between:[str]
,[float]
)That's because checking
cls in PRIMITIVE_TYPES
doesn't catch a list of string for example.It treated all lists the same way, using dict unpacking which only works for complex objects.
composed_model_input_classes
function: Calledissubclass([str], ModelSimple)
which fails withTypeError: issubclass() arg 1 must be a class
when the oneOf schema contains list types like[str]
.Changes
Updated
.generator/src/generator/templates/model_utils.j2
with two fixes:1. Type Guard in
composed_model_input_classes
(lines 73-92)Added a guard to handle list types before calling
issubclass
:This prevents
TypeError: issubclass() arg 1 must be a class
when encountering list types like[str]
or[float]
in oneOf schemas.2. Three-Way List Handling in
get_oneof_instance
(lines 1558-1602)Distinguished between three types of list contents:
[str]
,[float]
): Usevalidate_and_convert_types
to properly handle primitive valuesModelSimple(arg)
Tests
I cherry-picked the changes from this PR onto #2759 and ran the tests (I unskipped the problematic test before)
Related Work
Similar issues were fixed in the Java client: