From 9cd1bec35b6c5a65f9593a5370f34523e2ff3b26 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Thu, 4 Nov 2021 10:58:39 -0400 Subject: [PATCH] - additional unit tests fixes for go snippets generation Signed-off-by: Vincent Biret --- .../GoGeneratorTests.cs | 27 ++++++++------ .../LanguageGenerators/GoGenerator.cs | 37 +++++++++---------- 2 files changed, 33 insertions(+), 31 deletions(-) diff --git a/CodeSnippetsReflection.OpenAPI.Test/GoGeneratorTests.cs b/CodeSnippetsReflection.OpenAPI.Test/GoGeneratorTests.cs index 064912022..d189f7f67 100644 --- a/CodeSnippetsReflection.OpenAPI.Test/GoGeneratorTests.cs +++ b/CodeSnippetsReflection.OpenAPI.Test/GoGeneratorTests.cs @@ -105,7 +105,7 @@ public async Task WritesALongAndFindsAnAction() { }; var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("10L", result); + Assert.Contains("int64(10)", result); Assert.DoesNotContain("microsoft.graph", result); } [Fact] @@ -118,7 +118,7 @@ public async Task WritesADouble() { }; var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("10d", result); + Assert.Contains("float64(10)", result); } [Fact] public async Task GeneratesABinaryPayload() { @@ -128,7 +128,7 @@ public async Task GeneratesABinaryPayload() { requestPayload.Content.Headers.ContentType = new ("application/octect-stream"); var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("new MemoryStream", result); + Assert.Contains("make([]byte, 0)", result); } [Fact] public async Task GeneratesABase64UrlPayload() { @@ -138,7 +138,7 @@ public async Task GeneratesABase64UrlPayload() { }; var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("Encoding.ASCII.GetBytes", result); + Assert.Contains("[]byte(", result); } [Fact] public async Task GeneratesADateTimeOffsetPayload() { @@ -148,7 +148,7 @@ public async Task GeneratesADateTimeOffsetPayload() { }; var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("DateTimeOffset.Parse", result); + Assert.Contains(",err := time.Parse(time.RFC3339,", result); } [Fact] public async Task GeneratesAnArrayPayloadInAdditionalData() { @@ -158,8 +158,9 @@ public async Task GeneratesAnArrayPayloadInAdditionalData() { }; var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("new List", result); - Assert.Contains("AdditionalData", result); + Assert.Contains("map[string]interface{}{", result); + Assert.Contains("[]String {", result); + Assert.Contains("SetAdditionalData", result); Assert.Contains("members", result); // property name hasn't been changed } [Fact] @@ -167,8 +168,12 @@ public async Task GeneratesSelectQueryParameters() { using var requestPayload = new HttpRequestMessage(HttpMethod.Get, $"{ServiceRootUrl}/me?$select=displayName,id"); var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("displayName", result); - Assert.Contains("(q) =>", result); + Assert.Contains("Select: \"displayName", result); + Assert.Contains("Q: ", result); + Assert.Contains("MeRequestBuilderGetQueryParameters", result); + Assert.Contains("MeRequestBuilderGetOptions", result); + Assert.Contains("options :=", result); + Assert.Contains("requestParameters :=", result); } [Fact] public async Task GeneratesCountBooleanQueryParameters() { @@ -202,8 +207,8 @@ public async Task GeneratesRequestHeaders() { requestPayload.Headers.Add("ConsistencyLevel", "eventual"); var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1TreeNode()); var result = _generator.GenerateCodeSnippet(snippetModel); - Assert.Contains("Add(\"ConsistencyLevel\", \"eventual\");", result); - Assert.Contains("(h) =>", result); + Assert.Contains("\"ConsistencyLevel\": \"eventual\"", result); + Assert.Contains("H: headers", result); } //TODO test for DateTimeOffset } diff --git a/CodeSnippetsReflection.OpenAPI/LanguageGenerators/GoGenerator.cs b/CodeSnippetsReflection.OpenAPI/LanguageGenerators/GoGenerator.cs index af0d10fdb..a819f8d24 100644 --- a/CodeSnippetsReflection.OpenAPI/LanguageGenerators/GoGenerator.cs +++ b/CodeSnippetsReflection.OpenAPI/LanguageGenerators/GoGenerator.cs @@ -59,7 +59,7 @@ private static (string, string) GetRequestHeaders(SnippetModel snippetModel, Ind private static (string, string) GetOptionsParameter(SnippetModel model, IndentManager indentManager, string payloadParam, string queryParamsParam, string headersParam) { var nonEmptyParameters = new string[] { payloadParam, queryParamsParam, headersParam}.Where(p => !string.IsNullOrEmpty(p)); if(nonEmptyParameters.Any()) { - var className = $"{model.PathNodes.Last().GetClassName("RequestBuilder")}{model.Method.ToString().ToFirstCharacterUpperCase()}Options"; + var className = $"{model.PathNodes.Last().GetClassName("RequestBuilder").ToFirstCharacterUpperCase()}{model.Method.ToString().ToLowerInvariant().ToFirstCharacterUpperCase()}Options"; var payloadSB = new StringBuilder(); payloadSB.AppendLine($"{indentManager.GetIndent()}{optionsParameterVarName} := &{className}{{"); indentManager.Indent(); @@ -78,9 +78,8 @@ private static (string, string) GetOptionsParameter(SnippetModel model, IndentMa private static (string, string) GetRequestQueryParameters(SnippetModel model, IndentManager indentManager) { var payloadSB = new StringBuilder(); if(!string.IsNullOrEmpty(model.QueryString)) { - var className = $"{model.PathNodes.Last().GetClassName("RequestBuilder")}{model.Method.ToString().ToFirstCharacterUpperCase()}QueryParameters"; + var className = $"msgraphsdk.{model.PathNodes.Last().GetClassName("RequestBuilder").ToFirstCharacterUpperCase()}{model.Method.ToString().ToLowerInvariant().ToFirstCharacterUpperCase()}QueryParameters"; payloadSB.AppendLine($"{indentManager.GetIndent()}{requestParametersVarName} := &{className}{{"); - payloadSB.AppendLine($"{indentManager.GetIndent()}{{"); indentManager.Indent(); var (queryString, replacements) = ReplaceNestedOdataQueryParameters(model.QueryString); foreach(var queryParam in queryString.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) { @@ -150,55 +149,53 @@ private static (string, string) GetRequestPayloadAndVariableName(SnippetModel sn } private static void WriteJsonObjectValue(StringBuilder payloadSB, JsonElement value, OpenApiSchema schema, IndentManager indentManager, bool includePropertyAssignment = true, string variableName = default) { if (value.ValueKind != JsonValueKind.Object) throw new InvalidOperationException($"Expected JSON object and got {value.ValueKind}"); - indentManager.Indent(); var propertiesAndSchema = value.EnumerateObject() .Select(x => new Tuple(x, schema.GetPropertySchema(x.Name))); + if(!string.IsNullOrEmpty(variableName)) + variableName += "."; foreach(var propertyAndSchema in propertiesAndSchema.Where(x => x.Item2 != null)) { var propertyName = propertyAndSchema.Item1.Name.ToFirstCharacterUpperCase(); - var propertyAssignment = includePropertyAssignment ? $"{indentManager.GetIndent()}{propertyName} := " : string.Empty; - WriteProperty(payloadSB, propertyAndSchema.Item1.Value, propertyAndSchema.Item2, indentManager, propertyAssignment); + var propertyAssignment = includePropertyAssignment ? $"{variableName}Set{indentManager.GetIndent()}{propertyName}(" : string.Empty; + WriteProperty(payloadSB, propertyAndSchema.Item1.Value, propertyAndSchema.Item2, indentManager, propertyAssignment, ")"); } var propertiesWithoutSchema = propertiesAndSchema.Where(x => x.Item2 == null).Select(x => x.Item1); if(propertiesWithoutSchema.Any()) { - payloadSB.AppendLine($"{indentManager.GetIndent()}{variableName}.SetAdditionalData(map[string]interface{{}}{{"); + payloadSB.AppendLine($"{indentManager.GetIndent()}{variableName}SetAdditionalData(map[string]interface{{}}{{"); indentManager.Indent(); foreach(var property in propertiesWithoutSchema) { var propertyAssignment = $"{indentManager.GetIndent()}\"{property.Name}\": "; - WriteProperty(payloadSB, property.Value, null, indentManager, propertyAssignment); + WriteProperty(payloadSB, property.Value, null, indentManager, propertyAssignment, ","); } indentManager.Unindent(); payloadSB.AppendLine($"{indentManager.GetIndent()}}}"); } - indentManager.Unindent(); } private static void WriteProperty(StringBuilder payloadSB, JsonElement value, OpenApiSchema propSchema, IndentManager indentManager, string propertyAssignment, string propertySuffix = default) { switch (value.ValueKind) {// TODO: this function needs to be splat between declaring the properties and assigning them with pointers case JsonValueKind.String: if(propSchema?.Format?.Equals("base64url", StringComparison.OrdinalIgnoreCase) ?? false) - payloadSB.AppendLine($"{propertyAssignment}[]byte(\"{value.GetString()}\"){propertySuffix},"); + payloadSB.AppendLine($"{propertyAssignment}[]byte(\"{value.GetString()}\"){propertySuffix}"); else if (propSchema?.Format?.Equals("date-time", StringComparison.OrdinalIgnoreCase) ?? false) - payloadSB.AppendLine($"{propertyAssignment}time.Parse(time.RFC3339, \"{value.GetString()}\"){propertySuffix},"); + payloadSB.AppendLine($"{propertyAssignment}time.Parse(time.RFC3339, \"{value.GetString()}\"){propertySuffix}"); else if (propSchema?.Format?.Equals("guid", StringComparison.OrdinalIgnoreCase) ?? false) - payloadSB.AppendLine($"{propertyAssignment}uuid.MustParse(\"{value.GetString()}\"){propertySuffix},"); + payloadSB.AppendLine($"{propertyAssignment}uuid.MustParse(\"{value.GetString()}\"){propertySuffix}"); else - payloadSB.AppendLine($"{propertyAssignment}\"{value.GetString()}\"{propertySuffix},"); + payloadSB.AppendLine($"{propertyAssignment}\"{value.GetString()}\"{propertySuffix}"); break; case JsonValueKind.Number: - payloadSB.AppendLine($"{propertyAssignment}{GetNumberLiteral(propSchema, value)}{propertySuffix},"); + payloadSB.AppendLine($"{propertyAssignment}{GetNumberLiteral(propSchema, value)}{propertySuffix}"); break; case JsonValueKind.False: case JsonValueKind.True: - payloadSB.AppendLine($"{propertyAssignment}{value.GetBoolean().ToString().ToLowerInvariant()}{propertySuffix},"); + payloadSB.AppendLine($"{propertyAssignment}{value.GetBoolean().ToString().ToLowerInvariant()}{propertySuffix}"); break; case JsonValueKind.Null: - payloadSB.AppendLine($"{propertyAssignment}nil{propertySuffix},"); + payloadSB.AppendLine($"{propertyAssignment}nil{propertySuffix}"); break; case JsonValueKind.Object: if(propSchema != null) { - payloadSB.AppendLine($"{propertyAssignment}msgraphsdk.New{propSchema.GetSchemaTitle().ToFirstCharacterUpperCase()}"); - payloadSB.AppendLine($"{indentManager.GetIndent()}{{"); + payloadSB.AppendLine($"{propertyAssignment}msgraphsdk.New{propSchema.GetSchemaTitle().ToFirstCharacterUpperCase()}{propertySuffix}"); WriteJsonObjectValue(payloadSB, value, propSchema, indentManager); - payloadSB.AppendLine($"{indentManager.GetIndent()}}}{propertySuffix},"); } break; case JsonValueKind.Array: @@ -213,7 +210,7 @@ private static void WriteJsonArrayValue(StringBuilder payloadSB, JsonElement val payloadSB.AppendLine($"{propertyAssignment} []{genericType} {{"); indentManager.Indent(); foreach(var item in value.EnumerateArray()) - WriteProperty(payloadSB, item, schema, indentManager, indentManager.GetIndent()); + WriteProperty(payloadSB, item, schema, indentManager, indentManager.GetIndent(), ","); indentManager.Unindent(); payloadSB.AppendLine($"{indentManager.GetIndent()}}}"); }