From 46b72555509f5d9428e434307fc0af9b96763e68 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Tue, 3 Oct 2023 19:08:36 +0100 Subject: [PATCH 1/6] [Python] Move (most of) the name mangling logic into the refiner --- it/compare-generation.ps1 | 10 +- .../Refiners/CommonLanguageRefiner.cs | 2 +- src/Kiota.Builder/Refiners/PythonRefiner.cs | 63 +++++++- .../Python/CodeClassDeclarationWriter.cs | 4 +- .../Writers/Python/CodeEnumWriter.cs | 4 +- .../Writers/Python/CodeMethodWriter.cs | 137 +++++++++--------- .../Writers/Python/CodePropertyWriter.cs | 6 +- .../Writers/Python/CodeUsingWriter.cs | 6 +- .../Writers/Python/PythonConventionService.cs | 14 +- .../Python/PythonRelativeImportManager.cs | 10 +- .../Writers/Python/CodeUsingWriterTests.cs | 4 +- 11 files changed, 159 insertions(+), 101 deletions(-) diff --git a/it/compare-generation.ps1 b/it/compare-generation.ps1 index 58753b89c1..cd738e5908 100755 --- a/it/compare-generation.ps1 +++ b/it/compare-generation.ps1 @@ -61,15 +61,15 @@ else { $tmpFolder1 = New-TemporaryDirectory $tmpFolder2 = New-TemporaryDirectory -Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow -Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow +Start-Process "./publish/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow +Start-Process "./src/kiota/bin/Debug/net7.0/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow # Remove variable output files -Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") +Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log") } -Remove-Item (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") +Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log") } @@ -84,6 +84,8 @@ Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString2)) Write-Output "Folder 1: $tmpFolder1" Write-Output "Folder 2: $tmpFolder2" +diff -r --color $tmpFolder1 $tmpFolder2 + if ($HashString1 -eq $HashString2) { Write-Output "The content of the folders is identical" diff --git a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs index ba248fa6c8..c3c6456271 100644 --- a/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs +++ b/src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs @@ -1309,7 +1309,7 @@ public void AddQueryParameterMapperMethod(CodeElement currentElement, string met { if (currentElement is CodeClass currentClass && currentClass.IsOfKind(CodeClassKind.QueryParameters) && - currentClass.Properties.Any(static x => x.IsNameEscaped)) + currentClass.Properties.Any(static x => x.IsNameEscaped && !x.SerializationName.Equals(x.Name, StringComparison.Ordinal))) { var method = currentClass.AddMethod(new CodeMethod { diff --git a/src/Kiota.Builder/Refiners/PythonRefiner.cs b/src/Kiota.Builder/Refiners/PythonRefiner.cs index 46c7d678a4..66950b956c 100644 --- a/src/Kiota.Builder/Refiners/PythonRefiner.cs +++ b/src/Kiota.Builder/Refiners/PythonRefiner.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Data.Common; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -16,6 +17,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance return Task.Run(() => { cancellationToken.ThrowIfCancellationRequested(); + CorrectCommonNames(generatedCode); RemoveMethodByKind(generatedCode, CodeMethodKind.RawUrlConstructor); AddDefaultImports(generatedCode, defaultUsingEvaluators); DisableActionOf(generatedCode, @@ -43,7 +45,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance AddPropertiesAndMethodTypesImports(generatedCode, true, true, true, codeTypeFilter); AddParsableImplementsForModelClasses(generatedCode, "Parsable"); cancellationToken.ThrowIfCancellationRequested(); - ReplaceBinaryByNativeType(generatedCode, "bytes", string.Empty); + ReplaceBinaryByNativeType(generatedCode, "bytes", string.Empty, true); ReplaceReservedNames( generatedCode, new PythonReservedNamesProvider(), @@ -68,10 +70,12 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance MoveClassesWithNamespaceNamesUnderNamespace(generatedCode); ReplacePropertyNames(generatedCode, new() { + CodePropertyKind.AdditionalData, CodePropertyKind.Custom, CodePropertyKind.QueryParameter, + CodePropertyKind.RequestBuilder, }, - static s => s.ToSnakeCase()); + static s => s.ToFirstCharacterLowerCase().ToSnakeCase()); AddParentClassToErrorClasses( generatedCode, "APIError", @@ -114,7 +118,9 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance $"{AbstractionsPackageName}.serialization.ParseNodeFactoryRegistry" }); cancellationToken.ThrowIfCancellationRequested(); AddQueryParameterMapperMethod( - generatedCode + generatedCode, + "get_query_parameter", + "original_name" ); AddDiscriminatorMappingsUsingsToParentClasses( generatedCode, @@ -158,6 +164,56 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance new (static x => x is CodeClass { OriginalComposedType: CodeIntersectionType intersectionType } && intersectionType.Types.Any(static y => !y.IsExternal) && intersectionType.DiscriminatorInformation.HasBasicDiscriminatorInformation, $"{AbstractionsPackageName}.serialization", "ParseNodeHelper"), }; + + private static void CorrectCommonNames(CodeElement currentElement) + { + if (currentElement is CodeMethod m && + currentElement.Parent is CodeClass parentClassM) + { + parentClassM.RenameChildElement(m.Name, m.Name.ToFirstCharacterLowerCase().ToSnakeCase()); + + foreach (var param in m.Parameters) + { + param.Name = param.Name.ToFirstCharacterLowerCase().ToSnakeCase(); + } + } + else if (currentElement is CodeClass c) + { + c.Name = c.Name.ToFirstCharacterUpperCase(); + } + else if (currentElement is CodeProperty p && + (p.IsOfKind(CodePropertyKind.RequestAdapter) || + p.IsOfKind(CodePropertyKind.PathParameters) || + p.IsOfKind(CodePropertyKind.QueryParameters) || + p.IsOfKind(CodePropertyKind.UrlTemplate)) && + currentElement.Parent is CodeClass parentClassP) + { + if (p.SerializationName != null) + p.SerializationName = p.Name; + + parentClassP.RenameChildElement(p.Name, p.Name.ToFirstCharacterLowerCase().ToSnakeCase()); + } + else if (currentElement is CodeIndexer i) + { + i.IndexParameter.Name = i.IndexParameter.Name.ToFirstCharacterLowerCase().ToSnakeCase(); + } + else if (currentElement is CodeEnum e) + { + foreach (var option in e.Options) + { + if (!string.IsNullOrEmpty(option.Name) && Char.IsLower(option.Name[0])) + { + if (string.IsNullOrEmpty(option.SerializationName)) + { + option.SerializationName = option.Name; + } + option.Name = option.Name.ToCamelCase().ToFirstCharacterUpperCase(); + } + } + } + + CrawlTree(currentElement, element => CorrectCommonNames(element)); + } private static void CorrectImplements(ProprietableBlockDeclaration block) { block.Implements.Where(x => "IAdditionalDataHolder".Equals(x.Name, StringComparison.OrdinalIgnoreCase)).ToList().ForEach(x => x.Name = x.Name[1..]); // skipping the I @@ -184,6 +240,7 @@ private static void CorrectPropertyType(CodeProperty currentProperty) if (!string.IsNullOrEmpty(currentProperty.DefaultValue)) currentProperty.DefaultValue = "{}"; } + currentProperty.Type.Name = currentProperty.Type.Name.ToFirstCharacterUpperCase(); CorrectCoreTypes(currentProperty.Parent as CodeClass, DateTypesReplacements, currentProperty.Type); } private static void CorrectMethodType(CodeMethod currentMethod) diff --git a/src/Kiota.Builder/Writers/Python/CodeClassDeclarationWriter.cs b/src/Kiota.Builder/Writers/Python/CodeClassDeclarationWriter.cs index 1c745b1fe5..9d40d35699 100644 --- a/src/Kiota.Builder/Writers/Python/CodeClassDeclarationWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodeClassDeclarationWriter.cs @@ -35,13 +35,13 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit } } - var abcClass = !codeElement.Implements.Any() ? string.Empty : $"{codeElement.Implements.Select(static x => x.Name.ToFirstCharacterUpperCase()).Aggregate((x, y) => x + ", " + y)}"; + var abcClass = !codeElement.Implements.Any() ? string.Empty : $"{codeElement.Implements.Select(static x => x.Name).Aggregate((x, y) => x + ", " + y)}"; var derivation = codeElement.Inherits is CodeType inheritType && conventions.GetTypeString(inheritType, codeElement) is string inheritSymbol && !string.IsNullOrEmpty(inheritSymbol) ? inheritSymbol : abcClass; - writer.WriteLine($"class {codeElement.Name.ToFirstCharacterUpperCase()}({derivation}):"); + writer.WriteLine($"class {codeElement.Name}({derivation}):"); writer.IncreaseIndent(); if (codeElement.Parent is CodeClass parent) { diff --git a/src/Kiota.Builder/Writers/Python/CodeEnumWriter.cs b/src/Kiota.Builder/Writers/Python/CodeEnumWriter.cs index 9ef0f100c6..a2098d947b 100644 --- a/src/Kiota.Builder/Writers/Python/CodeEnumWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodeEnumWriter.cs @@ -14,7 +14,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write ArgumentNullException.ThrowIfNull(writer); writer.WriteLine("from enum import Enum"); writer.WriteLine(); - writer.WriteLine($"class {codeElement.Name.ToFirstCharacterUpperCase()}(str, Enum):"); + writer.WriteLine($"class {codeElement.Name}(str, Enum):"); writer.IncreaseIndent(); if (!codeElement.Options.Any()) { @@ -25,7 +25,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write codeElement.Options.ToList().ForEach(x => { conventions.WriteInLineDescription(x.Documentation.Description, writer); - writer.WriteLine($"{x.Name.ToFirstCharacterUpperCase()} = \"{x.WireName}\","); + writer.WriteLine($"{x.Name} = \"{x.WireName}\","); }); } } diff --git a/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs b/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs index 40761c5eca..65b0ec8c4a 100644 --- a/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodeMethodWriter.cs @@ -41,7 +41,7 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri !(codeElement.IsOfKind(CodeMethodKind.Constructor) && parentClass.IsOfKind(CodeClassKind.RequestBuilder))) foreach (var parameter in codeElement.Parameters.Where(static x => !x.Optional).OrderBy(static x => x.Name)) { - var parameterName = parameter.Name.ToSnakeCase(); + var parameterName = parameter.Name; writer.StartBlock($"if not {parameterName}:"); writer.WriteLine($"raise TypeError(\"{parameterName} cannot be null.\")"); writer.DecreaseIndent(); @@ -113,7 +113,7 @@ private void WriteRawUrlBuilderBody(CodeClass parentClass, CodeMethod codeElemen { 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"); - writer.WriteLine($"return {parentClass.Name.ToFirstCharacterUpperCase()}(self.{requestAdapterProperty.Name.ToSnakeCase()}, {rawUrlParameter.Name.ToSnakeCase()})"); + writer.WriteLine($"return {parentClass.Name}(self.{requestAdapterProperty.Name}, {rawUrlParameter.Name})"); } private const string DiscriminatorMappingVarName = "mapping_value"; @@ -126,15 +126,15 @@ private void WriteFactoryMethodBodyForInheritedModel(CodeClass parentClass, Lang writer.StartBlock($"if {DiscriminatorMappingVarName} and {DiscriminatorMappingVarName}.casefold() == \"{mappedType.Key}\".casefold():"); var mappedTypeName = mappedType.Value.AllTypes.First().Name; _codeUsingWriter.WriteDeferredImport(parentClass, mappedTypeName, writer); - writer.WriteLine($"return {mappedTypeName.ToFirstCharacterUpperCase()}()"); + writer.WriteLine($"return {mappedTypeName}()"); writer.DecreaseIndent(); } - writer.WriteLine($"return {parentClass.Name.ToFirstCharacterUpperCase()}()"); + writer.WriteLine($"return {parentClass.Name}()"); } private const string ResultVarName = "result"; private void WriteFactoryMethodBodyForUnionModel(CodeMethod codeElement, CodeClass parentClass, CodeParameter parseNodeParameter, LanguageWriter writer) { - writer.WriteLine($"{ResultVarName} = {parentClass.Name.ToFirstCharacterUpperCase()}()"); + writer.WriteLine($"{ResultVarName} = {parentClass.Name}()"); var includeElse = false; foreach (var property in parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .OrderBy(static x => x, CodePropertyTypeForwardComparer) @@ -146,14 +146,14 @@ private void WriteFactoryMethodBodyForUnionModel(CodeMethod codeElement, CodeCla var mappedType = parentClass.DiscriminatorInformation.DiscriminatorMappings.FirstOrDefault(x => x.Value.Name.Equals(propertyType.Name, StringComparison.OrdinalIgnoreCase)); writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if {DiscriminatorMappingVarName} and {DiscriminatorMappingVarName}.casefold() == \"{mappedType.Key}\".casefold():"); _codeUsingWriter.WriteDeferredImport(parentClass, propertyType.Name, writer); - writer.WriteLine($"{ResultVarName}.{property.Name.ToSnakeCase()} = {propertyType.Name.ToFirstCharacterUpperCase()}()"); + writer.WriteLine($"{ResultVarName}.{property.Name} = {propertyType.Name}()"); writer.DecreaseIndent(); } else if (propertyType.TypeDefinition is CodeClass && propertyType.IsCollection || propertyType.TypeDefinition is null || propertyType.TypeDefinition is CodeEnum) { - var valueVarName = $"{property.Name.ToSnakeCase()}_value"; - writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if {valueVarName} := {parseNodeParameter.Name.ToSnakeCase()}.{GetDeserializationMethodName(propertyType, codeElement, parentClass)}:"); - writer.WriteLine($"{ResultVarName}.{property.Name.ToSnakeCase()} = {valueVarName}"); + var valueVarName = $"{property.Name}_value"; + writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if {valueVarName} := {parseNodeParameter.Name}.{GetDeserializationMethodName(propertyType, codeElement, parentClass)}:"); + writer.WriteLine($"{ResultVarName}.{property.Name} = {valueVarName}"); writer.DecreaseIndent(); } if (!includeElse) @@ -163,7 +163,7 @@ private void WriteFactoryMethodBodyForUnionModel(CodeMethod codeElement, CodeCla } private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, CodeClass parentClass, CodeParameter parseNodeParameter, LanguageWriter writer) { - writer.WriteLine($"{ResultVarName} = {parentClass.Name.ToFirstCharacterUpperCase()}()"); + writer.WriteLine($"{ResultVarName} = {parentClass.Name}()"); var includeElse = false; foreach (var property in parentClass.GetPropertiesOfKind(CodePropertyKind.Custom) .Where(static x => x.Type is not CodeType propertyType || propertyType.IsCollection || propertyType.TypeDefinition is not CodeClass) @@ -172,9 +172,9 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, { if (property.Type is CodeType propertyType) { - var valueVarName = $"{property.Name.ToSnakeCase()}_value"; - writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if {valueVarName} := {parseNodeParameter.Name.ToSnakeCase()}.{GetDeserializationMethodName(propertyType, codeElement, parentClass)}:"); - writer.WriteLine($"{ResultVarName}.{property.Name.ToSnakeCase()} = {valueVarName}"); + var valueVarName = $"{property.Name}_value"; + writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if {valueVarName} := {parseNodeParameter.Name}.{GetDeserializationMethodName(propertyType, codeElement, parentClass)}:"); + writer.WriteLine($"{ResultVarName}.{property.Name} = {valueVarName}"); writer.DecreaseIndent(); } if (!includeElse) @@ -193,7 +193,7 @@ private void WriteFactoryMethodBodyForIntersectionModel(CodeMethod codeElement, foreach (var property in complexProperties) { _codeUsingWriter.WriteDeferredImport(parentClass, property.Item2.Name, writer); - writer.WriteLine($"{ResultVarName}.{property.Item1.Name.ToSnakeCase()} = {property.Item2.Name.ToFirstCharacterUpperCase()}()"); + writer.WriteLine($"{ResultVarName}.{property.Item1.Name} = {property.Item2.Name}()"); } if (includeElse) { @@ -209,7 +209,7 @@ private void WriteFactoryMethodBody(CodeMethod codeElement, CodeClass parentClas if (parentClass.DiscriminatorInformation.ShouldWriteParseNodeCheck && !parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForIntersectionType) { writer.StartBlock("try:"); - writer.WriteLine($"{DiscriminatorMappingVarName} = {parseNodeParameter.Name.ToSnakeCase()}.get_child_node(\"{parentClass.DiscriminatorInformation.DiscriminatorPropertyName}\").get_str_value()"); + writer.WriteLine($"{DiscriminatorMappingVarName} = {parseNodeParameter.Name}.get_child_node(\"{parentClass.DiscriminatorInformation.DiscriminatorPropertyName}\").get_str_value()"); writer.DecreaseIndent(); writer.StartBlock($"except AttributeError:"); writer.WriteLine($"{DiscriminatorMappingVarName} = None"); @@ -222,7 +222,7 @@ private void WriteFactoryMethodBody(CodeMethod codeElement, CodeClass parentClas else if (parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForIntersectionType) WriteFactoryMethodBodyForIntersectionModel(codeElement, parentClass, parseNodeParameter, writer); else - writer.WriteLine($"return {parentClass.Name.ToFirstCharacterUpperCase()}()"); + writer.WriteLine($"return {parentClass.Name}()"); } private void WriteIndexerBody(CodeMethod codeElement, CodeClass parentClass, string returnType, LanguageWriter writer) { @@ -230,7 +230,7 @@ private void WriteIndexerBody(CodeMethod codeElement, CodeClass parentClass, str if (parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters) is CodeProperty pathParametersProperty && codeElement.OriginalIndexer != null) conventions.AddParametersAssignment(writer, pathParametersProperty.Type, $"self.{pathParametersProperty.Name}", - (codeElement.OriginalIndexer.IndexParameter.Type, codeElement.OriginalIndexer.IndexParameter.SerializationName, codeElement.OriginalIndexer.IndexParameter.Name.ToSnakeCase())); + (codeElement.OriginalIndexer.IndexParameter.Type, codeElement.OriginalIndexer.IndexParameter.SerializationName, codeElement.OriginalIndexer.IndexParameter.Name)); conventions.AddRequestBuilderBody(parentClass, returnType, writer, conventions.TempDictionaryVarName); } private void WriteRequestBuilderWithParametersBody(CodeMethod codeElement, CodeClass parentClass, string returnType, LanguageWriter writer) @@ -244,7 +244,7 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me { if (parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter) is not CodeProperty requestAdapterProperty) return; var backingStoreParameter = method.Parameters.OfKind(CodeParameterKind.BackingStore); - var requestAdapterPropertyName = requestAdapterProperty.Name.ToSnakeCase(); + var requestAdapterPropertyName = requestAdapterProperty.Name; var pathParametersProperty = parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters); WriteSerializationRegistration(method.SerializerModules, writer, "register_default_serializer"); WriteSerializationRegistration(method.DeserializerModules, writer, "register_default_deserializer"); @@ -254,27 +254,27 @@ private static void WriteApiConstructorBody(CodeClass parentClass, CodeMethod me writer.WriteLine($"self.{requestAdapterPropertyName}.base_url = \"{method.BaseUrl}\""); writer.DecreaseIndent(); if (pathParametersProperty != null) - writer.WriteLine($"self.{pathParametersProperty.Name.ToSnakeCase()}[\"base_url\"] = self.{requestAdapterPropertyName}.base_url"); + writer.WriteLine($"self.{pathParametersProperty.Name}[\"base_url\"] = self.{requestAdapterPropertyName}.base_url"); } if (backingStoreParameter != null) - writer.WriteLine($"self.{requestAdapterPropertyName}.enable_backing_store({backingStoreParameter.Name.ToSnakeCase()})"); + writer.WriteLine($"self.{requestAdapterPropertyName}.enable_backing_store({backingStoreParameter.Name})"); } private static void WriteQueryParametersMapper(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer) { var parameter = codeElement.Parameters.FirstOrDefault(x => x.IsOfKind(CodeParameterKind.QueryParametersMapperParameter)); if (parameter == null) throw new InvalidOperationException("QueryParametersMapper should have a parameter of type QueryParametersMapper"); - var parameterName = parameter.Name.ToSnakeCase(); + var parameterName = parameter.Name; var escapedProperties = parentClass.Properties.Where(x => x.IsOfKind(CodePropertyKind.QueryParameter) && x.IsNameEscaped); var unescapedProperties = parentClass.Properties.Where(x => x.IsOfKind(CodePropertyKind.QueryParameter) && !x.IsNameEscaped); foreach (var escapedProperty in escapedProperties) { - writer.StartBlock($"if {parameterName} == \"{escapedProperty.Name.ToSnakeCase()}\":"); + writer.StartBlock($"if {parameterName} == \"{escapedProperty.Name}\":"); writer.WriteLine($"return \"{escapedProperty.SerializationName}\""); writer.DecreaseIndent(); } foreach (var unescapedProperty in unescapedProperties.Select(x => x.Name)) { - writer.StartBlock($"if {parameterName} == \"{unescapedProperty.ToSnakeCase()}\":"); + writer.StartBlock($"if {parameterName} == \"{unescapedProperty}\":"); writer.WriteLine($"return \"{unescapedProperty}\""); writer.DecreaseIndent(); } @@ -333,22 +333,22 @@ private void WriteConstructorBody(CodeClass parentClass, CodeMethod currentMetho { var pathParameters = currentMethod.Parameters .Where(static x => x.IsOfKind(CodeParameterKind.Path)) - .Select(static x => (string.IsNullOrEmpty(x.SerializationName) ? x.Name : x.SerializationName, x.Name.ToSnakeCase())) + .Select(static x => (string.IsNullOrEmpty(x.SerializationName) ? x.Name : x.SerializationName, x.Name)) .ToArray(); if (pathParameters.Any()) { - writer.StartBlock($"if isinstance({pathParametersParameter.Name.ToSnakeCase()}, dict):"); + writer.StartBlock($"if isinstance({pathParametersParameter.Name}, dict):"); foreach (var parameter in pathParameters) { var (name, identName) = parameter; - writer.WriteLine($"{pathParametersParameter.Name.ToSnakeCase()}['{name}'] = str({identName})"); + writer.WriteLine($"{pathParametersParameter.Name}['{name}'] = str({identName})"); } writer.DecreaseIndent(); } - writer.WriteLine($"super().__init__({requestAdapterParameter.Name.ToSnakeCase()}, {urlTemplateProperty.DefaultValue ?? ""}, {pathParametersParameter.Name.ToSnakeCase()})"); + writer.WriteLine($"super().__init__({requestAdapterParameter.Name}, {urlTemplateProperty.DefaultValue ?? ""}, {pathParametersParameter.Name})"); } else - writer.WriteLine($"super().__init__({requestAdapterParameter.Name.ToSnakeCase()}, {urlTemplateProperty.DefaultValue ?? ""}, None)"); + writer.WriteLine($"super().__init__({requestAdapterParameter.Name}, {urlTemplateProperty.DefaultValue ?? ""}, None)"); } else writer.WriteLine("super().__init__()"); @@ -382,17 +382,17 @@ private void WriteDirectAccessProperties(CodeClass parentClass, LanguageWriter w if (propWithDefault.Type is CodeType propertyType && propertyType.TypeDefinition is CodeEnum enumDefinition) { _codeUsingWriter.WriteDeferredImport(parentClass, enumDefinition.Name, writer); - defaultValue = $"{enumDefinition.Name.ToFirstCharacterUpperCase()}({defaultValue})"; + defaultValue = $"{enumDefinition.Name}({defaultValue})"; } conventions.WriteInLineDescription(propWithDefault.Documentation.Description, writer); if (parentClass.IsOfKind(CodeClassKind.Model)) { - writer.WriteLine($"{propWithDefault.Name.ToSnakeCase()}: {(propWithDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithDefault.Type.IsNullable ? "]" : string.Empty)} = {defaultValue}"); + writer.WriteLine($"{propWithDefault.Name}: {(propWithDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithDefault.Type.IsNullable ? "]" : string.Empty)} = {defaultValue}"); writer.WriteLine(); } else { - writer.WriteLine($"self.{conventions.GetAccessModifier(propWithDefault.Access)}{propWithDefault.NamePrefix}{propWithDefault.Name.ToSnakeCase()}: {(propWithDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithDefault.Type.IsNullable ? "]" : string.Empty)} = {defaultValue}"); + writer.WriteLine($"self.{conventions.GetAccessModifier(propWithDefault.Access)}{propWithDefault.NamePrefix}{propWithDefault.Name}: {(propWithDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithDefault.Type.IsNullable ? "]" : string.Empty)} = {defaultValue}"); writer.WriteLine(); } } @@ -410,11 +410,11 @@ private void WriteSetterAccessProperties(CodeClass parentClass, LanguageWriter w if (propWithDefault.Type is CodeType propertyType && propertyType.TypeDefinition is CodeEnum enumDefinition) { _codeUsingWriter.WriteDeferredImport(parentClass, enumDefinition.Name, writer); - defaultValue = $"{enumDefinition.Name.ToFirstCharacterUpperCase()}({defaultValue})"; + defaultValue = $"{enumDefinition.Name}({defaultValue})"; } var returnType = conventions.GetTypeString(propWithDefault.Type, propWithDefault, true, writer); conventions.WriteInLineDescription(propWithDefault.Documentation.Description, writer); - var setterString = $"{propWithDefault.Name.ToSnakeCase()}: {(propWithDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithDefault.Type.IsNullable ? "]" : string.Empty)} = {defaultValue}"; + var setterString = $"{propWithDefault.Name}: {(propWithDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithDefault.Type.IsNullable ? "]" : string.Empty)} = {defaultValue}"; if (parentClass.IsOfKind(CodeClassKind.Model)) { writer.WriteLine($"{setterString}"); @@ -433,9 +433,9 @@ private void WriteSetterAccessPropertiesWithoutDefaults(CodeClass parentClass, L var returnType = conventions.GetTypeString(propWithoutDefault.Type, propWithoutDefault, true, writer); conventions.WriteInLineDescription(propWithoutDefault.Documentation.Description, writer); if (parentClass.IsOfKind(CodeClassKind.Model)) - writer.WriteLine($"{propWithoutDefault.Name.ToSnakeCase()}: {(propWithoutDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithoutDefault.Type.IsNullable ? "]" : string.Empty)} = None"); + writer.WriteLine($"{propWithoutDefault.Name}: {(propWithoutDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithoutDefault.Type.IsNullable ? "]" : string.Empty)} = None"); else - writer.WriteLine($"self.{conventions.GetAccessModifier(propWithoutDefault.Access)}{propWithoutDefault.NamePrefix}{propWithoutDefault.Name.ToSnakeCase()}: {(propWithoutDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithoutDefault.Type.IsNullable ? "]" : string.Empty)} = None"); + writer.WriteLine($"self.{conventions.GetAccessModifier(propWithoutDefault.Access)}{propWithoutDefault.NamePrefix}{propWithoutDefault.Name}: {(propWithoutDefault.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(propWithoutDefault.Type.IsNullable ? "]" : string.Empty)} = None"); } } private static void WriteSetterBody(CodeMethod codeElement, LanguageWriter writer, CodeClass parentClass) @@ -444,9 +444,9 @@ private static void WriteSetterBody(CodeMethod codeElement, LanguageWriter write { var backingStore = parentClass.GetBackingStoreProperty(); if (backingStore == null) - writer.WriteLine($"self.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name?.ToSnakeCase()} = value"); + writer.WriteLine($"self.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name} = value"); else - writer.WriteLine($"self.{backingStore.NamePrefix}{backingStore.Name.ToSnakeCase()}[\"{codeElement.AccessedProperty?.Name?.ToSnakeCase()}\"] = value"); + writer.WriteLine($"self.{backingStore.NamePrefix}{backingStore.Name}[\"{codeElement.AccessedProperty?.Name}\"] = value"); writer.CloseBlock(string.Empty); } else @@ -458,22 +458,22 @@ private void WriteGetterBody(CodeMethod codeElement, LanguageWriter writer, Code { var backingStore = parentClass.GetBackingStoreProperty(); if (backingStore == null) - writer.WriteLine($"return self.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name?.ToSnakeCase()}"); + writer.WriteLine($"return self.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name}"); else if (!(codeElement.AccessedProperty?.Type?.IsNullable ?? true) && !(codeElement.AccessedProperty?.ReadOnly ?? true) && !string.IsNullOrEmpty(codeElement.AccessedProperty?.DefaultValue)) { - writer.WriteLines($"value: {conventions.GetTypeString(codeElement.AccessedProperty.Type, codeElement, true, writer)} = self.{backingStore.NamePrefix}{backingStore.Name.ToSnakeCase()}.get(\"{codeElement.AccessedProperty.Name.ToSnakeCase()}\")", + writer.WriteLines($"value: {conventions.GetTypeString(codeElement.AccessedProperty.Type, codeElement, true, writer)} = self.{backingStore.NamePrefix}{backingStore.Name}.get(\"{codeElement.AccessedProperty.Name}\")", "if not value:"); writer.IncreaseIndent(); writer.WriteLines($"value = {codeElement.AccessedProperty.DefaultValue}", - $"self.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name?.ToSnakeCase()} = value"); + $"self.{codeElement.AccessedProperty?.NamePrefix}{codeElement.AccessedProperty?.Name} = value"); writer.DecreaseIndent(); writer.WriteLines("return value"); } else - writer.WriteLine($"return self.{backingStore.NamePrefix}{backingStore.Name.ToSnakeCase()}.get(\"{codeElement.AccessedProperty?.Name?.ToSnakeCase()}\")"); + writer.WriteLine($"return self.{backingStore.NamePrefix}{backingStore.Name}.get(\"{codeElement.AccessedProperty?.Name}\")"); writer.CloseBlock(string.Empty); } else @@ -505,8 +505,8 @@ private void WriteDeserializerBodyForUnionModel(CodeMethod method, CodeClass par .ThenBy(static x => x.Name) .Select(static x => x.Name)) { - writer.StartBlock($"if self.{otherPropName.ToSnakeCase()}:"); - writer.WriteLine($"return self.{otherPropName.ToSnakeCase()}.{method.Name.ToSnakeCase()}()"); + writer.StartBlock($"if self.{otherPropName}:"); + writer.WriteLine($"return self.{otherPropName}.{method.Name}()"); writer.DecreaseIndent(); } writer.WriteLine($"return {DefaultDeserializerValue}"); @@ -519,7 +519,7 @@ private void WriteDeserializerBodyForIntersectionModel(CodeClass parentClass, La if (complexProperties.Any()) { var propertiesNames = complexProperties - .Select(static x => x.Name.ToSnakeCase()) + .Select(static x => x.Name) .OrderBy(static x => x) .ToArray(); var propertiesNamesAsConditions = propertiesNames @@ -542,12 +542,12 @@ private void WriteDeserializerBodyForInheritedModel(bool inherits, CodeMethod co .Where(static x => !x.ExistsInBaseType) .OrderBy(static x => x.Name)) { - writer.WriteLine($"\"{otherProp.WireName}\": lambda n : setattr(self, '{otherProp.Name.ToSnakeCase()}', n.{GetDeserializationMethodName(otherProp.Type, codeElement, parentClass)}),"); + writer.WriteLine($"\"{otherProp.WireName}\": lambda n : setattr(self, '{otherProp.Name}', n.{GetDeserializationMethodName(otherProp.Type, codeElement, parentClass)}),"); } writer.CloseBlock(); if (inherits) { - writer.WriteLine($"super_fields = super().{codeElement.Name.ToSnakeCase()}()"); + writer.WriteLine($"super_fields = super().{codeElement.Name}()"); writer.WriteLine("fields.update(super_fields)"); } writer.WriteLine("return fields"); @@ -559,12 +559,11 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ var generatorMethodName = parentClass .Methods .FirstOrDefault(x => x.IsOfKind(CodeMethodKind.RequestGenerator) && x.HttpMethod == codeElement.HttpMethod) - ?.Name - ?.ToSnakeCase(); + ?.Name; writer.WriteLine($"request_info = self.{generatorMethodName}("); var requestInfoParameters = new[] { requestParams.requestBody, requestParams.requestConfiguration } .Where(static x => x != null) - .Select(static x => x!.Name.ToSnakeCase()) + .Select(static x => x!.Name) .ToArray(); if (requestInfoParameters.Any() && requestInfoParameters.Aggregate(static (x, y) => $"{x}, {y}") is string parameters) { @@ -585,7 +584,7 @@ private void WriteRequestExecutorBody(CodeMethod codeElement, RequestParams requ writer.StartBlock($"{errorMappingVarName}: Dict[str, ParsableFactory] = {{"); foreach (var errorMapping in codeElement.ErrorMappings) { - writer.WriteLine($"\"{errorMapping.Key.ToUpperInvariant()}\": {errorMapping.Value.Name.ToFirstCharacterUpperCase()},"); + writer.WriteLine($"\"{errorMapping.Key.ToUpperInvariant()}\": {errorMapping.Value.Name},"); } writer.CloseBlock(); } @@ -623,7 +622,7 @@ private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams req UpdateRequestInformationFromRequestBody(codeElement, requestParams, requestAdapterProperty, writer); writer.WriteLine($"return {RequestInfoVarName}"); } - private static string GetPropertyCall(CodeProperty property, string defaultValue) => property == null ? defaultValue : $"self.{property.Name.ToSnakeCase()}"; + private static string GetPropertyCall(CodeProperty property, string defaultValue) => property == null ? defaultValue : $"self.{property.Name}"; private void WriteSerializerBody(bool inherits, CodeClass parentClass, LanguageWriter writer) { if (parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForUnionType) @@ -634,7 +633,7 @@ private void WriteSerializerBody(bool inherits, CodeClass parentClass, LanguageW WriteSerializerBodyForInheritedModel(inherits, parentClass, writer); if (parentClass.GetPropertyOfKind(CodePropertyKind.AdditionalData) is CodeProperty additionalDataProperty) - writer.WriteLine($"writer.write_additional_data_value(self.{additionalDataProperty.Name.ToSnakeCase()})"); + writer.WriteLine($"writer.write_additional_data_value(self.{additionalDataProperty.Name})"); } private void WriteSerializerBodyForInheritedModel(bool inherits, CodeClass parentClass, LanguageWriter writer) { @@ -646,7 +645,7 @@ private void WriteSerializerBodyForInheritedModel(bool inherits, CodeClass paren .OrderBy(static x => x.Name)) { var serializationMethodName = GetSerializationMethodName(otherProp.Type); - writer.WriteLine($"writer.{serializationMethodName}(\"{otherProp.WireName}\", self.{otherProp.Name.ToSnakeCase()})"); + writer.WriteLine($"writer.{serializationMethodName}(\"{otherProp.WireName}\", self.{otherProp.Name})"); } } private void WriteSerializerBodyForUnionModel(CodeClass parentClass, LanguageWriter writer) @@ -658,8 +657,8 @@ private void WriteSerializerBodyForUnionModel(CodeClass parentClass, LanguageWri .OrderBy(static x => x, CodePropertyTypeForwardComparer) .ThenBy(static x => x.Name)) { - writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if self.{otherProp.Name.ToSnakeCase()}:"); - writer.WriteLine($"writer.{GetSerializationMethodName(otherProp.Type)}(None, self.{otherProp.Name.ToSnakeCase()})"); + writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if self.{otherProp.Name}:"); + writer.WriteLine($"writer.{GetSerializationMethodName(otherProp.Type)}(None, self.{otherProp.Name})"); writer.DecreaseIndent(); if (!includeElse) includeElse = true; @@ -675,8 +674,8 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Lang .OrderBy(static x => x, CodePropertyTypeBackwardComparer) .ThenBy(static x => x.Name)) { - writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if self.{otherProp.Name.ToSnakeCase()}:"); - writer.WriteLine($"writer.{GetSerializationMethodName(otherProp.Type)}(None, self.{otherProp.Name.ToSnakeCase()})"); + writer.StartBlock($"{(includeElse ? "el" : string.Empty)}if self.{otherProp.Name}:"); + writer.WriteLine($"writer.{GetSerializationMethodName(otherProp.Type)}(None, self.{otherProp.Name})"); writer.DecreaseIndent(); if (!includeElse) includeElse = true; @@ -691,7 +690,7 @@ private void WriteSerializerBodyForIntersectionModel(CodeClass parentClass, Lang writer.StartBlock("else:"); } var propertiesNames = complexProperties - .Select(static x => x.Name.ToSnakeCase()) + .Select(static x => x.Name) .OrderBy(static x => x, StringComparer.OrdinalIgnoreCase) .Aggregate(static (x, y) => $"self.{x}, self.{y}"); writer.WriteLine($"writer.{GetSerializationMethodName(complexProperties[0].Type)}(None, {propertiesNames})"); @@ -711,7 +710,7 @@ private void WriteMethodDocumentation(CodeMethod code, LanguageWriter writer, st code.Parameters .Where(static x => x.Documentation.DescriptionAvailable) .OrderBy(static x => x.Name, StringComparer.OrdinalIgnoreCase) - .Select(x => $"param {x.Name.ToSnakeCase()}: {PythonConventionService.RemoveInvalidDescriptionCharacters(x.Documentation.Description)}") + .Select(x => $"param {x.Name}: {PythonConventionService.RemoveInvalidDescriptionCharacters(x.Documentation.Description)}") .Union(new[] { returnRemark })); } private static readonly PythonCodeParameterOrderComparer parameterOrderComparer = new(); @@ -726,7 +725,7 @@ private void WriteMethodPrototype(CodeMethod code, LanguageWriter writer, string _ when code.IsAccessor => code.AccessedProperty?.Name, _ when isConstructor => "__init__", _ => code.Name, - })?.ToSnakeCase(); + }); var asyncPrefix = code.IsAsync && code.Kind is CodeMethodKind.RequestExecutor ? "async " : string.Empty; var instanceReference = code.IsOfKind(CodeMethodKind.Factory) ? string.Empty : "self,"; var parameters = string.Join(", ", code.Parameters.OrderBy(x => x, parameterOrderComparer) @@ -752,7 +751,7 @@ private string GetDeserializationMethodName(CodeTypeBase propType, CodeMethod co var isCollection = propType.CollectionKind != CodeTypeBase.CodeTypeCollectionKind.None; var propertyType = conventions.TranslateType(propType); if (conventions.TypeExistInSameClassAsTarget(propType, codeElement)) - propertyType = parentClass.Name.ToFirstCharacterUpperCase(); + propertyType = parentClass.Name; if (propType is CodeType currentType) { if (currentType.TypeDefinition is CodeEnum currentEnum) @@ -822,14 +821,14 @@ private static void UpdateRequestInformationFromRequestConfiguration(RequestPara { if (requestParams.requestConfiguration != null) { - writer.StartBlock($"if {requestParams.requestConfiguration.Name.ToSnakeCase()}:"); - var headers = requestParams.Headers?.Name.ToSnakeCase() ?? "headers"; - writer.WriteLine($"{RequestInfoVarName}.add_request_headers({requestParams.requestConfiguration.Name.ToSnakeCase()}.{headers})"); + writer.StartBlock($"if {requestParams.requestConfiguration.Name}:"); + var headers = requestParams.Headers?.Name ?? "headers"; + writer.WriteLine($"{RequestInfoVarName}.add_request_headers({requestParams.requestConfiguration.Name}.{headers})"); var queryString = requestParams.QueryParameters; if (queryString != null) - writer.WriteLines($"{RequestInfoVarName}.set_query_string_parameters_from_raw_object({requestParams.requestConfiguration.Name.ToSnakeCase()}.{queryString.Name.ToSnakeCase()})"); - var options = requestParams.Options?.Name.ToSnakeCase() ?? "options"; - writer.WriteLine($"{RequestInfoVarName}.add_request_options({requestParams.requestConfiguration.Name.ToSnakeCase()}.{options})"); + writer.WriteLines($"{RequestInfoVarName}.set_query_string_parameters_from_raw_object({requestParams.requestConfiguration.Name}.{queryString.Name})"); + var options = requestParams.Options?.Name ?? "options"; + writer.WriteLine($"{RequestInfoVarName}.add_request_options({requestParams.requestConfiguration.Name}.{options})"); writer.DecreaseIndent(); } } @@ -839,11 +838,11 @@ private void UpdateRequestInformationFromRequestBody(CodeMethod codeElement, Req if (requestParams.requestBody != null) { if (requestParams.requestBody.Type.Name.Equals(conventions.StreamTypeName, StringComparison.OrdinalIgnoreCase)) - writer.WriteLine($"{RequestInfoVarName}.set_stream_content({requestParams.requestBody.Name.ToSnakeCase()})"); + writer.WriteLine($"{RequestInfoVarName}.set_stream_content({requestParams.requestBody.Name})"); else { var setMethodName = requestParams.requestBody.Type is CodeType bodyType && bodyType.TypeDefinition is CodeClass ? "set_content_from_parsable" : "set_content_from_scalar"; - writer.WriteLine($"{RequestInfoVarName}.{setMethodName}(self.{requestAdapterProperty.Name.ToSnakeCase()}, \"{codeElement.RequestBodyContentType}\", {requestParams.requestBody.Name})"); + writer.WriteLine($"{RequestInfoVarName}.{setMethodName}(self.{requestAdapterProperty.Name}, \"{codeElement.RequestBodyContentType}\", {requestParams.requestBody.Name})"); } } } diff --git a/src/Kiota.Builder/Writers/Python/CodePropertyWriter.cs b/src/Kiota.Builder/Writers/Python/CodePropertyWriter.cs index ce2872c04d..228965ebed 100644 --- a/src/Kiota.Builder/Writers/Python/CodePropertyWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodePropertyWriter.cs @@ -25,7 +25,7 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w { case CodePropertyKind.RequestBuilder: writer.WriteLine("@property"); - writer.WriteLine($"def {codeElement.Name.ToSnakeCase()}(self) -> {returnType}:"); + writer.WriteLine($"def {codeElement.Name}(self) -> {returnType}:"); writer.IncreaseIndent(); conventions.WriteLongDescription(codeElement.Documentation, writer); _codeUsingWriter.WriteDeferredImport(parentClass, codeElement.Type.Name, writer); @@ -33,13 +33,13 @@ public override void WriteCodeElement(CodeProperty codeElement, LanguageWriter w writer.CloseBlock(string.Empty); break; case CodePropertyKind.QueryParameters: - returnType = $"{codeElement.Parent?.Parent?.Name.ToFirstCharacterUpperCase()}.{codeElement.Type.Name.ToFirstCharacterUpperCase()}"; + returnType = $"{codeElement.Parent?.Parent?.Name}.{codeElement.Type.Name}"; goto case CodePropertyKind.Headers; case CodePropertyKind.Headers: case CodePropertyKind.Options: case CodePropertyKind.QueryParameter: conventions.WriteInLineDescription(codeElement.Documentation.Description, writer); - writer.WriteLine($"{conventions.GetAccessModifier(codeElement.Access)}{codeElement.NamePrefix}{codeElement.Name.ToSnakeCase()}: {(codeElement.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(codeElement.Type.IsNullable ? "]" : string.Empty)} = None"); + writer.WriteLine($"{conventions.GetAccessModifier(codeElement.Access)}{codeElement.NamePrefix}{codeElement.Name}: {(codeElement.Type.IsNullable ? "Optional[" : string.Empty)}{returnType}{(codeElement.Type.IsNullable ? "]" : string.Empty)} = None"); writer.WriteLine(); break; } diff --git a/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs b/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs index e23fb213f7..e16c9ab232 100644 --- a/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs +++ b/src/Kiota.Builder/Writers/Python/CodeUsingWriter.cs @@ -36,7 +36,7 @@ public void WriteExternalImports(ClassDeclaration codeElement, LanguageWriter wr if ("-".Equals(codeUsing.Key, StringComparison.OrdinalIgnoreCase)) writer.WriteLine($"import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); else - writer.WriteLine($"from {codeUsing.Key.ToSnakeCase()} import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); + writer.WriteLine($"from {codeUsing.Key} import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); } writer.WriteLine(); } @@ -105,7 +105,7 @@ public void WriteConditionalInternalImports(ClassDeclaration codeElement, Langua writer.WriteLine("if TYPE_CHECKING:"); writer.IncreaseIndent(); foreach (var codeUsing in internalImportSymbolsAndPaths) - writer.WriteLine($"from {codeUsing.Key.ToSnakeCase()} import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); + writer.WriteLine($"from {codeUsing.Key} import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); writer.DecreaseIndent(); writer.WriteLine(); @@ -139,7 +139,7 @@ private static void WriteCodeUsings(IGrouping[ if (importSymbolsAndPaths.Any()) { foreach (var codeUsing in importSymbolsAndPaths) - writer.WriteLine($"from {codeUsing.Key.ToSnakeCase()} import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); + writer.WriteLine($"from {codeUsing.Key} import {codeUsing.Select(x => GetAliasedSymbol(x.Item1, x.Item2)).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).Aggregate(static (x, y) => x + ", " + y)}"); writer.WriteLine(); } } diff --git a/src/Kiota.Builder/Writers/Python/PythonConventionService.cs b/src/Kiota.Builder/Writers/Python/PythonConventionService.cs index 9b42876492..bccd06ddd5 100644 --- a/src/Kiota.Builder/Writers/Python/PythonConventionService.cs +++ b/src/Kiota.Builder/Writers/Python/PythonConventionService.cs @@ -23,16 +23,16 @@ public class PythonConventionService : CommonLanguageConventionService internal void AddRequestBuilderBody(CodeClass parentClass, string returnType, LanguageWriter writer, string? urlTemplateVarName = default, IEnumerable? pathParameters = default) { var urlTemplateParams = string.IsNullOrEmpty(urlTemplateVarName) && parentClass.GetPropertyOfKind(CodePropertyKind.PathParameters) is CodeProperty pathParametersProperty ? - $"self.{pathParametersProperty.Name.ToSnakeCase()}" : + $"self.{pathParametersProperty.Name}" : urlTemplateVarName; - var pathParametersSuffix = !(pathParameters?.Any() ?? false) ? string.Empty : $", {string.Join(", ", pathParameters.Select(x => $"{x.Name.ToSnakeCase()}"))}"; + var pathParametersSuffix = !(pathParameters?.Any() ?? false) ? string.Empty : $", {string.Join(", ", pathParameters.Select(x => $"{x.Name}"))}"; if (parentClass.GetPropertyOfKind(CodePropertyKind.RequestAdapter) is CodeProperty requestAdapterProp) - writer.WriteLine($"return {returnType}(self.{requestAdapterProp.Name.ToSnakeCase()}, {urlTemplateParams}{pathParametersSuffix})"); + writer.WriteLine($"return {returnType}(self.{requestAdapterProp.Name}, {urlTemplateParams}{pathParametersSuffix})"); } internal void AddParametersAssignment(LanguageWriter writer, CodeTypeBase? pathParametersType, string pathParametersReference, params (CodeTypeBase, string, string)[] parameters) { if (pathParametersType == null) return; - writer.WriteLine($"{TempDictionaryVarName} = get_path_parameters({pathParametersReference.ToSnakeCase()})"); + writer.WriteLine($"{TempDictionaryVarName} = get_path_parameters({pathParametersReference})"); if (parameters.Any()) writer.WriteLines(parameters.Select(p => $"{TempDictionaryVarName}[\"{p.Item2}\"] = {p.Item3}" @@ -53,7 +53,7 @@ public override string GetParameterSignature(CodeParameter parameter, CodeElemen ArgumentNullException.ThrowIfNull(parameter); ArgumentNullException.ThrowIfNull(targetElement); var defaultValueSuffix = string.IsNullOrEmpty(parameter.DefaultValue) ? string.Empty : $" = {parameter.DefaultValue}"; - return $"{parameter.Name.ToSnakeCase()}: {(parameter.Type.IsNullable ? "Optional[" : string.Empty)}{GetTypeString(parameter.Type, targetElement, true, writer)}{(parameter.Type.IsNullable ? "] = None" : string.Empty)}{defaultValueSuffix}"; + return $"{parameter.Name}: {(parameter.Type.IsNullable ? "Optional[" : string.Empty)}{GetTypeString(parameter.Type, targetElement, true, writer)}{(parameter.Type.IsNullable ? "] = None" : string.Empty)}{defaultValueSuffix}"; } private static string GetTypeAlias(CodeType targetType, CodeElement targetElement) { @@ -81,7 +81,7 @@ public override string GetTypeString(CodeTypeBase code, CodeElement targetElemen var alias = GetTypeAlias(currentType, targetElement); var typeName = string.IsNullOrEmpty(alias) ? TranslateType(currentType) : alias; if (TypeExistInSameClassAsTarget(code, targetElement) && targetElement.Parent != null) - typeName = targetElement.Parent.Name.ToFirstCharacterUpperCase(); + typeName = targetElement.Parent.Name; if (code.ActionOf && writer != null) return WriteInlineDeclaration(currentType, targetElement, writer); return $"{collectionPrefix}{typeName}{collectionSuffix}"; @@ -109,7 +109,7 @@ private static string TranslateAllTypes(string typeName) "boolean" => "bool", "guid" or "uuid" => "UUID", "object" or "str" or "int" or "float" or "bytes" or "datetime.datetime" or "datetime.timedelta" or "datetime.date" or "datetime.time" => typeName.ToLowerInvariant(), - _ => !string.IsNullOrEmpty(typeName) ? typeName.ToFirstCharacterUpperCase() : "object", + _ => !string.IsNullOrEmpty(typeName) ? typeName : "object", }; } diff --git a/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs b/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs index b56b94c999..1971974a55 100644 --- a/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs +++ b/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs @@ -23,8 +23,8 @@ public override (string, string, string) GetRelativeImportPathForUsing(CodeUsing return (string.Empty, string.Empty, string.Empty);//it's an external import, add nothing var (importSymbol, typeDef) = codeUsing.Declaration?.TypeDefinition is CodeElement td ? td switch { - CodeFunction f => (f.Name.ToFirstCharacterLowerCase(), td), - _ => (td.Name.ToFirstCharacterUpperCase(), td), + CodeFunction f => (f.Name, td), + _ => (td.Name, td), } : (codeUsing.Name, null); if (typeDef == null) @@ -32,9 +32,9 @@ public override (string, string, string) GetRelativeImportPathForUsing(CodeUsing var importPath = GetImportRelativePathFromNamespaces(currentNamespace, typeDef.GetImmediateParentOfType()); if (string.IsNullOrEmpty(importPath)) - importPath += codeUsing.Name; + importPath += codeUsing.Name.ToSnakeCase(); else - importPath += codeUsing.Declaration?.Name.ToFirstCharacterLowerCase(); + importPath += codeUsing.Declaration?.Name.ToSnakeCase(); return (importSymbol, codeUsing.Alias, importPath); } protected new string GetImportRelativePathFromNamespaces(CodeNamespace currentNamespace, CodeNamespace importNamespace) @@ -53,7 +53,7 @@ public override (string, string, string) GetRelativeImportPathForUsing(CodeUsing protected static new string GetUpwardsMoves(int UpwardsMovesCount) => string.Join("", Enumerable.Repeat(".", UpwardsMovesCount)) + (UpwardsMovesCount > 0 ? "." : string.Empty); protected static new string GetRemainingImportPath(IEnumerable remainingSegments) { - var segments = remainingSegments.Select(static x => x.ToFirstCharacterLowerCase()).ToArray(); + var segments = remainingSegments.Select(static x => x.ToSnakeCase()).ToArray(); if (segments.Any()) return segments.Aggregate(static (x, y) => $"{x}.{y}") + '.'; return string.Empty; diff --git a/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs index a3b919fdca..4ff606b287 100644 --- a/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs @@ -35,7 +35,7 @@ public void WritesAliasedSymbol() Alias = "baz", Declaration = new CodeType { - Name = "bar", + Name = "Bar", TypeDefinition = codeClass, }, }; @@ -50,7 +50,7 @@ public void DoesntAliasRegularSymbols() var usingWriter = new CodeUsingWriter("foo"); var codeClass = root.AddClass(new CodeClass { - Name = "bar", + Name = "Bar", }).First(); var us = new CodeUsing From 8b9563e2986833fc4e5ea90ef62e5b9452533a84 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Tue, 3 Oct 2023 19:12:31 +0100 Subject: [PATCH 2/6] revert undesired changes --- it/compare-generation.ps1 | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/it/compare-generation.ps1 b/it/compare-generation.ps1 index cd738e5908..58753b89c1 100755 --- a/it/compare-generation.ps1 +++ b/it/compare-generation.ps1 @@ -61,15 +61,15 @@ else { $tmpFolder1 = New-TemporaryDirectory $tmpFolder2 = New-TemporaryDirectory -Start-Process "./publish/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow -Start-Process "./src/kiota/bin/Debug/net7.0/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow +Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow +Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow # Remove variable output files -Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") +Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log") } -Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") +Remove-Item (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log") } @@ -84,8 +84,6 @@ Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString2)) Write-Output "Folder 1: $tmpFolder1" Write-Output "Folder 2: $tmpFolder2" -diff -r --color $tmpFolder1 $tmpFolder2 - if ($HashString1 -eq $HashString2) { Write-Output "The content of the folders is identical" From 46dda5944ec8b5bf901f2da710f1ba04b66bd95d Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Wed, 4 Oct 2023 10:17:52 +0100 Subject: [PATCH 3/6] all the tests passing --- .../Python/PythonRelativeImportManager.cs | 4 +- .../Refiners/PythonLanguageRefinerTests.cs | 5 +- .../Python/CodeClassDeclarationWriterTests.cs | 12 +- .../Writers/Python/CodeEnumWriterTests.cs | 2 +- .../Writers/Python/CodeMethodWriterTests.cs | 125 ++++++++++-------- .../Writers/Python/CodePropertyWriterTests.cs | 8 +- .../Writers/Python/CodeUsingWriterTests.cs | 24 +++- 7 files changed, 106 insertions(+), 74 deletions(-) diff --git a/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs b/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs index 1971974a55..cbc7a6c5f2 100644 --- a/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs +++ b/src/Kiota.Builder/Writers/Python/PythonRelativeImportManager.cs @@ -32,10 +32,10 @@ public override (string, string, string) GetRelativeImportPathForUsing(CodeUsing var importPath = GetImportRelativePathFromNamespaces(currentNamespace, typeDef.GetImmediateParentOfType()); if (string.IsNullOrEmpty(importPath)) - importPath += codeUsing.Name.ToSnakeCase(); + importPath += codeUsing.Name.ToSnakeCase(); // TODO: review the logic happening for those imports else importPath += codeUsing.Declaration?.Name.ToSnakeCase(); - return (importSymbol, codeUsing.Alias, importPath); + return (importSymbol.ToFirstCharacterUpperCase(), codeUsing.Alias, importPath); } protected new string GetImportRelativePathFromNamespaces(CodeNamespace currentNamespace, CodeNamespace importNamespace) { diff --git a/tests/Kiota.Builder.Tests/Refiners/PythonLanguageRefinerTests.cs b/tests/Kiota.Builder.Tests/Refiners/PythonLanguageRefinerTests.cs index 1caf0a11d4..564d38b72e 100644 --- a/tests/Kiota.Builder.Tests/Refiners/PythonLanguageRefinerTests.cs +++ b/tests/Kiota.Builder.Tests/Refiners/PythonLanguageRefinerTests.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using Kiota.Builder.CodeDOM; using Kiota.Builder.Configuration; +using Kiota.Builder.Extensions; using Kiota.Builder.Refiners; using Xunit; @@ -101,7 +102,7 @@ public async Task EnumWithReservedName_IsRenamed(string input) model.AddOption(option); await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Python }, root); - Assert.Equal(input + "_", model.Options.First().Name);// we need to escape this in python + Assert.Equal(input.ToFirstCharacterUpperCase() + "_", model.Options.First().Name);// we need to escape this in python } [Fact] public async Task AddsExceptionInheritanceOnErrorClasses() @@ -167,7 +168,7 @@ public async Task InlineParentOnErrorClassesWhichAlreadyInherit() await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Python }, root); Assert.Contains(model.Properties, x => x.Name.Equals("other_prop")); - Assert.Contains(model.Methods, x => x.Name.Equals("otherMethod")); + Assert.Contains(model.Methods, x => x.Name.Equals("other_method")); Assert.Contains(model.Usings, x => x.Name.Equals("otherNs")); } [Fact] diff --git a/tests/Kiota.Builder.Tests/Writers/Python/CodeClassDeclarationWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Python/CodeClassDeclarationWriterTests.cs index 2db9338291..c0cc9f764d 100644 --- a/tests/Kiota.Builder.Tests/Writers/Python/CodeClassDeclarationWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Python/CodeClassDeclarationWriterTests.cs @@ -32,7 +32,7 @@ public CodeClassDeclarationWriterTests() ns = root.AddNamespace("graphtests.models"); parentClass = new() { - Name = "parentClass" + Name = "ParentClass" }; ns.AddClass(parentClass); } @@ -81,11 +81,11 @@ public void WritesImplementation() var declaration = parentClass.StartBlock; declaration.AddImplements(new CodeType { - Name = "someInterface" + Name = "SomeInterface" }); declaration.AddImplements(new CodeType { - Name = "secondInterface" + Name = "SecondInterface" }); codeElementWriter.WriteCodeElement(declaration, writer); var result = tw.ToString(); @@ -98,7 +98,7 @@ public void WritesInheritance() var declaration = parentClass.StartBlock; var interfaceDef = new CodeInterface { - Name = "someInterface", + Name = "SomeInterface", }; ns.AddInterface(interfaceDef); var nUsing = new CodeUsing @@ -106,14 +106,14 @@ public void WritesInheritance() Name = "graph", Declaration = new() { - Name = "someInterface", + Name = "SomeInterface", TypeDefinition = interfaceDef, } }; declaration.AddUsings(nUsing); declaration.Inherits = new() { - Name = "someInterface" + Name = "SomeInterface" }; codeElementWriter.WriteCodeElement(declaration, writer); var result = tw.ToString(); diff --git a/tests/Kiota.Builder.Tests/Writers/Python/CodeEnumWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Python/CodeEnumWriterTests.cs index 499311d8b0..c531832d2b 100644 --- a/tests/Kiota.Builder.Tests/Writers/Python/CodeEnumWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Python/CodeEnumWriterTests.cs @@ -35,7 +35,7 @@ public void Dispose() [Fact] public void WritesEnum() { - const string optionName = "option1"; + const string optionName = "Option1"; currentEnum.AddOption(new CodeEnumOption { Name = optionName }); writer.Write(currentEnum); var result = tw.ToString(); diff --git a/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs index ed08d668c1..a885bd4525 100644 --- a/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Python/CodeMethodWriterTests.cs @@ -25,7 +25,7 @@ public class CodeMethodWriterTests : IDisposable private const string ReturnTypeName = "Somecustomtype"; private const string MethodDescription = "some description"; private const string ParamDescription = "some parameter description"; - private const string ParamName = "paramName"; + private const string ParamName = "param_name"; public CodeMethodWriterTests() { writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.Python, DefaultPath, DefaultName); @@ -42,11 +42,11 @@ private void setup(bool withInheritance = false) { baseClass = root.AddClass(new CodeClass { - Name = "someParentClass", + Name = "SomeParentClass", }).First(); baseClass.AddProperty(new CodeProperty { - Name = "definedInParent", + Name = "defined_in_parent", Type = new CodeType { Name = "string" @@ -56,20 +56,20 @@ private void setup(bool withInheritance = false) } parentClass = new CodeClass { - Name = "parentClass" + Name = "ParentClass" }; if (withInheritance) { parentClass.StartBlock.Inherits = new CodeType { - Name = "someParentClass", + Name = "SomeParentClass", TypeDefinition = baseClass }; } root.AddClass(parentClass); childClass = new CodeClass { - Name = "childClass" + Name = "ChildClass" }; root.AddClass(childClass); var returnTypeClassDef = new CodeClass @@ -106,16 +106,16 @@ private void AddRequestProperties() { parentClass.AddProperty(new CodeProperty { - Name = "requestAdapter", + Name = "request_adapter", Kind = CodePropertyKind.RequestAdapter, Type = new CodeType { - Name = "requestAdapter" + Name = "RequestAdapter" }, }); parentClass.AddProperty(new CodeProperty { - Name = "pathParameters", + Name = "path_parameters", Kind = CodePropertyKind.PathParameters, Type = new CodeType { @@ -124,7 +124,7 @@ private void AddRequestProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "urlTemplate", + Name = "url_template", Kind = CodePropertyKind.UrlTemplate, Type = new CodeType { @@ -136,7 +136,7 @@ private void AddSerializationProperties() { parentClass.AddProperty(new CodeProperty { - Name = "additionalData", + Name = "additional_data", Kind = CodePropertyKind.AdditionalData, Type = new CodeType { @@ -145,7 +145,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyString", + Name = "dummy_string", Type = new CodeType { Name = "string" @@ -153,7 +153,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyInteger", + Name = "dummy_integer", Type = new CodeType { Name = "integer" @@ -161,7 +161,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyBoolean", + Name = "dummy_boolean", Type = new CodeType { Name = "boolean" @@ -169,7 +169,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyFloat", + Name = "dummy_float", Type = new CodeType { Name = "decimal" @@ -177,7 +177,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyTimespan", + Name = "dummy_timespan", Type = new CodeType { Name = "datetime.timedelta" @@ -185,7 +185,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyDateTime", + Name = "dummy_date_time", Type = new CodeType { Name = "datetime.datetime" @@ -193,7 +193,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyTime", + Name = "dummy_time", Type = new CodeType { Name = "datetime.time" @@ -201,7 +201,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyDate", + Name = "dummy_date", Type = new CodeType { Name = "datetime.date" @@ -209,7 +209,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyGuid", + Name = "dummy_guid", Type = new CodeType { Name = "UUID" @@ -217,15 +217,15 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyClass", + Name = "dummy_class", Type = new CodeType { - Name = "dummyClass" + Name = "DummyClass" }, }); parentClass.AddProperty(new CodeProperty { - Name = "dummyStream", + Name = "dummy_stream", Type = new CodeType { Name = "binary" @@ -233,7 +233,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyColl", + Name = "dummy_coll", Type = new CodeType { Name = "guid", @@ -242,7 +242,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyComplexColl", + Name = "dummy_complex_coll", Type = new CodeType { Name = "Complex", @@ -255,7 +255,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "dummyEnumCollection", + Name = "dummy_enum_collection", Type = new CodeType { Name = "SomeEnum", @@ -267,7 +267,7 @@ private void AddSerializationProperties() }); parentClass.AddProperty(new CodeProperty { - Name = "definedInParent", + Name = "defined_in_parent", Type = new CodeType { Name = "string" @@ -349,19 +349,19 @@ private CodeClass AddUnionTypeWrapper() unionTypeWrapper.OriginalComposedType.AddType(sType); unionTypeWrapper.AddProperty(new CodeProperty { - Name = "ComplexType1Value", + Name = "complex_type1_value", Type = cType1, Kind = CodePropertyKind.Custom }); unionTypeWrapper.AddProperty(new CodeProperty { - Name = "ComplexType2Value", + Name = "complex_type2_value", Type = cType2, Kind = CodePropertyKind.Custom }); unionTypeWrapper.AddProperty(new CodeProperty { - Name = "StringValue", + Name = "string_value", Type = sType, Kind = CodePropertyKind.Custom }); @@ -457,25 +457,25 @@ private CodeClass AddIntersectionTypeWrapper() intersectionTypeWrapper.OriginalComposedType.AddType(sType); intersectionTypeWrapper.AddProperty(new CodeProperty { - Name = "ComplexType1Value", + Name = "complex_type1_value", Type = cType1, Kind = CodePropertyKind.Custom }); intersectionTypeWrapper.AddProperty(new CodeProperty { - Name = "ComplexType2Value", + Name = "complex_type2_value", Type = cType2, Kind = CodePropertyKind.Custom }); intersectionTypeWrapper.AddProperty(new CodeProperty { - Name = "ComplexType3Value", + Name = "complex_type3_value", Type = cType3, Kind = CodePropertyKind.Custom }); intersectionTypeWrapper.AddProperty(new CodeProperty { - Name = "StringValue", + Name = "string_value", Type = sType, Kind = CodePropertyKind.Custom }); @@ -728,7 +728,7 @@ public void WritesUnionDeSerializerBody() var wrapper = AddUnionTypeWrapper(); var deserializationMethod = wrapper.AddMethod(new CodeMethod { - Name = "GetFieldDeserializers", + Name = "get_field_deserializers", Kind = CodeMethodKind.Deserializer, IsAsync = false, ReturnType = new CodeType @@ -1028,7 +1028,7 @@ public void WritesFactoryMethods() method.Kind = CodeMethodKind.Factory; method.AddParameter(new CodeParameter { - Name = "parseNode", + Name = "parse_node", Kind = CodeParameterKind.ParseNode, Type = new CodeType { @@ -1073,7 +1073,7 @@ public void WritesModelFactoryBodyForInheritedModels() AddCodeUsings(); method.AddParameter(new CodeParameter { - Name = "parseNode", + Name = "parse_node", Kind = CodeParameterKind.ParseNode, Type = new CodeType { @@ -1114,7 +1114,7 @@ public void WritesModelFactoryBodyForUnionModels() }).First(); factoryMethod.AddParameter(new CodeParameter { - Name = "parseNode", + Name = "parse_node", Kind = CodeParameterKind.ParseNode, Type = new CodeType { @@ -1155,7 +1155,7 @@ public void WritesModelFactoryBodyForIntersectionModels() }).First(); factoryMethod.AddParameter(new CodeParameter { - Name = "parseNode", + Name = "parse_node", Kind = CodeParameterKind.ParseNode, Type = new CodeType { @@ -1229,7 +1229,7 @@ public void DoesntWriteFactoryConditionalsOnEmptyPropertyName() parentClass.DiscriminatorInformation.DiscriminatorPropertyName = string.Empty; method.AddParameter(new CodeParameter { - Name = "parseNode", + Name = "parse_node", Kind = CodeParameterKind.ParseNode, Type = new CodeType { @@ -1265,7 +1265,7 @@ public void DoesntWriteFactorySwitchOnEmptyMappings() parentClass.DiscriminatorInformation.DiscriminatorPropertyName = "@odata.type"; method.AddParameter(new CodeParameter { - Name = "parseNode", + Name = "parse_node", Kind = CodeParameterKind.ParseNode, Type = new CodeType { @@ -1363,17 +1363,19 @@ public void WritesGetterToBackingStore() setup(); parentClass.GetGreatestGrandparent().AddBackingStoreProperty(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Getter; writer.Write(method); var result = tw.ToString(); Assert.Contains("@property", result); - Assert.Contains("return self.backing_store.get(\"some_property\")", result); + Assert.Contains("return self.backingStore.get(\"some_property\")", result); } [Fact] public void WritesGetterNullBackingStore() { setup(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Getter; writer.Write(method); var result = tw.ToString(); @@ -1403,6 +1405,7 @@ public void WritesSetterNullBackingStore() { setup(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Setter; writer.Write(method); var result = tw.ToString(); @@ -1417,13 +1420,14 @@ public void WritesSetterToBackingStore() method.Kind = CodeMethodKind.Setter; writer.Write(method); var result = tw.ToString(); - Assert.Contains("self.backing_store[\"some_property\"] = value", result); + Assert.Contains("self.backingStore[\"someProperty\"] = value", result); } [Fact] public void WritesGetterToField() { setup(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Getter; writer.Write(method); var result = tw.ToString(); @@ -1445,6 +1449,7 @@ public void WritesSetterToField() { setup(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Setter; writer.Write(method); var result = tw.ToString(); @@ -1497,7 +1502,7 @@ public void WritesWithUrl() Assert.Throws(() => writer.Write(method)); method.AddParameter(new CodeParameter { - Name = "rawUrl", + Name = "raw_url", Kind = CodeParameterKind.RawUrl, Type = new CodeType { @@ -1508,7 +1513,7 @@ public void WritesWithUrl() AddRequestProperties(); writer.Write(method); var result = tw.ToString(); - Assert.Contains($"return {parentClass.Name.ToFirstCharacterUpperCase()}", result); + Assert.Contains($"return {parentClass.Name}", result); Assert.Contains("request_adapter, raw_url", result); } [Fact] @@ -1568,11 +1573,11 @@ public void WritesConstructorForRequestBuilderWithRequestAdapter() // AddRequestProperties(); method.AddParameter(new CodeParameter { - Name = "requestAdapter", + Name = "request_adapter", Kind = CodeParameterKind.RequestAdapter, Type = new CodeType { - Name = "requestAdapter" + Name = "RequestAdapter" }, }); writer.Write(method); @@ -1610,16 +1615,16 @@ public void WritesConstructorForRequestBuilderWithRequestAdapterAndPathParameter // AddRequestProperties(); method.AddParameter(new CodeParameter { - Name = "requestAdapter", + Name = "request_adapter", Kind = CodeParameterKind.RequestAdapter, Type = new CodeType { - Name = "requestAdapter" + Name = "RequestAdapter" }, }); method.AddParameter(new CodeParameter { - Name = "pathParameters", + Name = "path_parameters", Kind = CodeParameterKind.PathParameters, Type = new CodeType { @@ -1655,6 +1660,7 @@ public void DoesntWriteConstructorForModelClasses() { setup(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Constructor; method.IsAsync = false; var defaultValue = "someVal"; @@ -1687,6 +1693,7 @@ public void WritesModelClasses() { setup(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Constructor; parentClass.Kind = CodeClassKind.Model; writer.Write(method); @@ -1700,12 +1707,13 @@ public void WritesModelClassesWithDefaultEnumValue() { setup(); method.AddAccessedProperty(); + method.AccessedProperty.Name = "some_property"; method.Kind = CodeMethodKind.Constructor; var defaultValue = "1024x1024"; var propName = "size"; var codeEnum = new CodeEnum { - Name = "pictureSize" + Name = "PictureSize" }; root.AddEnum(codeEnum); parentClass.Kind = CodeClassKind.Model; @@ -1741,7 +1749,7 @@ public void WritesModelClassesWithDefaultEnumValue() Assert.DoesNotContain("super().__init__()", result); Assert.Contains($"from .{codeEnum.Name.ToSnakeCase()} import {codeEnum.Name.ToFirstCharacterUpperCase()}", result); Assert.Contains("has a description", result); - Assert.Contains($"{propName}: Optional[{codeEnum.Name.ToFirstCharacterUpperCase()}] = {codeEnum.Name.ToFirstCharacterUpperCase()}({defaultValue})", result); + Assert.Contains($"{propName}: Optional[{codeEnum.Name}] = {codeEnum.Name}({defaultValue})", result); Assert.Contains($"some_property: Optional[str] = None", result); } [Fact] @@ -1851,7 +1859,7 @@ public void WritesApiConstructor() method.BaseUrl = "https://graph.microsoft.com/v1.0"; parentClass.AddProperty(new CodeProperty { - Name = "pathParameters", + Name = "path_parameters", Kind = CodePropertyKind.PathParameters, Type = new CodeType { @@ -1934,7 +1942,7 @@ public void WritesApiConstructorWithBackingStore() }); var backingStoreParam = new CodeParameter { - Name = "backingStore", + Name = "backing_store", Kind = CodeParameterKind.BackingStore, Type = new CodeType { @@ -1979,7 +1987,7 @@ public void WritesNameMapperMethod() }, new CodeProperty { - Name = "select-from", + Name = "select_from", Kind = CodePropertyKind.QueryParameter, SerializationName = "select%2Dfrom", Type = new CodeType @@ -2000,7 +2008,7 @@ public void WritesNameMapperMethod() method.AddParameter(new CodeParameter { Kind = CodeParameterKind.QueryParametersMapperParameter, - Name = "originalName", + Name = "original_name", Type = new CodeType { Name = "string", @@ -2027,7 +2035,8 @@ public void WritesNameMapperMethodWithUnescapedProperties() method.IsAsync = false; parentClass.AddProperty(new CodeProperty { - Name = "startDateTime", + Name = "start_date_time", + SerializationName = "startDateTime", Kind = CodePropertyKind.QueryParameter, Type = new CodeType { @@ -2037,7 +2046,7 @@ public void WritesNameMapperMethodWithUnescapedProperties() method.AddParameter(new CodeParameter { Kind = CodeParameterKind.QueryParametersMapperParameter, - Name = "originalName", + Name = "original_name", Type = new CodeType { Name = "string", diff --git a/tests/Kiota.Builder.Tests/Writers/Python/CodePropertyWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Python/CodePropertyWriterTests.cs index 533576540d..a4a9673c08 100644 --- a/tests/Kiota.Builder.Tests/Writers/Python/CodePropertyWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Python/CodePropertyWriterTests.cs @@ -16,7 +16,7 @@ public class CodePropertyWriterTests : IDisposable private readonly CodeProperty property; private readonly CodeClass parentClass; private readonly CodeNamespace ns; - private const string PropertyName = "propertyName"; + private const string PropertyName = "property_name"; private const string TypeName = "Somecustomtype"; public CodePropertyWriterTests() { @@ -24,7 +24,7 @@ public CodePropertyWriterTests() tw = new StringWriter(); writer.SetTextWriter(tw); var root = CodeNamespace.InitRootNamespace(); - ns = root.AddNamespace("graphtests.models"); + ns = root.AddNamespace("Graphtests.models"); parentClass = new CodeClass { Name = "parentClass" @@ -56,7 +56,7 @@ public CodePropertyWriterTests() parentClass.StartBlock.AddUsings(nUsing); parentClass.AddProperty(property, new() { - Name = "pathParameters", + Name = "path_parameters", Kind = CodePropertyKind.PathParameters, Type = new CodeType { @@ -64,7 +64,7 @@ public CodePropertyWriterTests() }, }, new() { - Name = "requestAdapter", + Name = "request_adapter", Kind = CodePropertyKind.RequestAdapter, Type = new CodeType { diff --git a/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs b/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs index 4ff606b287..3c544cd9f5 100644 --- a/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs +++ b/tests/Kiota.Builder.Tests/Writers/Python/CodeUsingWriterTests.cs @@ -31,7 +31,7 @@ public void WritesAliasedSymbol() }).First(); var us = new CodeUsing { - Name = "bar", + Name = "Bar", Alias = "baz", Declaration = new CodeType { @@ -45,6 +45,28 @@ public void WritesAliasedSymbol() Assert.Contains("from .bar import Bar as baz", result); } [Fact] + public void WritesRefinedNames() + { + var usingWriter = new CodeUsingWriter("foo"); + var codeClass = root.AddClass(new CodeClass + { + Name = "BarBaz", + }).First(); + var us = new CodeUsing + { + Name = "BarBaz", + Declaration = new CodeType + { + Name = "BarBaz", + TypeDefinition = codeClass, + }, + }; + codeClass.AddUsing(us); + usingWriter.WriteInternalImports(codeClass, writer); + var result = tw.ToString(); + Assert.Contains("from .bar_baz import BarBaz", result); + } + [Fact] public void DoesntAliasRegularSymbols() { var usingWriter = new CodeUsingWriter("foo"); From 2ec4c6e30873240ad3ad4bea93ac5a135ac3c657 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Wed, 4 Oct 2023 10:51:00 +0100 Subject: [PATCH 4/6] test in ci --- .github/workflows/integration-tests.yml | 47 +++++++++++++------------ it/compare-generation.ps1 | 10 +++--- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index c53e44ff15..6c7623c903 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -1,30 +1,31 @@ name: integration-tests on: - workflow_dispatch: + # workflow_dispatch: push: - branches: [main] - paths-ignore: - [ - "abstractions/**", - "authentication/**", - "serialization/**", - "http/**", - "**.md", - ".vscode/**", - "**.svg", - ] - pull_request: - paths-ignore: - [ - "abstractions/**", - "authentication/**", - "serialization/**", - "http/**", - "**.md", - ".vscode/**", - "**.svg", - ] + # TEST in CI + # branches: [main] + # paths-ignore: + # [ + # "abstractions/**", + # "authentication/**", + # "serialization/**", + # "http/**", + # "**.md", + # ".vscode/**", + # "**.svg", + # ] + # pull_request: + # paths-ignore: + # [ + # "abstractions/**", + # "authentication/**", + # "serialization/**", + # "http/**", + # "**.md", + # ".vscode/**", + # "**.svg", + # ] concurrency: # Only run once for latest commit per ref and cancel other (previous) runs. diff --git a/it/compare-generation.ps1 b/it/compare-generation.ps1 index 58753b89c1..cd738e5908 100755 --- a/it/compare-generation.ps1 +++ b/it/compare-generation.ps1 @@ -61,15 +61,15 @@ else { $tmpFolder1 = New-TemporaryDirectory $tmpFolder2 = New-TemporaryDirectory -Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow -Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow +Start-Process "./publish/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow +Start-Process "./src/kiota/bin/Debug/net7.0/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow # Remove variable output files -Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") +Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log") } -Remove-Item (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") +Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log") } @@ -84,6 +84,8 @@ Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString2)) Write-Output "Folder 1: $tmpFolder1" Write-Output "Folder 2: $tmpFolder2" +diff -r --color $tmpFolder1 $tmpFolder2 + if ($HashString1 -eq $HashString2) { Write-Output "The content of the folders is identical" From 538010d785979780693f213f691a4f0dd2f0ae08 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Wed, 4 Oct 2023 11:04:37 +0100 Subject: [PATCH 5/6] restore --- it/compare-generation.ps1 | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/it/compare-generation.ps1 b/it/compare-generation.ps1 index cd738e5908..58753b89c1 100755 --- a/it/compare-generation.ps1 +++ b/it/compare-generation.ps1 @@ -61,15 +61,15 @@ else { $tmpFolder1 = New-TemporaryDirectory $tmpFolder2 = New-TemporaryDirectory -Start-Process "./publish/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow -Start-Process "./src/kiota/bin/Debug/net7.0/kiota" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow +Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder1" -Wait -NoNewWindow +Start-Process "$kiotaExec" -ArgumentList "generate --exclude-backward-compatible --clean-output --language ${language} --openapi ${targetOpenapiPath} --dvr all --output $tmpFolder2" -Wait -NoNewWindow # Remove variable output files -Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") +Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log") } -Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") +Remove-Item (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json") if (Test-Path (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log")) { Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log") } @@ -84,8 +84,6 @@ Get-FileHash -InputStream ([IO.MemoryStream]::new([char[]]$HashString2)) Write-Output "Folder 1: $tmpFolder1" Write-Output "Folder 2: $tmpFolder2" -diff -r --color $tmpFolder1 $tmpFolder2 - if ($HashString1 -eq $HashString2) { Write-Output "The content of the folders is identical" From 7cdac6dc857959b3c1ec9e71bd770fbcab70e291 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Wed, 4 Oct 2023 11:38:08 +0100 Subject: [PATCH 6/6] cleanup --- .github/workflows/integration-tests.yml | 47 ++++++++++++------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index 6c7623c903..c53e44ff15 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -1,31 +1,30 @@ name: integration-tests on: - # workflow_dispatch: + workflow_dispatch: push: - # TEST in CI - # branches: [main] - # paths-ignore: - # [ - # "abstractions/**", - # "authentication/**", - # "serialization/**", - # "http/**", - # "**.md", - # ".vscode/**", - # "**.svg", - # ] - # pull_request: - # paths-ignore: - # [ - # "abstractions/**", - # "authentication/**", - # "serialization/**", - # "http/**", - # "**.md", - # ".vscode/**", - # "**.svg", - # ] + branches: [main] + paths-ignore: + [ + "abstractions/**", + "authentication/**", + "serialization/**", + "http/**", + "**.md", + ".vscode/**", + "**.svg", + ] + pull_request: + paths-ignore: + [ + "abstractions/**", + "authentication/**", + "serialization/**", + "http/**", + "**.md", + ".vscode/**", + "**.svg", + ] concurrency: # Only run once for latest commit per ref and cancel other (previous) runs.