Skip to content
This repository was archived by the owner on Dec 25, 2024. It is now read-only.

Commit 03e90e0

Browse files
committed
Adds example schema with optional props only and addProps false
1 parent 808d63e commit 03e90e0

10 files changed

Lines changed: 156 additions & 67 deletions

File tree

modules/openapi-json-schema-generator/src/main/java/org/openapijsonschematools/codegen/DefaultCodegen.java

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2294,7 +2294,7 @@ public CodegenSchema fromSchema(Schema p, String sourceJsonPath, String currentJ
22942294
if (currentJsonPath != null) {
22952295
String currentName = currentJsonPath.substring(currentJsonPath.lastIndexOf("/") + 1);
22962296
property.requiredProperties = getRequiredProperties(required, property.properties, property.additionalProperties, requiredAndOptionalProperties, sourceJsonPath, ((Schema<?>) p).getProperties(), currentName);
2297-
property.optionalProperties = getOptionalProperties(property.properties, required, sourceJsonPath, currentName);
2297+
property.optionalProperties = getOptionalProperties(property.properties, required, sourceJsonPath, currentName, property.additionalProperties);
22982298
if ((property.types == null || property.types.contains("object")) && sourceJsonPath != null) {
22992299
boolean addPropsIsFalse = property.additionalProperties != null && property.additionalProperties.isBooleanSchemaFalse;
23002300
// only set mapInputJsonPathPiece when object input is possible
@@ -3334,7 +3334,7 @@ protected LinkedHashMapWithContext<CodegenKey, CodegenSchema> getProperties(Map<
33343334
* @param required a set of required properties' name
33353335
* @return the optional properties
33363336
*/
3337-
protected LinkedHashMapWithContext<CodegenKey, CodegenSchema> getOptionalProperties(LinkedHashMapWithContext<CodegenKey, CodegenSchema> properties, Set<String> required, String sourceJsonPath, String currentName) {
3337+
protected LinkedHashMapWithContext<CodegenKey, CodegenSchema> getOptionalProperties(LinkedHashMapWithContext<CodegenKey, CodegenSchema> properties, Set<String> required, String sourceJsonPath, String currentName, CodegenSchema additionalProperties) {
33383338
if (properties == null) {
33393339
return null;
33403340
}
@@ -3343,7 +3343,13 @@ protected LinkedHashMapWithContext<CodegenKey, CodegenSchema> getOptionalPropert
33433343
LinkedHashMapWithContext<CodegenKey, CodegenSchema> optionalProperties = new LinkedHashMapWithContext<>();
33443344
optionalProperties.putAll(properties);
33453345
optionalProperties.setAllAreInline(properties.allAreInline());
3346-
CodegenKey jsonPathPiece = getKey(currentName + "DictInput", "schemaProperty", sourceJsonPath);
3346+
CodegenKey jsonPathPiece;
3347+
boolean addPropsIsFalse = additionalProperties != null && additionalProperties.isBooleanSchemaFalse;
3348+
if (addPropsIsFalse) {
3349+
jsonPathPiece = getKey(currentName + "Dict", "schemaProperty", sourceJsonPath);
3350+
} else {
3351+
jsonPathPiece = getKey(currentName + "DictInput", "schemaProperty", sourceJsonPath);
3352+
}
33473353
optionalProperties.setJsonPathPiece(jsonPathPiece);
33483354
return optionalProperties;
33493355
}

modules/openapi-json-schema-generator/src/test/resources/3_0/python/petstore_customized.yaml

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3080,6 +3080,7 @@ components:
30803080
required:
30813081
- amount
30823082
- currency
3083+
additionalProperties: false
30833084
DecimalPayload:
30843085
type: string
30853086
format: number
@@ -3289,4 +3290,11 @@ components:
32893290
required:
32903291
- a
32913292
allOf:
3292-
- $ref: '#/components/schemas/ObjWithRequiredPropsBase'
3293+
- $ref: '#/components/schemas/ObjWithRequiredPropsBase'
3294+
ObjectWithOnlyOptionalProps:
3295+
properties:
3296+
a:
3297+
type: string
3298+
b:
3299+
type: number
3300+
additionalProperties: false

samples/openapi3/client/petstore/python/.openapi-generator/FILES

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ docs/components/schema/object_with_decimal_properties.md
128128
docs/components/schema/object_with_difficultly_named_props.md
129129
docs/components/schema/object_with_inline_composition_property.md
130130
docs/components/schema/object_with_invalid_named_refed_properties.md
131+
docs/components/schema/object_with_only_optional_props.md
131132
docs/components/schema/object_with_optional_test_prop.md
132133
docs/components/schema/object_with_validations.md
133134
docs/components/schema/order.md
@@ -476,6 +477,7 @@ src/petstore_api/components/schema/object_with_decimal_properties.py
476477
src/petstore_api/components/schema/object_with_difficultly_named_props.py
477478
src/petstore_api/components/schema/object_with_inline_composition_property.py
478479
src/petstore_api/components/schema/object_with_invalid_named_refed_properties.py
480+
src/petstore_api/components/schema/object_with_only_optional_props.py
479481
src/petstore_api/components/schema/object_with_optional_test_prop.py
480482
src/petstore_api/components/schema/object_with_validations.py
481483
src/petstore_api/components/schema/order.py

samples/openapi3/client/petstore/python/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,7 @@ Class | Description
363363
[ObjectWithDifficultlyNamedProps](docs/components/schema/object_with_difficultly_named_props.md) | model with properties that have invalid names for python
364364
[ObjectWithInlineCompositionProperty](docs/components/schema/object_with_inline_composition_property.md) |
365365
[ObjectWithInvalidNamedRefedProperties](docs/components/schema/object_with_invalid_named_refed_properties.md) |
366+
[ObjectWithOnlyOptionalProps](docs/components/schema/object_with_only_optional_props.md) |
366367
[ObjectWithOptionalTestProp](docs/components/schema/object_with_optional_test_prop.md) |
367368
[ObjectWithValidations](docs/components/schema/object_with_validations.md) |
368369
[Order](docs/components/schema/order.md) |

samples/openapi3/client/petstore/python/docs/components/schema/money.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,5 @@ Key | Input Type | Accessed Type | Description | Notes
1111
------------ | ------------- | ------------- | ------------- | -------------
1212
**amount** | str | str | | value must be numeric and storable in decimal.Decimal
1313
**currency** | [**Currency**](currency.md), str | [**Currency**](currency.md) | |
14-
**any_string_name** | dict, frozendict.frozendict, list, tuple, decimal.Decimal, float, int, str, datetime.date, datetime.datetime, uuid.UUID, bool, None, bytes, io.FileIO, io.BufferedReader, schemas.Schema | frozendict.frozendict, tuple, decimal.Decimal, str, bytes, BoolClass, NoneClass, FileIO | any string name can be used but the value must be the correct type | [optional]
1514

1615
[[Back to top]](#top) [[Back to Component Schemas]](../../../README.md#Component-Schemas) [[Back to README]](../../../README.md)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
petstore_api.components.schema.object_with_only_optional_props
2+
# Schema ObjectWithOnlyOptionalProps
3+
4+
## Type Info
5+
Input Type | Accessed Type | Description | Notes
6+
------------ | ------------- | ------------- | -------------
7+
dict, frozendict.frozendict | frozendict.frozendict | |
8+
9+
## Dictionary Keys
10+
Key | Input Type | Accessed Type | Description | Notes
11+
------------ | ------------- | ------------- | ------------- | -------------
12+
**a** | str | str | | [optional]
13+
**b** | decimal.Decimal, int, float | decimal.Decimal | | [optional]
14+
15+
[[Back to top]](#top) [[Back to Component Schemas]](../../../README.md#Component-Schemas) [[Back to README]](../../../README.md)

samples/openapi3/client/petstore/python/src/petstore_api/components/schema/money.py

Lines changed: 10 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from __future__ import annotations
1111
from petstore_api.shared_imports.schema_imports import *
1212

13+
AdditionalProperties: typing_extensions.TypeAlias = schemas.NotAnyTypeSchema[U]
1314
Amount: typing_extensions.TypeAlias = schemas.DecimalSchema[U]
1415

1516

@@ -31,6 +32,7 @@ class Schema_(metaclass=schemas.SingletonMeta):
3132
"currency",
3233
})
3334
properties: Properties = dataclasses.field(default_factory=lambda: schemas.typed_dict_to_instance(Properties)) # type: ignore
35+
additional_properties: typing.Type[AdditionalProperties] = dataclasses.field(default_factory=lambda: AdditionalProperties) # type: ignore
3436

3537
@property
3638
def amount(self) -> Amount[str]:
@@ -46,24 +48,11 @@ def __getitem__(self, name: typing_extensions.Literal["amount"]) -> Amount[str]:
4648
@typing.overload
4749
def __getitem__(self, name: typing_extensions.Literal["currency"]) -> currency.Currency[str]: ...
4850

49-
@typing.overload
50-
def __getitem__(self, name: str) -> schemas.AnyTypeSchema[typing.Union[
51-
frozendict.frozendict,
52-
str,
53-
decimal.Decimal,
54-
schemas.BoolClass,
55-
schemas.NoneClass,
56-
tuple,
57-
bytes,
58-
schemas.FileIO
59-
]]: ...
60-
6151
def __getitem__(
6252
self,
6353
name: typing.Union[
6454
typing_extensions.Literal["amount"],
6555
typing_extensions.Literal["currency"],
66-
str
6756
]
6857
):
6958
# dict_instance[name] accessor
@@ -73,7 +62,7 @@ def __getitem__(
7362
def validate(
7463
cls,
7564
arg: typing.Union[
76-
MoneyDictInput,
65+
MoneyDict,
7766
Money[frozendict.frozendict],
7867
],
7968
configuration: typing.Optional[schemas.schema_configuration.SchemaConfiguration] = None
@@ -92,57 +81,16 @@ def validate(
9281
"currency": typing.Type[currency.Currency],
9382
}
9483
)
95-
MoneyDictInput = typing.Mapping[
96-
str,
97-
typing.Union[
98-
typing.Union[
84+
MoneyDict = typing_extensions.TypedDict(
85+
'MoneyDict',
86+
{
87+
"amount": typing.Union[
9988
Amount[str],
10089
str
10190
],
102-
typing.Union[
91+
"currency": typing.Union[
10392
currency.Currency[str],
10493
str
10594
],
106-
schemas.INPUT_TYPES_ALL_INCL_SCHEMA
107-
]
108-
]
109-
110-
111-
class MoneyDict(typing.Dict[str, typing.Any]):
112-
113-
@property
114-
def amount(self) -> Amount[str]:
115-
return self.__getitem__("amount")
116-
117-
@property
118-
def currency(self) -> currency.Currency[str]:
119-
return self.__getitem__("currency")
120-
121-
@typing.overload
122-
def __getitem__(self, name: typing_extensions.Literal["amount"]) -> Amount[str]: ...
123-
124-
@typing.overload
125-
def __getitem__(self, name: typing_extensions.Literal["currency"]) -> currency.Currency[str]: ...
126-
127-
@typing.overload
128-
def __getitem__(self, name: str) -> schemas.AnyTypeSchema[typing.Union[
129-
frozendict.frozendict,
130-
str,
131-
decimal.Decimal,
132-
schemas.BoolClass,
133-
schemas.NoneClass,
134-
tuple,
135-
bytes,
136-
schemas.FileIO
137-
]]: ...
138-
139-
def __getitem__(
140-
self,
141-
name: typing.Union[
142-
typing_extensions.Literal["amount"],
143-
typing_extensions.Literal["currency"],
144-
str
145-
]
146-
):
147-
# dict_instance[name] accessor
148-
return super().__getitem__(name)
95+
}
96+
)
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# coding: utf-8
2+
3+
"""
4+
OpenAPI Petstore
5+
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
6+
The version of the OpenAPI document: 1.0.0
7+
Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
8+
"""
9+
10+
from __future__ import annotations
11+
from petstore_api.shared_imports.schema_imports import *
12+
13+
AdditionalProperties: typing_extensions.TypeAlias = schemas.NotAnyTypeSchema[U]
14+
A: typing_extensions.TypeAlias = schemas.StrSchema[U]
15+
B: typing_extensions.TypeAlias = schemas.NumberSchema[U]
16+
Properties = typing_extensions.TypedDict(
17+
'Properties',
18+
{
19+
"a": typing.Type[A],
20+
"b": typing.Type[B],
21+
}
22+
)
23+
ObjectWithOnlyOptionalPropsDict = typing_extensions.TypedDict(
24+
'ObjectWithOnlyOptionalPropsDict',
25+
{
26+
"a": typing.Union[
27+
A[str],
28+
str
29+
],
30+
"b": typing.Union[
31+
B[decimal.Decimal],
32+
decimal.Decimal,
33+
int,
34+
float
35+
],
36+
},
37+
total=False
38+
)
39+
40+
41+
class ObjectWithOnlyOptionalProps(
42+
schemas.DictSchema[schemas.T]
43+
):
44+
"""NOTE: This class is auto generated by OpenAPI JSON Schema Generator.
45+
Ref: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
46+
47+
Do not edit the class manually.
48+
"""
49+
50+
51+
@dataclasses.dataclass(frozen=True)
52+
class Schema_(metaclass=schemas.SingletonMeta):
53+
types: typing.FrozenSet[typing.Type] = frozenset({frozendict.frozendict})
54+
properties: Properties = dataclasses.field(default_factory=lambda: schemas.typed_dict_to_instance(Properties)) # type: ignore
55+
additional_properties: typing.Type[AdditionalProperties] = dataclasses.field(default_factory=lambda: AdditionalProperties) # type: ignore
56+
57+
@typing.overload
58+
def __getitem__(self, name: typing_extensions.Literal["a"]) -> A[str]: ...
59+
60+
@typing.overload
61+
def __getitem__(self, name: typing_extensions.Literal["b"]) -> B[decimal.Decimal]: ...
62+
63+
def __getitem__(
64+
self,
65+
name: typing.Union[
66+
typing_extensions.Literal["a"],
67+
typing_extensions.Literal["b"],
68+
]
69+
):
70+
# dict_instance[name] accessor
71+
return super().__getitem__(name)
72+
73+
@classmethod
74+
def validate(
75+
cls,
76+
arg: typing.Union[
77+
ObjectWithOnlyOptionalPropsDict,
78+
ObjectWithOnlyOptionalProps[frozendict.frozendict],
79+
],
80+
configuration: typing.Optional[schemas.schema_configuration.SchemaConfiguration] = None
81+
) -> ObjectWithOnlyOptionalPropsDict:
82+
return super().validate(
83+
arg,
84+
configuration=configuration,
85+
)
86+

samples/openapi3/client/petstore/python/src/petstore_api/components/schemas/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@
100100
from petstore_api.components.schema.object_with_difficultly_named_props import ObjectWithDifficultlyNamedProps
101101
from petstore_api.components.schema.object_with_inline_composition_property import ObjectWithInlineCompositionProperty
102102
from petstore_api.components.schema.object_with_invalid_named_refed_properties import ObjectWithInvalidNamedRefedProperties
103+
from petstore_api.components.schema.object_with_only_optional_props import ObjectWithOnlyOptionalProps
103104
from petstore_api.components.schema.object_with_optional_test_prop import ObjectWithOptionalTestProp
104105
from petstore_api.components.schema.object_with_validations import ObjectWithValidations
105106
from petstore_api.components.schema.order import Order
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# coding: utf-8
2+
3+
"""
4+
OpenAPI Petstore
5+
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
6+
The version of the OpenAPI document: 1.0.0
7+
Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
8+
"""
9+
10+
import unittest
11+
12+
import petstore_api
13+
from petstore_api.components.schema.object_with_only_optional_props import ObjectWithOnlyOptionalProps
14+
from petstore_api.configurations import schema_configuration
15+
16+
17+
class TestObjectWithOnlyOptionalProps(unittest.TestCase):
18+
"""ObjectWithOnlyOptionalProps unit test stubs"""
19+
configuration = schema_configuration.SchemaConfiguration()
20+
21+
22+
if __name__ == '__main__':
23+
unittest.main()

0 commit comments

Comments
 (0)