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

[python-experimental] removes enum cls factory #13491

Merged
merged 2 commits into from
Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
Expand Down Expand Up @@ -1226,6 +1227,8 @@ public String toEnumVarName(String value, String datatype) {
// our enum var names are keys in a python dict, so change spaces to underscores
if (value.length() == 0) {
return "EMPTY";
} else if (value.equals("null")) {
return "NONE";
}

String intPattern = "^[-\\+]?\\d+$";
Expand Down Expand Up @@ -1289,26 +1292,80 @@ private String charNameToVarName(String charName) {
return varName;
}

/**
* Return the enum value in the language specified format
* e.g. status becomes "status"
*
* @param value enum variable name
* @param datatype data type
* @return the sanitized value for enum
*/
public String toEnumValue(String value, String datatype) {
if ("int".equals(datatype) || "float".equals(datatype) || datatype.equals("int, float")) {
return value;
} else if ("bool".equals(datatype)) {
if (value.equals("true")) {
return "schemas.BoolClass.TRUE";
protected List<Map<String, Object>> buildEnumVars(List<Object> values, String dataType) {
List<Map<String, Object>> enumVars = new ArrayList<>();
int truncateIdx = 0;

if (isRemoveEnumValuePrefix()) {
String commonPrefix = findCommonPrefixOfVars(values);
truncateIdx = commonPrefix.length();
}

for (Object value : values) {
Map<String, Object> enumVar = new HashMap<>();
String enumName;
if (truncateIdx == 0) {
enumName = String.valueOf(value);
} else {
enumName = value.toString().substring(truncateIdx);
if (enumName.isEmpty()) {
enumName = value.toString();
}
}
return "schemas.BoolClass.FALSE";
} else {
String fixedValue = (String) processTestExampleData(value);
return ensureQuotes(fixedValue);

enumVar.put("name", toEnumVarName(enumName, dataType));
if (value instanceof Integer) {
enumVar.put("value", value);
} else if (value instanceof Double) {
enumVar.put("value", value);
} else if (value instanceof Long) {
enumVar.put("value", value);
} else if (value instanceof Float) {
enumVar.put("value", value);
} else if (value instanceof BigDecimal) {
enumVar.put("value", value);
} else if (value == null) {
enumVar.put("value", "schemas.NoneClass.NONE");
} else if (value instanceof Boolean) {
if (value.equals(Boolean.TRUE)) {
enumVar.put("value", "schemas.BoolClass.TRUE");
} else {
enumVar.put("value", "schemas.BoolClass.FALSE");
}
} else {
String fixedValue = (String) processTestExampleData(value);
enumVar.put("value", ensureQuotes(fixedValue));
}
enumVar.put("isString", isDataTypeString(dataType));
enumVars.add(enumVar);
}

if (enumUnknownDefaultCase) {
// If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.
// With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.
Map<String, Object> enumVar = new HashMap<>();
String enumName = enumUnknownDefaultCaseName;

String enumValue;
if (isDataTypeString(dataType)) {
enumValue = enumUnknownDefaultCaseName;
} else {
// This is a dummy value that attempts to avoid collisions with previously specified cases.
// Int.max / 192
// The number 192 that is used to calculate this random value, is the Swift Evolution proposal for frozen/non-frozen enums.
// [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md)
// Since this functionality was born in the Swift 5 generator and latter on broth to all generators
// https://github.com/OpenAPITools/openapi-generator/pull/11013
enumValue = String.valueOf(11184809);
}

enumVar.put("name", toEnumVarName(enumName, dataType));
enumVar.put("value", toEnumValue(enumValue, dataType));
enumVar.put("isString", isDataTypeString(dataType));
enumVars.add(enumVar);
}

return enumVars;
}

@Override
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
{{#if isNull}}

@schemas.classproperty
def NONE(cls):
return cls(None)
{{/if}}
{{#with allowableValues}}
{{#each enumVars}}

@schemas.classproperty
def {{name}}(cls):
{{#eq value "schemas.NoneClass.NONE"}}
return cls(None)
{{else}}
{{#eq value "schemas.BoolClass.TRUE"}}
return cls(True)
{{else}}
{{#eq value "schemas.BoolClass.FALSE"}}
return cls(False)
{{else}}
return cls({{{value}}})
{{/eq}}
{{/eq}}
{{/eq}}
{{/each}}
{{/with}}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{{#unless isArray}}{{#unless complexType}}{{#with allowableValues}}must be one of [{{#each enumVars}}{{{value}}}, {{/each}}] {{/with}}{{#if defaultValue}}{{#unless hasRequired}}if omitted the server will use the default value of {{{defaultValue}}}{{/unless}}{{/if}}{{#eq getFormat "uuid"}}value must be a uuid{{/eq}}{{#eq getFormat "date"}}value must conform to RFC-3339 full-date YYYY-MM-DD{{/eq}}{{#eq getFormat "date-time"}}value must conform to RFC-3339 date-time{{/eq}}{{#eq getFormat "number"}}value must be numeric and storable in decimal.Decimal{{/eq}}{{#eq getFormat "int32"}}value must be a 32 bit integer{{/eq}}{{#eq getFormat "int64"}}value must be a 64 bit integer{{/eq}}{{#eq getFormat "double"}}value must be a 64 bit float{{/eq}}{{#eq getFormat "float"}}value must be a 32 bit float{{/eq}}{{/unless}}{{/unless}}
{{#unless isArray}}{{#unless complexType}}{{#with allowableValues}}must be one of [{{#each enumVars}}{{#eq value "schemas.NoneClass.NONE"}}None{{else}}{{#eq value "schemas.BoolClass.TRUE"}}True{{else}}{{#eq value "schemas.BoolClass.FALSE"}}False{{else}}{{{value}}}{{/eq}}{{/eq}}{{/eq}}, {{/each}}] {{/with}}{{#if defaultValue}}{{#unless hasRequired}}if omitted the server will use the default value of {{{defaultValue}}}{{/unless}}{{/if}}{{#eq getFormat "uuid"}}value must be a uuid{{/eq}}{{#eq getFormat "date"}}value must conform to RFC-3339 full-date YYYY-MM-DD{{/eq}}{{#eq getFormat "date-time"}}value must conform to RFC-3339 date-time{{/eq}}{{#eq getFormat "number"}}value must be numeric and storable in decimal.Decimal{{/eq}}{{#eq getFormat "int32"}}value must be a 32 bit integer{{/eq}}{{#eq getFormat "int64"}}value must be a 64 bit integer{{/eq}}{{#eq getFormat "double"}}value must be a 64 bit float{{/eq}}{{#eq getFormat "float"}}value must be a 32 bit float{{/eq}}{{/unless}}{{/unless}}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}
schemas.ComposedBase,
{{/if}}
{{#if isEnum}}
{{> model_templates/enum_value_to_name }}
schemas.EnumBase,
{{/if}}
{{> model_templates/xbase_schema }}
{{/if}}
Expand All @@ -31,13 +31,22 @@ class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}
{{/if}}
"""
{{/if}}
{{#or hasValidation composedSchemas getItems additionalProperties getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping vars getFormat}}
{{#or hasValidation composedSchemas getItems additionalProperties getRequiredVarsMap getHasDiscriminatorWithNonEmptyMapping vars getFormat isEnum}}


class MetaOapg:
{{#if getFormat}}
format = '{{getFormat}}'
{{/if}}
{{#if isEnum}}
{{#with allowableValues}}
enum_value_to_name = {
{{#each enumVars}}
{{{value}}}: "{{name}}",
{{/each}}
}
{{/with}}
{{/if}}
{{#if getItems}}
{{> model_templates/list_partial }}
{{/if}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}}(
{{#if isEnum}}
{{> model_templates/enum_value_to_name }}
schemas.EnumBase,
{{/if}}
{{> model_templates/xbase_schema }}
):
Expand All @@ -18,12 +18,24 @@ class {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}
"""
{{/if}}
{{#unless isStub}}
{{#if hasValidation}}
{{#or hasValidation isEnum getFormat}}


class MetaOapg:
{{#if getFormat}}
format = '{{getFormat}}'
{{/if}}
{{> model_templates/validations }}
{{#if isEnum}}
{{#with allowableValues}}
enum_value_to_name = {
{{#each enumVars}}
{{{value}}}: "{{name}}",
{{/each}}
}
{{/with}}
{{/if}}
{{/or}}
{{/unless}}
{{#if isEnum}}
{{> model_templates/enums }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ class Schema:
"""
cls._process_schema_classes_oapg(schema_classes)
enum_schema = any(
hasattr(this_cls, '_enum_value_to_name') for this_cls in schema_classes)
issubclass(this_cls, EnumBase) for this_cls in schema_classes)
inheritable_primitive_type = schema_classes.intersection(cls.__inheritable_primitive_types_set)
chosen_schema_classes = schema_classes - inheritable_primitive_type
suffix = tuple(inheritable_primitive_type)
Expand Down Expand Up @@ -873,41 +873,22 @@ class ValidatorBase:
)


class EnumMakerBase:
pass


def SchemaEnumMakerClsFactory(enum_value_to_name: typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]) -> 'SchemaEnumMaker':
class SchemaEnumMaker(EnumMakerBase):
@classmethod
def _enum_value_to_name(
cls
) -> typing.Dict[typing.Union[str, decimal.Decimal, bool, none_type], str]:
pass
try:
super_enum_value_to_name = super()._enum_value_to_name()
except AttributeError:
return enum_value_to_name
intersection = dict(enum_value_to_name.items() & super_enum_value_to_name.items())
return intersection

@classmethod
def _validate_oapg(
cls,
arg,
validation_metadata: ValidationMetadata,
) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]:
"""
SchemaEnumMaker _validate_oapg
Validates that arg is in the enum's allowed values
"""
try:
cls._enum_value_to_name()[arg]
except KeyError:
raise ApiValueError("Invalid value {} passed in to {}, {}".format(arg, cls, cls._enum_value_to_name()))
return super()._validate_oapg(arg, validation_metadata=validation_metadata)

return SchemaEnumMaker
class EnumBase:
@classmethod
def _validate_oapg(
cls,
arg,
validation_metadata: ValidationMetadata,
) -> typing.Dict[typing.Tuple[typing.Union[str, int], ...], typing.Set[typing.Union['Schema', str, decimal.Decimal, BoolClass, NoneClass, frozendict.frozendict, tuple]]]:
"""
EnumBase _validate_oapg
Validates that arg is in the enum's allowed values
"""
try:
cls.MetaOapg.enum_value_to_name[arg]
except KeyError:
raise ApiValueError("Invalid value {} passed in to {}, allowed_values={}".format(arg, cls, cls.MetaOapg.enum_value_to_name.keys()))
return super()._validate_oapg(arg, validation_metadata=validation_metadata)


class BoolBase:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2224,6 +2224,7 @@ components:
multiple
lines
- "double quote \n with newline"
- null
IntegerEnum:
type: integer
enum:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Model Type Info
Input Type | Accessed Type | Description | Notes
------------ | ------------- | ------------- | -------------
bool, | BoolClass, | | must be one of [schemas.BoolClass.FALSE, ]
bool, | BoolClass, | | must be one of [False, ]

[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Model Type Info
Input Type | Accessed Type | Description | Notes
------------ | ------------- | ------------- | -------------
bool, | BoolClass, | | must be one of [schemas.BoolClass.TRUE, ]
bool, | BoolClass, | | must be one of [True, ]

[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md)

Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,20 @@


class EnumWith0DoesNotMatchFalse(
schemas.SchemaEnumMakerClsFactory(
enum_value_to_name={
0: "POSITIVE_0",
}
),
schemas.EnumBase,
schemas.NumberSchema
):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech

Do not edit the class manually.
"""


class MetaOapg:
enum_value_to_name = {
0: "POSITIVE_0",
}

@schemas.classproperty
def POSITIVE_0(cls):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ from unit_test_api import schemas # noqa: F401


class EnumWith0DoesNotMatchFalse(
schemas.SchemaEnumMakerClsFactory(
enum_value_to_name={
0: "POSITIVE_0",
}
),
schemas.EnumBase,
schemas.NumberSchema
):
"""NOTE: This class is auto generated by OpenAPI Generator.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,20 @@


class EnumWith1DoesNotMatchTrue(
schemas.SchemaEnumMakerClsFactory(
enum_value_to_name={
1: "POSITIVE_1",
}
),
schemas.EnumBase,
schemas.NumberSchema
):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech

Do not edit the class manually.
"""


class MetaOapg:
enum_value_to_name = {
1: "POSITIVE_1",
}

@schemas.classproperty
def POSITIVE_1(cls):
Expand Down
Loading