Skip to content

Commit

Permalink
- additional unit tests fixes for go snippets generation
Browse files Browse the repository at this point in the history
Signed-off-by: Vincent Biret <[email protected]>
  • Loading branch information
baywet committed Nov 4, 2021
1 parent 830ac94 commit 9cd1bec
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 31 deletions.
27 changes: 16 additions & 11 deletions CodeSnippetsReflection.OpenAPI.Test/GoGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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() {
Expand All @@ -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() {
Expand All @@ -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() {
Expand All @@ -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() {
Expand All @@ -158,17 +158,22 @@ 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]
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() {
Expand Down Expand Up @@ -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
}
Expand Down
37 changes: 17 additions & 20 deletions CodeSnippetsReflection.OpenAPI/LanguageGenerators/GoGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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)) {
Expand Down Expand Up @@ -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<JsonProperty, OpenApiSchema>(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:
Expand All @@ -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()}}}");
}
Expand Down

0 comments on commit 9cd1bec

Please sign in to comment.