Skip to content

Commit

Permalink
Generate readme after running test
Browse files Browse the repository at this point in the history
  • Loading branch information
alanwest committed Oct 24, 2023
1 parent 26fdf70 commit 624f9fa
Show file tree
Hide file tree
Showing 9 changed files with 172 additions and 200 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ public void OnNext(KeyValuePair<string, object?> value)
info.SetValues(actionMethodEventData.ActionDescriptor);
break;
case OnStopEvent:
// Can't update RouteInfo here because the response is already written.
context = value.Value as HttpContext;
Debug.Assert(context != null, "HttpContext was null");
info = context.Items["RouteInfo"] as RouteInfo;
Debug.Assert(info != null, "RouteInfo object not present in context.Items");
info.SetValues(context);
RouteInfoMiddleware.RouteInfos.Add(info);
break;
default:
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -507,12 +507,12 @@
{
"HttpMethod": "GET",
"Path": "/MinimalApi",
"HttpRouteByRawText": null,
"HttpRouteByRawText": "/MinimalApi/",
"HttpRouteByControllerActionAndParameters": "",
"HttpRouteByActionDescriptor": "",
"DebugInfo": {
"RawText": null,
"RouteDiagnosticMetadata": null,
"RawText": "/MinimalApi/",
"RouteDiagnosticMetadata": "/MinimalApi/",
"RouteData": {},
"AttributeRouteInfo": null,
"ActionParameters": null,
Expand All @@ -530,13 +530,15 @@
{
"HttpMethod": "GET",
"Path": "/MinimalApi/123",
"HttpRouteByRawText": null,
"HttpRouteByRawText": "/MinimalApi/{id}",
"HttpRouteByControllerActionAndParameters": "",
"HttpRouteByActionDescriptor": "",
"DebugInfo": {
"RawText": null,
"RouteDiagnosticMetadata": null,
"RouteData": {},
"RawText": "/MinimalApi/{id}",
"RouteDiagnosticMetadata": "/MinimalApi/{id}",
"RouteData": {
"id": "123"
},
"AttributeRouteInfo": null,
"ActionParameters": null,
"PageActionDescriptorRelativePath": null,
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,66 +18,35 @@

using System.Diagnostics;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using static System.Net.Mime.MediaTypeNames;

namespace RouteTests;

public class RouteInfoMiddleware
{
public static readonly List<RouteInfo> RouteInfos = new();
private readonly RequestDelegate next;

public RouteInfoMiddleware(RequestDelegate next)
{
this.next = next;
}

public static void ConfigureExceptionHandler(IApplicationBuilder builder)
public async Task InvokeAsync(HttpContext context)
{
builder.Run(async context =>
if (context.Request.Path.ToString().Contains("GetLastRouteInfo"))
{
context.Response.Body = (context.Items["originBody"] as Stream)!;

context.Response.ContentType = Application.Json;

var info = context.Items["RouteInfo"] as RouteInfo;
var response = context.Response;
var info = RouteInfos.Last();
Debug.Assert(info != null, "RouteInfo object not present in context.Items");
var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
string modifiedResponse = JsonSerializer.Serialize(info, jsonOptions);
await context.Response.WriteAsync(modifiedResponse);
});
}

public async Task InvokeAsync(HttpContext context)
{
var response = context.Response;

var originBody = response.Body;
context.Items["originBody"] = originBody;
using var newBody = new MemoryStream();
response.Body = newBody;

await this.next(context);

var stream = response.Body;
using var reader = new StreamReader(stream, leaveOpen: true);
var originalResponse = await reader.ReadToEndAsync();

var info = context.Items["RouteInfo"] as RouteInfo;
Debug.Assert(info != null, "RouteInfo object not present in context.Items");
var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
string modifiedResponse = JsonSerializer.Serialize(info, jsonOptions);

stream.SetLength(0);
using var writer = new StreamWriter(stream, leaveOpen: true);
await writer.WriteAsync(modifiedResponse);
await writer.FlushAsync();
response.ContentLength = stream.Length;
response.ContentType = "application/json";

newBody.Seek(0, SeekOrigin.Begin);
await newBody.CopyToAsync(originBody);
response.Body = originBody;
response.ContentType = "application/json";
await response.WriteAsync(modifiedResponse);
}
else
{
await this.next(context);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public class RouteTestCase

public string? HttpMethod { get; set; }

public string? Path { get; set; }
public string Path { get; set; } = string.Empty;

public int ExpectedStatusCode { get; set; }

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// <copyright file="RoutingTestFixture.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

#nullable enable

using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;

namespace RouteTests;

public class RoutingTestFixture : IDisposable
{
private readonly Dictionary<TestApplicationScenario, WebApplication> apps = new();
private readonly HttpClient client = new();
private readonly AspNetCoreDiagnosticObserver diagnostics = new();
private readonly List<TestResult> testResults = new();

public RoutingTestFixture()
{
foreach (var scenario in Enum.GetValues<TestApplicationScenario>())
{
this.apps.Add(scenario, TestApplicationFactory.CreateApplication(scenario));
}

foreach (var app in this.apps)
{
app.Value.RunAsync();
}
}

public async Task MakeRequest(TestApplicationScenario scenario, string path)
{
var app = this.apps[scenario];
var baseUrl = app.Urls.First();
var url = $"{baseUrl}{path}";
await this.client.GetAsync(url).ConfigureAwait(false);
}

public void AddTestResult(TestResult testResult)
{
var app = this.apps[testResult.TestCase.TestApplicationScenario];
var baseUrl = app.Urls.First();
var url = $"{baseUrl}/GetLastRouteInfo";
var responseMessage = this.client.GetAsync(url).ConfigureAwait(false).GetAwaiter().GetResult();
var response = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var info = JsonSerializer.Deserialize<RouteInfo>(response);
testResult.RouteInfo = info;
this.testResults.Add(testResult);
}

public void Dispose()
{
foreach (var app in this.apps)
{
app.Value.DisposeAsync().GetAwaiter().GetResult();
}

this.client.Dispose();
this.diagnostics.Dispose();

this.GenerateReadme();
}

private void GenerateReadme()
{
var sb = new StringBuilder();
sb.AppendLine("| | | display name | expected name (w/o http.method) | routing type | request |");
sb.AppendLine("| - | - | - | - | - | - |");

for (var i = 0; i < this.testResults.Count; ++i)
{
var result = this.testResults[i];
var emoji = result.ActivityDisplayName.Equals(result.TestCase.ExpectedHttpRoute, StringComparison.InvariantCulture)
? ":green_heart:"
: ":broken_heart:";
sb.Append($"| {emoji} | [{i + 1}](#{i + 1}) ");
sb.AppendLine(FormatTestResult(result));
}

for (var i = 0; i < this.testResults.Count; ++i)
{
var result = this.testResults[i];
sb.AppendLine();
sb.AppendLine($"#### {i + 1}");
sb.AppendLine();
sb.AppendLine("```json");
sb.AppendLine(result.RouteInfo.ToString());
sb.AppendLine("```");
}

File.WriteAllText(Path.Combine("..", "..", "..", "RouteTests", "README.md"), sb.ToString());

string FormatTestResult(TestResult result)
{
var testCase = result.TestCase!;

return $"| {string.Join(
" | ",
result.ActivityDisplayName, // TODO: should be result.HttpRoute, but http.route is not currently added to Activity
testCase.ExpectedHttpRoute,
testCase.TestApplicationScenario,
$"{testCase.HttpMethod} {testCase.Path}",
result.ActivityDisplayName)} |";
}
}
}
Loading

0 comments on commit 624f9fa

Please sign in to comment.