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

Validate python intergration tests. #5617

Merged
merged 9 commits into from
Oct 18, 2024
Merged
3 changes: 1 addition & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Fixed an issue where when generating Go code the deserializer for unions was using `CodeClass` as a filter and not `CodeInterface`. [#4844](https://github.com/microsoft/kiota/issues/4844)
- Fixes mapping of `int16` format to the `integer` type rather than `double` when the type is `integer` or `number` [#5611](https://github.com/microsoft/kiota/issues/5611)
- Fixes typing inconsistencies in generated code and libraries in Python [kiota-python#333](https://github.com/microsoft/kiota-python/issues/333)

## [1.19.1] - 2024-10-11

Expand Down Expand Up @@ -1484,5 +1485,3 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- Initial GitHub release


14 changes: 7 additions & 7 deletions it/python/requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -98,19 +98,19 @@ httpx[http2]==0.27.2

hyperframe==6.0.1 ; python_full_version >= '3.6.1'

microsoft-kiota-abstractions==1.3.3
microsoft-kiota-abstractions==1.4.6

microsoft-kiota-authentication-azure==1.1.0
microsoft-kiota-authentication-azure==1.4.6

microsoft-kiota-http==1.3.4
microsoft-kiota-http==1.4.6

microsoft-kiota-serialization-json==1.3.3
microsoft-kiota-serialization-json==1.4.6

microsoft-kiota-serialization-text==1.0.0
microsoft-kiota-serialization-text==1.4.6

microsoft-kiota-serialization-form==0.1.1
microsoft-kiota-serialization-form==1.4.6

microsoft-kiota-serialization-multipart==0.1.0
microsoft-kiota-serialization-multipart==1.4.6

msal==1.31.0

Expand Down
38 changes: 22 additions & 16 deletions src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
if (codeElement.Parent is not CodeClass parentClass) throw new InvalidOperationException("the parent of a method should be a class");

var returnType = conventions.GetTypeString(codeElement.ReturnType, codeElement, true, writer);
var returnTypeIsEnum = codeElement.ReturnType is CodeType { TypeDefinition: CodeEnum };
var isVoid = NoneKeyword.Equals(returnType, StringComparison.OrdinalIgnoreCase);
if (parentClass.IsOfKind(CodeClassKind.Model) && (codeElement.IsOfKind(CodeMethodKind.Setter) || codeElement.IsOfKind(CodeMethodKind.Getter) || codeElement.IsOfKind(CodeMethodKind.Constructor)))
{
Expand All @@ -40,7 +41,7 @@
var requestParams = new RequestParams(requestBodyParam, requestConfigParam, requestContentType);
if (!codeElement.IsOfKind(CodeMethodKind.Setter) &&
!(codeElement.IsOfKind(CodeMethodKind.Constructor) && parentClass.IsOfKind(CodeClassKind.RequestBuilder)))
foreach (var parameter in codeElement.Parameters.Where(static x => !x.Optional).OrderBy(static x => x.Name))

Check warning on line 44 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Loop should be simplified by calling Select(parameter => parameter.Name)) (https://rules.sonarsource.com/csharp/RSPEC-3267)
{
var parameterName = parameter.Name;
writer.StartBlock($"if {parameterName} is None:");
Expand Down Expand Up @@ -79,7 +80,7 @@
writer.CloseBlock(string.Empty);
break;
case CodeMethodKind.RequestExecutor:
WriteRequestExecutorBody(codeElement, requestParams, parentClass, isVoid, returnType, writer);
WriteRequestExecutorBody(codeElement, requestParams, parentClass, isVoid, returnType, writer, returnTypeIsEnum);
writer.CloseBlock(string.Empty);
break;
case CodeMethodKind.Getter:
Expand Down Expand Up @@ -112,7 +113,7 @@
break;
}
}
private void WriteRawUrlBuilderBody(CodeClass parentClass, CodeMethod codeElement, LanguageWriter writer)

Check warning on line 116 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Make 'WriteRawUrlBuilderBody' a static method. (https://rules.sonarsource.com/csharp/RSPEC-2325)
{
var rawUrlParameter = codeElement.Parameters.OfKind(CodeParameterKind.RawUrl) ?? throw new InvalidOperationException("RawUrlBuilder method should have a RawUrl parameter");
var requestAdapterProperty = parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter) ?? throw new InvalidOperationException("RawUrlBuilder method should have a RequestAdapter property");
Expand All @@ -135,7 +136,7 @@
writer.WriteLine($"return {parentClass.Name}()");
}
private const string ResultVarName = "result";
private void WriteFactoryMethodBodyForUnionModel(CodeMethod codeElement, CodeClass parentClass, CodeParameter parseNodeParameter, LanguageWriter writer)

Check warning on line 139 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 20 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
writer.WriteLine($"{ResultVarName} = {parentClass.Name}()");
var includeElse = false;
Expand Down Expand Up @@ -164,7 +165,7 @@
}
writer.WriteLine($"return {ResultVarName}");
}
private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, CodeClass parentClass, CodeParameter parseNodeParameter, LanguageWriter writer)

Check warning on line 168 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
writer.WriteLine($"{ResultVarName} = {parentClass.Name}()");
var includeElse = false;
Expand Down Expand Up @@ -212,9 +213,10 @@
if (parentClass.DiscriminatorInformation.ShouldWriteParseNodeCheck && !parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForIntersectionType)
{
writer.StartBlock("try:");
writer.WriteLine($"{DiscriminatorMappingVarName} = {parseNodeParameter.Name}.get_child_node(\"{parentClass.DiscriminatorInformation.DiscriminatorPropertyName}\").get_str_value()");
writer.WriteLine($"child_node = {parseNodeParameter.Name}.get_child_node(\"{parentClass.DiscriminatorInformation.DiscriminatorPropertyName}\")");
writer.WriteLine($"{DiscriminatorMappingVarName} = child_node.get_str_value() if child_node else {NoneKeyword}");
writer.DecreaseIndent();
writer.StartBlock($"except AttributeError:");
writer.StartBlock("except AttributeError:");
writer.WriteLine($"{DiscriminatorMappingVarName} = {NoneKeyword}");
writer.DecreaseIndent();
}
Expand Down Expand Up @@ -324,7 +326,7 @@
return _SetterAccessProperties;
}
}
private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMethod, LanguageWriter writer, bool inherits)

Check warning on line 329 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 28 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
if (inherits && !parentClass.IsOfKind(CodeClassKind.Model))
{
Expand Down Expand Up @@ -373,7 +375,7 @@
writer.IncreaseIndent();
}
}
private void WriteDirectAccessProperties(CodeClass parentClass, LanguageWriter writer)

Check warning on line 378 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 20 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
foreach (var propWithDefault in parentClass.GetPropertiesOfKind(DirectAccessProperties)
.Where(static x => !string.IsNullOrEmpty(x.DefaultValue) && !NoneKeyword.Equals(x.DefaultValue, StringComparison.Ordinal))
Expand All @@ -390,7 +392,7 @@
conventions.WriteInLineDescription(propWithDefault, writer);
if (parentClass.IsOfKind(CodeClassKind.Model))
{
writer.WriteLine($"{propWithDefault.Name}: {(propWithDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithDefault.Type.IsNullable ? "]" : string.Empty)} = {defaultValue}");

Check warning on line 395 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Define a constant instead of using this literal 'Optional[' 7 times. (https://rules.sonarsource.com/csharp/RSPEC-1192)
writer.WriteLine();
}
else
Expand Down Expand Up @@ -427,7 +429,7 @@
}
}
private const string NoneKeyword = "None";
private void WriteSetterAccessPropertiesWithoutDefaults(CodeClass parentClass, LanguageWriter writer)

Check warning on line 432 in src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
foreach (var propWithoutDefault in parentClass.GetPropertiesOfKind(SetterAccessProperties)
.Where(static x => string.IsNullOrEmpty(x.DefaultValue) || NoneKeyword.Equals(x.DefaultValue, StringComparison.Ordinal))
Expand Down Expand Up @@ -527,11 +529,12 @@
.OrderBy(static x => x)
.ToArray();
var propertiesNamesAsConditions = propertiesNames
.Select(static x => $"{x}")
.Aggregate(static (x, y) => $"self.{x} or self.{y}");
.Select(static x => $"self.{x}")
.Aggregate(static (x, y) => $"{x} or {y}");
writer.StartBlock($"if {propertiesNamesAsConditions}:");
var propertiesNamesAsArgument = propertiesNames
.Aggregate(static (x, y) => $"self.{x}, self.{y}");
.Select(static x => $"self.{x}")
.Aggregate(static (x, y) => $"{x}, {y}");
writer.WriteLine($"return ParseNodeHelper.merge_deserializers_for_intersection_wrapper({propertiesNamesAsArgument})");
writer.DecreaseIndent();
}
Expand All @@ -556,7 +559,8 @@
}
writer.WriteLine("return fields");
}
private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requestParams, CodeClass parentClass, bool isVoid, string returnType, LanguageWriter writer)
private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requestParams, CodeClass parentClass,
bool isVoid, string returnType, LanguageWriter writer, bool isEnum)
{
if (codeElement.HttpMethod == null) throw new InvalidOperationException("http method cannot be null");

Expand All @@ -578,8 +582,8 @@
writer.WriteLine(")");
var isStream = conventions.StreamTypeName.Equals(returnType, StringComparison.OrdinalIgnoreCase);
var returnTypeWithoutCollectionSymbol = GetReturnTypeWithoutCollectionSymbol(codeElement, returnType);
var genericTypeForSendMethod = GetSendRequestMethodName(isVoid, isStream, codeElement.ReturnType.IsCollection, returnTypeWithoutCollectionSymbol);
var newFactoryParameter = GetTypeFactory(isVoid, isStream, returnTypeWithoutCollectionSymbol);
var genericTypeForSendMethod = GetSendRequestMethodName(isVoid, isStream, codeElement.ReturnType.IsCollection, returnTypeWithoutCollectionSymbol, isEnum);
var newFactoryParameter = GetTypeFactory(isVoid, isStream, returnTypeWithoutCollectionSymbol, isEnum);
var errorMappingVarName = NoneKeyword;
if (codeElement.ErrorMappings.Any())
{
Expand Down Expand Up @@ -695,7 +699,8 @@
var propertiesNames = complexProperties
.Select(static x => x.Name)
.OrderBy(static x => x, StringComparer.OrdinalIgnoreCase)
.Aggregate(static (x, y) => $"self.{x}, self.{y}");
.Select(static x => $"self.{x}")
.Aggregate(static (x, y) => $"{x}, {y}");
writer.WriteLine($"writer.{GetSerializationMethodName(complexProperties[0].Type)}({NoneKeyword}, {propertiesNames})");
if (includeElse)
{
Expand Down Expand Up @@ -803,22 +808,23 @@
_ => "write_object_value",
};
}
private string GetTypeFactory(bool isVoid, bool isStream, string returnType)
private string GetTypeFactory(bool isVoid, bool isStream, string returnType, bool isEnum)
{
if (isVoid) return string.Empty;
if (isStream || conventions.IsPrimitiveType(returnType)) return $" \"{returnType}\",";
if (isStream || conventions.IsPrimitiveType(returnType) || isEnum) return $" \"{returnType}\",";
return $" {returnType},";
}
private string GetSendRequestMethodName(bool isVoid, bool isStream, bool isCollection, string returnType)
private string GetSendRequestMethodName(bool isVoid, bool isStream, bool isCollection, string returnType,
bool isEnum)
{
if (isVoid) return "send_no_response_content_async";
if (isCollection)
{
if (conventions.IsPrimitiveType(returnType)) return "send_collection_of_primitive_async";
return $"send_collection_async";
if (conventions.IsPrimitiveType(returnType) || isEnum) return "send_collection_of_primitive_async";
return "send_collection_async";
}

if (isStream || conventions.IsPrimitiveType(returnType)) return "send_primitive_async";
if (isStream || conventions.IsPrimitiveType(returnType) || isEnum) return "send_primitive_async";
return "send_async";
}
private void UpdateRequestInformationFromRequestBody(CodeMethod codeElement, RequestParams requestParams, CodeProperty requestAdapterProperty, LanguageWriter writer)
Expand Down
2 changes: 1 addition & 1 deletion src/Kiota.Builder/Writers/Python/CodePropertyWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
{
_codeUsingWriter = new(clientNamespaceName);
}
public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter writer)

Check warning on line 13 in src/Kiota.Builder/Writers/Python/CodePropertyWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
ArgumentNullException.ThrowIfNull(codeElement);
ArgumentNullException.ThrowIfNull(writer);
Expand All @@ -34,7 +34,7 @@
break;
case CodePropertyKind.QueryParameters:
returnType = $"{codeElement.Parent?.Parent?.Name}.{codeElement.Type.Name}";
goto case CodePropertyKind.Headers;

Check warning on line 37 in src/Kiota.Builder/Writers/Python/CodePropertyWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Remove this use of 'goto'. (https://rules.sonarsource.com/csharp/RSPEC-907)
case CodePropertyKind.Headers:
case CodePropertyKind.Options:
case CodePropertyKind.QueryParameter:
Expand All @@ -45,7 +45,7 @@
break;
case CodePropertyKind.ErrorMessageOverride when parentClass.IsErrorDefinition:
writer.WriteLine("@property");
writer.StartBlock($"def {codeElement.Name}(self) -> {codeElement.Type.Name}:");
writer.StartBlock($"def {codeElement.Name}(self) -> Optional[{codeElement.Type.Name}]:");
conventions.WriteLongDescription(codeElement, writer);
if (parentClass.GetPrimaryMessageCodePath(static x => x.Name.ToFirstCharacterLowerCase(),
static x => x.Name.ToSnakeCase()) is string primaryMessageCodePath &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1159,7 +1159,8 @@ public void WritesModelFactoryBodyForInheritedModels()
writer.Write(method);
var result = tw.ToString();
Assert.Contains("try:", result);
Assert.Contains("mapping_value = parse_node.get_child_node(\"@odata.type\").get_str_value()", result);
Assert.Contains("child_node = parse_node.get_child_node(\"@odata.type\")", result);
Assert.Contains("mapping_value = child_node.get_str_value() if child_node else None", result);
Assert.Contains("except AttributeError:", result);
Assert.Contains("mapping_value = None", result);
Assert.Contains("if mapping_value and mapping_value.casefold() == \"ns.childclass\".casefold()", result);
Expand Down Expand Up @@ -1194,7 +1195,8 @@ public void WritesModelFactoryBodyForUnionModels()
writer.Write(factoryMethod);
var result = tw.ToString();
Assert.Contains("try:", result);
Assert.Contains("mapping_value = parse_node.get_child_node(\"@odata.type\").get_str_value()", result);
Assert.Contains("child_node = parse_node.get_child_node(\"@odata.type\")", result);
Assert.Contains("mapping_value = child_node.get_str_value() if child_node else None", result);
Assert.Contains("except AttributeError:", result);
Assert.Contains("mapping_value = None", result);
Assert.Contains("result = UnionTypeWrapper()", result);
Expand Down
Loading