@autorest/python 6.18.0 → 6.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/autorest/m4reformatter/__init__.py +15 -3
  2. package/generator/pygen/black.py +2 -3
  3. package/generator/pygen/codegen/models/__init__.py +2 -0
  4. package/generator/pygen/codegen/models/code_model.py +2 -4
  5. package/generator/pygen/codegen/models/combined_type.py +1 -1
  6. package/generator/pygen/codegen/models/credential_types.py +7 -14
  7. package/generator/pygen/codegen/models/enum_type.py +1 -1
  8. package/generator/pygen/codegen/models/lro_operation.py +0 -1
  9. package/generator/pygen/codegen/models/lro_paging_operation.py +1 -1
  10. package/generator/pygen/codegen/models/model_type.py +6 -9
  11. package/generator/pygen/codegen/models/operation.py +13 -16
  12. package/generator/pygen/codegen/models/paging_operation.py +0 -1
  13. package/generator/pygen/codegen/models/parameter_list.py +2 -5
  14. package/generator/pygen/codegen/models/primitive_types.py +35 -3
  15. package/generator/pygen/codegen/models/property.py +1 -9
  16. package/generator/pygen/codegen/serializers/__init__.py +1 -1
  17. package/generator/pygen/codegen/serializers/builder_serializer.py +12 -13
  18. package/generator/pygen/codegen/serializers/general_serializer.py +2 -2
  19. package/generator/pygen/codegen/serializers/model_serializer.py +2 -0
  20. package/generator/pygen/codegen/serializers/sample_serializer.py +20 -15
  21. package/generator/pygen/codegen/templates/model_base.py.jinja2 +30 -18
  22. package/generator/pygen/codegen/templates/vendor.py.jinja2 +0 -2
  23. package/generator/pygen/m2r.py +1 -1
  24. package/generator/pygen/postprocess/__init__.py +2 -2
  25. package/generator/pygen/postprocess/venvtools.py +1 -3
  26. package/generator/pygen/preprocess/__init__.py +1 -1
  27. package/generator/pygen/utils.py +1 -3
  28. package/generator/setup.py +1 -1
  29. package/package.json +11 -6
  30. package/scripts/__pycache__/venvtools.cpython-310.pyc +0 -0
  31. package/scripts/copy-generator.ts +24 -0
  32. package/scripts/eng/format.ts +5 -0
  33. package/scripts/eng/lint.ts +75 -0
  34. package/scripts/eng/mypy.ini +38 -0
  35. package/scripts/eng/pylintrc +58 -0
  36. package/scripts/eng/pyrightconfig.json +6 -0
  37. package/scripts/eng/regenerate.ts +298 -0
  38. package/scripts/eng/run-tests.ts +80 -0
  39. package/scripts/eng/utils.ts +38 -0
  40. package/scripts/mypy.ini +38 -0
  41. package/scripts/run-python3.ts +25 -0
  42. package/scripts/system-requirements.ts +253 -0
  43. package/scripts/copy-generator.js +0 -19
@@ -28,6 +28,20 @@ KEY_TYPE = "Key"
28
28
  _LOGGER = logging.getLogger(__name__)
29
29
 
30
30
 
31
+ def get_item_type(yaml_data: Dict[str, Any], item_name: str, enable_exception: bool = True) -> Optional[Dict[str, Any]]:
32
+ try:
33
+ return next(p["type"] for p in yaml_data.get("properties", []) if p["wireName"] == item_name)
34
+ except StopIteration:
35
+ pass
36
+ for parent in yaml_data.get("parents", []):
37
+ result = get_item_type(parent, item_name, False)
38
+ if result:
39
+ return result
40
+ if enable_exception:
41
+ raise StopIteration(f"Could not find item type {item_name} from type {yaml_data['name']}")
42
+ return None
43
+
44
+
31
45
  def is_body(yaml_data: Dict[str, Any]) -> bool:
32
46
  """Return true if passed in parameter is a body param"""
33
47
  return yaml_data["protocol"]["http"]["in"] == "body"
@@ -544,9 +558,7 @@ class M4Reformatter(YamlUpdatePluginAutorest): # pylint: disable=too-many-publi
544
558
  if self.version_tolerant:
545
559
  # if we're in version tolerant, hide the paging model
546
560
  returned_response_object["type"]["internal"] = True
547
- operation["itemType"] = next(
548
- p["type"] for p in returned_response_object["type"]["properties"] if p["wireName"] == operation["itemName"]
549
- )
561
+ operation["itemType"] = get_item_type(returned_response_object["type"], operation["itemName"])
550
562
  if yaml_data["language"]["default"]["paging"].get("nextLinkOperation"):
551
563
  operation["nextOperation"] = self.update_operation(
552
564
  group_name=group_name,
@@ -6,7 +6,6 @@
6
6
  import logging
7
7
  from pathlib import Path
8
8
  import os
9
- from typing import Any, Dict
10
9
  import black
11
10
  from black.report import NothingChanged
12
11
 
@@ -19,7 +18,7 @@ _BLACK_MODE = black.Mode() # pyright: ignore [reportPrivateImportUsage]
19
18
  _BLACK_MODE.line_length = 120
20
19
 
21
20
 
22
- class BlackScriptPlugin(Plugin): # pylint: disable=abstract-method
21
+ class BlackScriptPlugin(Plugin):
23
22
  def __init__(self, **kwargs):
24
23
  super().__init__(**kwargs)
25
24
  output_folder = self.options.get("output_folder", str(self.output_folder))
@@ -57,7 +56,7 @@ class BlackScriptPlugin(Plugin): # pylint: disable=abstract-method
57
56
  file_content = black.format_file_contents(file_content, fast=True, mode=_BLACK_MODE)
58
57
  except NothingChanged:
59
58
  pass
60
- except: # pylint: disable=bare-except
59
+ except:
61
60
  _LOGGER.error("Error: failed to format %s", file)
62
61
  raise
63
62
  else:
@@ -30,6 +30,7 @@ from .primitive_types import (
30
30
  UnixTimeType,
31
31
  SdkCoreType,
32
32
  DecimalType,
33
+ MultiPartFileType,
33
34
  )
34
35
  from .enum_type import EnumType, EnumValue
35
36
  from .base import BaseType
@@ -149,6 +150,7 @@ TYPE_TO_OBJECT = {
149
150
  "unixtime": UnixTimeType,
150
151
  "credential": StringType,
151
152
  "sdkcore": SdkCoreType,
153
+ "multipartfile": MultiPartFileType,
152
154
  }
153
155
  _LOGGER = logging.getLogger(__name__)
154
156
 
@@ -7,7 +7,7 @@ from typing import List, Dict, Any, Set, Union, Literal
7
7
 
8
8
  from .base import BaseType
9
9
  from .enum_type import EnumType
10
- from .model_type import ModelType
10
+ from .model_type import ModelType, UsageFlags
11
11
  from .combined_type import CombinedType
12
12
  from .client import Client
13
13
  from .request_builder import RequestBuilder, OverloadedRequestBuilder
@@ -162,9 +162,7 @@ class CodeModel: # pylint: disable=too-many-public-methods, disable=too-many-in
162
162
  """All of the model types in this class"""
163
163
  if not self._model_types:
164
164
  self._model_types = [
165
- t
166
- for t in self.types_map.values()
167
- if isinstance(t, ModelType) and not (self.options["models_mode"] == "dpg" and t.page_result_model)
165
+ t for t in self.types_map.values() if isinstance(t, ModelType) and t.usage != UsageFlags.Default.value
168
166
  ]
169
167
  return self._model_types
170
168
 
@@ -51,7 +51,7 @@ class CombinedType(BaseType):
51
51
  def client_default_value(self) -> Any:
52
52
  return self.yaml_data.get("clientDefaultValue")
53
53
 
54
- def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument
54
+ def description(self, *, is_operation_file: bool) -> str:
55
55
  if len(self.types) == 2:
56
56
  return f"Is either a {self.types[0].type_description} type or a {self.types[1].type_description} type."
57
57
  return f"Is one of the following types: {', '.join([t.type_description for t in self.types])}"
@@ -106,7 +106,7 @@ CredentialPolicyType = TypeVar(
106
106
  )
107
107
 
108
108
 
109
- class CredentialType(Generic[CredentialPolicyType], BaseType): # pylint:disable=abstract-method
109
+ class CredentialType(Generic[CredentialPolicyType], BaseType):
110
110
  """Store info about the type of the credential. Can be either an KeyCredential or a TokenCredential"""
111
111
 
112
112
  def __init__(
@@ -118,7 +118,7 @@ class CredentialType(Generic[CredentialPolicyType], BaseType): # pylint:disable
118
118
  super().__init__(yaml_data, code_model)
119
119
  self.policy = policy
120
120
 
121
- def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument
121
+ def description(self, *, is_operation_file: bool) -> str:
122
122
  return ""
123
123
 
124
124
  def get_json_template_representation(
@@ -146,11 +146,7 @@ class CredentialType(Generic[CredentialPolicyType], BaseType): # pylint:disable
146
146
  )
147
147
 
148
148
 
149
- class TokenCredentialType(
150
- CredentialType[ # pylint: disable=unsubscriptable-object
151
- Union[BearerTokenCredentialPolicyType, ARMChallengeAuthenticationPolicyType]
152
- ]
153
- ):
149
+ class TokenCredentialType(CredentialType[Union[BearerTokenCredentialPolicyType, ARMChallengeAuthenticationPolicyType]]):
154
150
  """Type of a token credential. Used by BearerAuth and ARMChallenge policies"""
155
151
 
156
152
  def type_annotation(self, **kwargs: Any) -> str:
@@ -194,23 +190,20 @@ class TokenCredentialType(
194
190
  return "hasattr({}, 'get_token')"
195
191
 
196
192
 
197
- class KeyCredentialType(
198
- # pylint: disable=unsubscriptable-object
199
- CredentialType[KeyCredentialPolicyType]
200
- ):
193
+ class KeyCredentialType(CredentialType[KeyCredentialPolicyType]):
201
194
  """Type for an KeyCredential"""
202
195
 
203
- def docstring_type(self, **kwargs: Any) -> str: # pylint: disable=unused-argument
196
+ def docstring_type(self, **kwargs: Any) -> str:
204
197
  return f"~{self.code_model.core_library}.credentials.{self.policy.credential_name}"
205
198
 
206
- def type_annotation(self, **kwargs: Any) -> str: # pylint: disable=unused-argument
199
+ def type_annotation(self, **kwargs: Any) -> str:
207
200
  return self.policy.credential_name
208
201
 
209
202
  @property
210
203
  def instance_check_template(self) -> str:
211
204
  return "isinstance({}, " + f"{self.policy.credential_name})"
212
205
 
213
- def imports(self, **kwargs: Any) -> FileImport: # pylint: disable=unused-argument
206
+ def imports(self, **kwargs: Any) -> FileImport:
214
207
  file_import = super().imports(**kwargs)
215
208
  file_import.add_submodule_import(
216
209
  "credentials",
@@ -137,7 +137,7 @@ class EnumType(BaseType):
137
137
  """
138
138
  return self.value_type.serialization_type
139
139
 
140
- def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument
140
+ def description(self, *, is_operation_file: bool) -> str:
141
141
  possible_values = [self.get_declaration(v.value) for v in self.values]
142
142
  if not possible_values:
143
143
  return ""
@@ -1,4 +1,3 @@
1
- # pylint: disable=multiple-statements
2
1
  # -------------------------------------------------------------------------
3
2
  # Copyright (c) Microsoft Corporation. All rights reserved.
4
3
  # Licensed under the MIT License. See License.txt in the project root for
@@ -21,7 +21,7 @@ class LROPagingOperation(LROOperationBase[LROPagingResponse], PagingOperationBas
21
21
  return "lropaging"
22
22
 
23
23
  def cls_type_annotation(self, *, async_mode: bool) -> str:
24
- return f"ClsType[{Response.type_annotation(self.responses[0], async_mode=async_mode)}]" # pylint: disable=no-member
24
+ return f"ClsType[{Response.type_annotation(self.responses[0], async_mode=async_mode)}]"
25
25
 
26
26
  def imports(self, async_mode: bool, **kwargs: Any) -> FileImport:
27
27
  lro_imports = LROOperationBase.imports(self, async_mode, **kwargs)
@@ -17,9 +17,9 @@ from .property import Property
17
17
  from .imports import FileImport, ImportType, TypingSection
18
18
 
19
19
  if sys.version_info >= (3, 8):
20
- from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports
20
+ from typing import Literal
21
21
  else:
22
- from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports
22
+ from typing_extensions import Literal # type: ignore
23
23
 
24
24
  if TYPE_CHECKING:
25
25
  from .code_model import CodeModel
@@ -50,9 +50,7 @@ def _get_properties(type: "ModelType", properties: List[Property]) -> List[Prope
50
50
  return properties
51
51
 
52
52
 
53
- class ModelType( # pylint: disable=abstract-method
54
- BaseType
55
- ): # pylint: disable=too-many-instance-attributes, too-many-public-methods
53
+ class ModelType(BaseType): # pylint: disable=too-many-instance-attributes, too-many-public-methods
56
54
  """Represents a class ready to be serialized in Python.
57
55
 
58
56
  :param str name: The name of the class.
@@ -84,13 +82,12 @@ class ModelType( # pylint: disable=abstract-method
84
82
  self._got_polymorphic_subtypes = False
85
83
  self.internal: bool = self.yaml_data.get("internal", False)
86
84
  self.snake_case_name: str = self.yaml_data["snakeCaseName"]
87
- self.page_result_model: bool = self.yaml_data.get("pageResultModel", False)
88
85
  self.cross_language_definition_id: Optional[str] = self.yaml_data.get("crossLanguageDefinitionId")
89
- self.usage: int = self.yaml_data.get("usage", 0)
86
+ self.usage: int = self.yaml_data.get("usage", UsageFlags.Input.value | UsageFlags.Output.value)
90
87
 
91
88
  @property
92
89
  def is_usage_output(self) -> bool:
93
- return self.usage & UsageFlags.Output.value
90
+ return bool(self.usage & UsageFlags.Output.value)
94
91
 
95
92
  @property
96
93
  def flattened_property(self) -> Optional[Property]:
@@ -285,7 +282,7 @@ class JSONModelType(ModelType):
285
282
  return file_import
286
283
 
287
284
 
288
- class GeneratedModelType(ModelType): # pylint: disable=abstract-method
285
+ class GeneratedModelType(ModelType):
289
286
  def type_annotation(self, **kwargs: Any) -> str:
290
287
  is_operation_file = kwargs.pop("is_operation_file", False)
291
288
  skip_quote = kwargs.get("skip_quote", False)
@@ -418,8 +418,19 @@ class OperationBase( # pylint: disable=too-many-public-methods,too-many-instanc
418
418
  file_import.merge(self.get_request_builder_import(self.request_builder, async_mode))
419
419
  if self.overloads:
420
420
  file_import.add_submodule_import("typing", "overload", ImportType.STDLIB)
421
- if self.non_default_errors and self.code_model.options["models_mode"] == "dpg":
422
- file_import.add_submodule_import(f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL)
421
+ if self.code_model.options["models_mode"] == "dpg":
422
+ if self.parameters.has_body:
423
+ if self.has_form_data_body:
424
+ file_import.add_submodule_import(relative_path, "_model_base", ImportType.LOCAL)
425
+ else:
426
+ file_import.add_submodule_import(
427
+ f"{relative_path}_model_base",
428
+ "SdkJSONEncoder",
429
+ ImportType.LOCAL,
430
+ )
431
+ file_import.add_import("json", ImportType.STDLIB)
432
+ if (self.default_error_deserialization or any(r.type for r in self.responses)) or self.non_default_errors:
433
+ file_import.add_submodule_import(f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL)
423
434
  return file_import
424
435
 
425
436
  def get_response_from_status(self, status_code: Optional[Union[str, int]]) -> ResponseType:
@@ -492,20 +503,6 @@ class Operation(OperationBase[Response]):
492
503
  )
493
504
  if self.has_response_body and not self.has_optional_return_type and not self.code_model.options["models_mode"]:
494
505
  file_import.add_submodule_import("typing", "cast", ImportType.STDLIB)
495
- relative_path = "..." if async_mode else ".."
496
- if self.code_model.options["models_mode"] == "dpg":
497
- if self.parameters.has_body:
498
- if self.has_form_data_body:
499
- file_import.add_submodule_import(relative_path, "_model_base", ImportType.LOCAL)
500
- else:
501
- file_import.add_submodule_import(
502
- f"{relative_path}_model_base",
503
- "SdkJSONEncoder",
504
- ImportType.LOCAL,
505
- )
506
- file_import.add_import("json", ImportType.STDLIB)
507
- if self.default_error_deserialization or any(r.type for r in self.responses):
508
- file_import.add_submodule_import(f"{relative_path}_model_base", "_deserialize", ImportType.LOCAL)
509
506
 
510
507
  return file_import
511
508
 
@@ -1,4 +1,3 @@
1
- # pylint: disable=multiple-statements
2
1
  # -------------------------------------------------------------------------
3
2
  # Copyright (c) Microsoft Corporation. All rights reserved.
4
3
  # Licensed under the MIT License. See License.txt in the project root for
@@ -261,8 +261,7 @@ class _ParameterListBase(
261
261
  )
262
262
 
263
263
 
264
- class _ParameterList(_ParameterListBase[Parameter, BodyParameter]): # pylint: disable=unsubscriptable-object
265
- """Base Parameter class for the two operation ParameterLists"""
264
+ class _ParameterList(_ParameterListBase[Parameter, BodyParameter]):
266
265
 
267
266
  @staticmethod
268
267
  def parameter_creator() -> Callable[[Dict[str, Any], "CodeModel"], Parameter]:
@@ -285,9 +284,7 @@ class ParameterList(_ParameterList):
285
284
  """ParameterList is the parameter list for Operation classes"""
286
285
 
287
286
 
288
- class _RequestBuilderParameterList(
289
- _ParameterListBase[RequestBuilderParameter, RequestBuilderBodyParameter] # pylint: disable=unsubscriptable-object
290
- ):
287
+ class _RequestBuilderParameterList(_ParameterListBase[RequestBuilderParameter, RequestBuilderBodyParameter]):
291
288
  """_RequestBuilderParameterList is base parameter list for RequestBuilder classes"""
292
289
 
293
290
  @staticmethod
@@ -22,8 +22,8 @@ class RawString(object):
22
22
  return "r'{}'".format(self.string.replace("'", "\\'"))
23
23
 
24
24
 
25
- class PrimitiveType(BaseType): # pylint: disable=abstract-method
26
- def description(self, *, is_operation_file: bool) -> str: # pylint: disable=unused-argument
25
+ class PrimitiveType(BaseType):
26
+ def description(self, *, is_operation_file: bool) -> str:
27
27
  return ""
28
28
 
29
29
  def type_annotation(self, **kwargs: Any) -> str:
@@ -188,7 +188,7 @@ class AnyObjectType(PrimitiveType):
188
188
  return "JSON"
189
189
 
190
190
 
191
- class NumberType(PrimitiveType): # pylint: disable=abstract-method
191
+ class NumberType(PrimitiveType):
192
192
  def __init__(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None:
193
193
  super().__init__(yaml_data=yaml_data, code_model=code_model)
194
194
  self.precision: Optional[int] = yaml_data.get("precision")
@@ -233,6 +233,12 @@ class NumberType(PrimitiveType): # pylint: disable=abstract-method
233
233
 
234
234
 
235
235
  class IntegerType(NumberType):
236
+
237
+ def __init__(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None:
238
+ super().__init__(yaml_data=yaml_data, code_model=code_model)
239
+ if yaml_data.get("encode") == "string":
240
+ self.encode = "str"
241
+
236
242
  @property
237
243
  def serialization_type(self) -> str:
238
244
  return "int"
@@ -624,3 +630,29 @@ class SdkCoreType(PrimitiveType):
624
630
  @property
625
631
  def serialization_type(self) -> str:
626
632
  return self.name
633
+
634
+
635
+ class MultiPartFileType(PrimitiveType):
636
+ def __init__(self, yaml_data: Dict[str, Any], code_model: "CodeModel") -> None:
637
+ super().__init__(yaml_data=yaml_data, code_model=code_model)
638
+ self.name = "FileType"
639
+
640
+ def type_annotation(self, **kwargs: Any) -> str:
641
+ return self.name
642
+
643
+ def docstring_type(self, **kwargs: Any) -> str:
644
+ return f"~{self.code_model.namespace}._vendor.{self.name}"
645
+
646
+ def imports(self, **kwargs: Any) -> FileImport:
647
+ file_import = super().imports(**kwargs)
648
+ relative_path = "..." if kwargs.get("async_mode") else ".."
649
+ file_import.add_submodule_import(f"{relative_path}_vendor", self.name, ImportType.LOCAL)
650
+ return file_import
651
+
652
+ @property
653
+ def default_template_representation_declaration(self) -> str:
654
+ return '"filetype"' if self.code_model.for_test else "filetype"
655
+
656
+ @property
657
+ def instance_check_template(self) -> str:
658
+ return f"isinstance({{}}, {self.name})"
@@ -97,12 +97,9 @@ class Property(BaseModel): # pylint: disable=too-many-instance-attributes
97
97
  return self.is_discriminator and self.is_polymorphic and cast(ConstantType, self.type).value is None
98
98
 
99
99
  def type_annotation(self, *, is_operation_file: bool = False) -> str:
100
- types_type_annotation = self.type.type_annotation(is_operation_file=is_operation_file)
101
- if self.is_multipart_file_input:
102
- # we only support FileType or list of FileType
103
- types_type_annotation = types_type_annotation.replace("bytes", "FileType")
104
100
  if self.is_base_discriminator:
105
101
  return "str"
102
+ types_type_annotation = self.type.type_annotation(is_operation_file=is_operation_file)
106
103
  if self.optional and self.client_default_value is None:
107
104
  return f"Optional[{types_type_annotation}]"
108
105
  return types_type_annotation
@@ -115,9 +112,6 @@ class Property(BaseModel): # pylint: disable=too-many-instance-attributes
115
112
  *,
116
113
  client_default_value_declaration: Optional[str] = None,
117
114
  ) -> Any:
118
- if self.is_multipart_file_input:
119
- file_type_str = '"filetype"' if self.code_model.for_test else "filetype"
120
- return f"[{file_type_str}]" if self.type.type == "list" else file_type_str
121
115
  if self.client_default_value:
122
116
  client_default_value_declaration = self.get_declaration(self.client_default_value)
123
117
  # make sure there is no \n otherwise the json template will be invalid
@@ -156,8 +150,6 @@ class Property(BaseModel): # pylint: disable=too-many-instance-attributes
156
150
  "rest_discriminator" if self.is_discriminator else "rest_field",
157
151
  ImportType.LOCAL,
158
152
  )
159
- if self.is_multipart_file_input:
160
- file_import.add_submodule_import(".._vendor", "FileType", ImportType.LOCAL)
161
153
  return file_import
162
154
 
163
155
  @classmethod
@@ -66,7 +66,7 @@ def _sample_output_path(source_file_path: str) -> Path:
66
66
  return Path("")
67
67
 
68
68
 
69
- class JinjaSerializer(ReaderAndWriter): # pylint: disable=abstract-method
69
+ class JinjaSerializer(ReaderAndWriter):
70
70
  def __init__(
71
71
  self,
72
72
  code_model: CodeModel,
@@ -1,4 +1,4 @@
1
- # pylint: disable=too-many-lines,multiple-statements
1
+ # pylint: disable=too-many-lines
2
2
  # -------------------------------------------------------------------------
3
3
  # Copyright (c) Microsoft Corporation. All rights reserved.
4
4
  # Licensed under the MIT License. See License.txt in the project root for
@@ -23,7 +23,6 @@ from ..models import (
23
23
  BinaryType,
24
24
  BodyParameter,
25
25
  ParameterMethodLocation,
26
- RequestBuilderBodyParameter,
27
26
  OverloadedRequestBuilder,
28
27
  Property,
29
28
  RequestBuilderType,
@@ -218,7 +217,7 @@ def is_json_model_type(parameters: ParameterListType) -> bool:
218
217
  )
219
218
 
220
219
 
221
- class _BuilderBaseSerializer(Generic[BuilderType]): # pylint: disable=abstract-method
220
+ class _BuilderBaseSerializer(Generic[BuilderType]):
222
221
  def __init__(self, code_model: CodeModel, async_mode: bool) -> None:
223
222
  self.code_model = code_model
224
223
  self.async_mode = async_mode
@@ -391,7 +390,7 @@ class _BuilderBaseSerializer(Generic[BuilderType]): # pylint: disable=abstract-
391
390
  ############################## REQUEST BUILDERS ##############################
392
391
 
393
392
 
394
- class RequestBuilderSerializer(_BuilderBaseSerializer[RequestBuilderType]): # pylint: disable=abstract-method
393
+ class RequestBuilderSerializer(_BuilderBaseSerializer[RequestBuilderType]):
395
394
  def description_and_summary(self, builder: RequestBuilderType) -> List[str]:
396
395
  retval = super().description_and_summary(builder)
397
396
  retval += [
@@ -517,7 +516,7 @@ class RequestBuilderSerializer(_BuilderBaseSerializer[RequestBuilderType]): # p
517
516
  ############################## NORMAL OPERATIONS ##############################
518
517
 
519
518
 
520
- class _OperationSerializer(_BuilderBaseSerializer[OperationType]): # pylint: disable=abstract-method
519
+ class _OperationSerializer(_BuilderBaseSerializer[OperationType]):
521
520
  def description_and_summary(self, builder: OperationType) -> List[str]:
522
521
  retval = super().description_and_summary(builder)
523
522
  if builder.deprecated:
@@ -535,9 +534,9 @@ class _OperationSerializer(_BuilderBaseSerializer[OperationType]): # pylint: di
535
534
  return "response"
536
535
 
537
536
  def example_template(self, builder: OperationType) -> List[str]:
537
+ if self.code_model.options["models_mode"] in ("msrest", "dpg"):
538
+ return []
538
539
  retval = super().example_template(builder)
539
- if self.code_model.options["models_mode"] == "msrest":
540
- return retval
541
540
  for response in builder.responses:
542
541
  polymorphic_subtypes: List[ModelType] = []
543
542
  if not response.type:
@@ -842,14 +841,14 @@ class _OperationSerializer(_BuilderBaseSerializer[OperationType]): # pylint: di
842
841
  elif request_builder.overloads:
843
842
  seen_body_params = set()
844
843
  for overload in request_builder.overloads:
845
- body_param = cast(RequestBuilderBodyParameter, overload.parameters.body_parameter)
844
+ body_param = overload.parameters.body_parameter
846
845
  if body_param.client_name in seen_body_params:
847
846
  continue
848
847
  seen_body_params.add(body_param.client_name)
849
848
 
850
849
  retval.append(f" {body_param.client_name}={body_param.name_in_high_level_operation},")
851
850
  elif request_builder.parameters.has_body:
852
- body_param = cast(RequestBuilderBodyParameter, request_builder.parameters.body_parameter)
851
+ body_param = request_builder.parameters.body_parameter
853
852
  retval.append(f" {body_param.client_name}={body_param.name_in_high_level_operation},")
854
853
  retval.append(" headers=_headers,")
855
854
  retval.append(" params=_params,")
@@ -871,7 +870,7 @@ class _OperationSerializer(_BuilderBaseSerializer[OperationType]): # pylint: di
871
870
  )
872
871
  return retval
873
872
 
874
- def _call_request_builder_helper( # pylint: disable=too-many-statements
873
+ def _call_request_builder_helper(
875
874
  self,
876
875
  builder: OperationType,
877
876
  request_builder: RequestBuilderType,
@@ -1031,7 +1030,7 @@ class _OperationSerializer(_BuilderBaseSerializer[OperationType]): # pylint: di
1031
1030
  retval.append("deserialized = None")
1032
1031
  if builder.any_response_has_headers:
1033
1032
  retval.append("response_headers = {}")
1034
- if builder.has_response_body or builder.any_response_has_headers:
1033
+ if builder.has_response_body or builder.any_response_has_headers: # pylint: disable=too-many-nested-blocks
1035
1034
  if len(builder.responses) > 1:
1036
1035
  status_codes, res_headers, res_deserialization = [], [], []
1037
1036
  for status_code in builder.success_status_codes:
@@ -1173,7 +1172,7 @@ class OperationSerializer(_OperationSerializer[Operation]): ...
1173
1172
  PagingOperationType = TypeVar("PagingOperationType", bound=Union[PagingOperation, LROPagingOperation])
1174
1173
 
1175
1174
 
1176
- class _PagingOperationSerializer(_OperationSerializer[PagingOperationType]): # pylint: disable=abstract-method
1175
+ class _PagingOperationSerializer(_OperationSerializer[PagingOperationType]):
1177
1176
  def __init__(self, code_model: CodeModel, async_mode: bool) -> None:
1178
1177
  # for pylint reasons need to redefine init
1179
1178
  # probably because inheritance is going too deep
@@ -1458,7 +1457,7 @@ class LROOperationSerializer(_LROOperationSerializer[LROOperation]): ...
1458
1457
  class LROPagingOperationSerializer(
1459
1458
  _LROOperationSerializer[LROPagingOperation],
1460
1459
  _PagingOperationSerializer[LROPagingOperation],
1461
- ): # pylint: disable=abstract-method
1460
+ ):
1462
1461
  @property
1463
1462
  def _call_method(self) -> str:
1464
1463
  return "await " if self.async_mode else ""
@@ -124,7 +124,6 @@ class GeneralSerializer(BaseSerializer):
124
124
  file_import.add_submodule_import("typing", "Union", ImportType.STDLIB)
125
125
  file_import.add_submodule_import("typing", "Optional", ImportType.STDLIB)
126
126
  file_import.add_submodule_import("typing", "Mapping", ImportType.STDLIB)
127
- file_import.add_submodule_import("typing", "Sequence", ImportType.STDLIB)
128
127
  file_import.add_submodule_import("typing", "Dict", ImportType.STDLIB)
129
128
  file_import.add_submodule_import("typing", "Any", ImportType.STDLIB)
130
129
  file_import.add_submodule_import("typing", "List", ImportType.STDLIB)
@@ -183,12 +182,13 @@ class GeneralSerializer(BaseSerializer):
183
182
  def serialize_cross_language_definition_file(self) -> str:
184
183
  cross_langauge_def_dict = {
185
184
  f"{self.code_model.namespace}.models.{model.name}": model.cross_language_definition_id
186
- for model in self.code_model.model_types
185
+ for model in self.code_model.public_model_types
187
186
  }
188
187
  cross_langauge_def_dict.update(
189
188
  {
190
189
  f"{self.code_model.namespace}.models.{enum.name}": enum.cross_language_definition_id
191
190
  for enum in self.code_model.enums
191
+ if not enum.internal
192
192
  }
193
193
  )
194
194
  cross_langauge_def_dict.update(
@@ -194,6 +194,8 @@ class DpgModelSerializer(_ModelSerializer):
194
194
  )
195
195
 
196
196
  for model in self.code_model.model_types:
197
+ if model.base == "json":
198
+ continue
197
199
  file_import.merge(model.imports(is_operation_file=False))
198
200
  for prop in model.properties:
199
201
  file_import.merge(prop.imports())
@@ -1,4 +1,3 @@
1
- # pylint: disable=too-many-lines
2
1
  # -------------------------------------------------------------------------
3
2
  # Copyright (c) Microsoft Corporation. All rights reserved.
4
3
  # Licensed under the MIT License. See License.txt in the project root for
@@ -22,7 +21,6 @@ from ..models import (
22
21
  FileImport,
23
22
  )
24
23
  from .utils import get_namespace_config, get_namespace_from_package_name
25
- from ...utils import to_snake_case
26
24
 
27
25
  _LOGGER = logging.getLogger(__name__)
28
26
 
@@ -42,7 +40,7 @@ class SampleSerializer(BaseSerializer):
42
40
  self.operation = operation
43
41
  self.sample = sample
44
42
  self.file_name = file_name
45
- self.sample_params = {to_snake_case(k): v for k, v in sample.get("parameters", {}).items()}
43
+ self.sample_params = sample.get("parameters", {})
46
44
 
47
45
  def _imports(self) -> FileImportSerializer:
48
46
  imports = FileImport(self.code_model)
@@ -66,8 +64,8 @@ class SampleSerializer(BaseSerializer):
66
64
  "AzureKeyCredential",
67
65
  ImportType.SDKCORE,
68
66
  )
69
- for param in self.operation.parameters.positional:
70
- if not param.client_default_value and not param.optional and param.client_name in self.sample_params:
67
+ for param in self.operation.parameters.positional + self.operation.parameters.keyword_only:
68
+ if not param.client_default_value and not param.optional and param.wire_name in self.sample_params:
71
69
  imports.merge(param.type.imports_for_sample())
72
70
  return FileImportSerializer(imports, True)
73
71
 
@@ -80,15 +78,19 @@ class SampleSerializer(BaseSerializer):
80
78
  elif isinstance(credential_type, KeyCredentialType):
81
79
  special_param.update({"credential": 'AzureKeyCredential(key=os.getenv("AZURE_KEY"))'})
82
80
 
83
- params_positional = [
84
- p for p in self.code_model.clients[0].parameters.positional if not (p.optional or p.client_default_value)
81
+ params = [
82
+ p
83
+ for p in (
84
+ self.code_model.clients[0].parameters.positional + self.code_model.clients[0].parameters.keyword_only
85
+ )
86
+ if not (p.optional or p.client_default_value)
85
87
  ]
86
88
  client_params = {
87
89
  p.client_name: special_param.get(
88
90
  p.client_name,
89
- f'"{self.sample_params.get(p.client_name) or p.client_name.upper()}"',
91
+ f'"{self.sample_params.get(p.wire_name) or p.client_name.upper()}"',
90
92
  )
91
- for p in params_positional
93
+ for p in params
92
94
  }
93
95
 
94
96
  return client_params
@@ -103,15 +105,18 @@ class SampleSerializer(BaseSerializer):
103
105
 
104
106
  # prepare operation parameters
105
107
  def _operation_params(self) -> Dict[str, Any]:
106
- params_positional = [p for p in self.operation.parameters.positional if not p.client_default_value]
108
+ params = [
109
+ p
110
+ for p in (self.operation.parameters.positional + self.operation.parameters.keyword_only)
111
+ if not p.client_default_value
112
+ ]
107
113
  failure_info = "fail to find required param named {}"
108
114
  operation_params = {}
109
- for param in params_positional:
110
- name = param.client_name
111
- param_value = self.sample_params.get(name)
115
+ for param in params:
112
116
  if not param.optional:
117
+ param_value = self.sample_params.get(param.wire_name)
113
118
  if not param_value:
114
- raise Exception(failure_info.format(name)) # pylint: disable=broad-exception-raised
119
+ raise Exception(failure_info.format(param.client_name)) # pylint: disable=broad-exception-raised
115
120
  operation_params[param.client_name] = self.handle_param(param, param_value)
116
121
  return operation_params
117
122
 
@@ -145,7 +150,7 @@ class SampleSerializer(BaseSerializer):
145
150
  name = self.sample.get("x-ms-original-file", "")
146
151
  if "specification" in name:
147
152
  return "specification" + name.split("specification")[-1]
148
- return ""
153
+ return name if self.code_model.options["from_typespec"] else ""
149
154
 
150
155
  def serialize(self) -> str:
151
156
  operation_result, return_var = self._operation_result()