Skip to content

Commit

Permalink
Fix inconsistent tenant/activity test
Browse files Browse the repository at this point in the history
The test relied on accessing IHttpActivityFeature after the request
completed in order to extract the Activity to assert against.

However, the runtime
(https://github.com/dotnet/aspnetcore/blob/main/src/Hosting/Hosting/src/Internal/HostingApplication.cs)
actually sets the value of IHttpActivityFeature.Activity to null after
each request so that the IHttpActivityFeature can be recycled.

This commit works around this behavior by copying the Activity into a
custom feature.
  • Loading branch information
richardszalay committed Nov 19, 2024
1 parent 65ca00c commit a3bb54e
Showing 1 changed file with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Diagnostics;
using System.Security.Claims;
using Alba;
using Alba.Security;
Expand Down Expand Up @@ -357,7 +358,7 @@ public async Task does_tag_current_activity_with_tenant_id()
x.WithRequestHeader("tenant", "green");
});

var feature = result.Context.Features.Get<IHttpActivityFeature>();
var feature = result.Context.Features.Get<CustomActivityFeature>();
var activity = feature?.Activity;
activity.ShouldNotBeNull();
activity.Tags.ShouldContain(x => x.Key == "tenant.id" && x.Value == "green");
Expand All @@ -373,8 +374,12 @@ public static string GetTenantIdFromRoute(IMessageBus bus)
}

[WolverineGet("/tenant")]
public static string GetTenantIdFromWhatever(IMessageBus bus)
public static string GetTenantIdFromWhatever(IMessageBus bus, HttpContext httpContext)
{
// IHttpActivityFeature.Activity is set to null after the request, so to access the
// Activity in the test we capture the Activity into a custom Feature
httpContext.Features.Set(CustomActivityFeature.FromHttpContext(httpContext));

return bus.TenantId;
}

Expand Down Expand Up @@ -452,4 +457,17 @@ public class TenantTodo : ITenanted
public string Id { get; set; }
public string Description { get; set; }
public string TenantId { get; set; }
}

// Custom HttpContext Feature used to capture the Activity
// from IHttpActivityFeature.Activity, which is set to null by
// the runtime (HostingApplication) so the activity instance can
// be recycled.
public record CustomActivityFeature(Activity? Activity)
{
public static CustomActivityFeature FromHttpContext(HttpContext httpContext)
{
var activity = httpContext.Features.Get<IHttpActivityFeature>()?.Activity;
return new CustomActivityFeature(activity);
}
}

0 comments on commit a3bb54e

Please sign in to comment.