Skip to content

Commit

Permalink
update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mpdreamz committed Dec 1, 2023
1 parent 187f6f7 commit 7a2b3a7
Show file tree
Hide file tree
Showing 14 changed files with 173 additions and 189 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,22 @@ internal static class HttpRequestExtensions
internal static string ExtractRequestBody(this HttpRequest request, IConfiguration configuration, out bool longerThanMaxLength)
{
//Ensure the request Microsoft.AspNetCore.Http.HttpRequest.Body can be read multiple times
#pragma warning disable CS0162 // Unreachable code detected
request.EnableBuffering();

if (request.HasFormContentType)
{
var form = new AspNetCoreHttpForm(request.Form);
return form.AsSanitizedString(configuration, out longerThanMaxLength);
}
else
{
// allow synchronous reading of the request stream, which is false by default from 3.0 onwards.
// Reading must be synchronous as it can happen within a synchronous diagnostic listener method
var bodyControlFeature = request.HttpContext.Features.Get<IHttpBodyControlFeature>();
if (bodyControlFeature != null)
bodyControlFeature.AllowSynchronousIO = true;
// allow synchronous reading of the request stream, which is false by default from 3.0 onwards.
// Reading must be synchronous as it can happen within a synchronous diagnostic listener method
var bodyControlFeature = request.HttpContext.Features.Get<IHttpBodyControlFeature>();
if (bodyControlFeature != null)
bodyControlFeature.AllowSynchronousIO = true;

return RequestBodyStreamHelper.ToString(request.Body, out longerThanMaxLength);
}
return RequestBodyStreamHelper.ToString(request.Body, out longerThanMaxLength);
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
11 changes: 11 additions & 0 deletions test/Elastic.Apm.Tests.Utilities/XUnit/DisabledTestFact.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System;
using Xunit;

namespace Elastic.Apm.Tests.Utilities.XUnit;
Expand All @@ -16,3 +17,13 @@ public DisabledTestFact(string reason, string issueLink = null)
Skip += $", issue link: {issueLink}";
}
}

public sealed class FactRequiresMvcTestingFix : FactAttribute
{
public FactRequiresMvcTestingFix()
{
if (Environment.Version.Major < 7) return;
Skip = $"This Test is disabled on .NET 7 until https://github.com/dotnet/aspnetcore/issues/45233";
}
}

2 changes: 1 addition & 1 deletion test/Elastic.Apm.Tests.Utilities/XUnit/MemberData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public static IEnumerable<object[]> TestWithDiagnosticSourceOnly()
yield return new object[] { false };
//
// Skip "DiagnosticSourceOnly" tests on .NET 7
// until https://github.com/dotnet/aspnetcore/issues/45233 is resolved.
// until is resolved.
//
if (Environment.Version.Major < 7)
yield return new object[] { true };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ public ConfigTests(WebApplicationFactory<Startup> factory, ITestOutputHelper xUn
/// Tests for: https://github.com/elastic/apm-agent-dotnet/issues/1077
/// </summary>
/// <param name="withDiagnosticSourceOnly"></param>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task AgentDisabledInAppConfig(bool withDiagnosticSourceOnly)
[Fact]
public async Task AgentDisabledInAppConfig()
{
var defaultServerUrlConnectionMade = false;

Expand Down Expand Up @@ -65,9 +64,8 @@ public async Task AgentDisabledInAppConfig(bool withDiagnosticSourceOnly)
new NoopLogger(),
new RuntimeConfigurationSnapshot(configReader)));

var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, _factory);
if (withDiagnosticSourceOnly)
Agent.Setup(agent);
var client = Helper.ConfigureHttpClient(true, agent, _factory);
Agent.Setup(agent);

var response = await client.GetAsync("/Home/StartTransactionWithAgentApi");
response.IsSuccessStatusCode.Should().BeTrue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public ApmConfigurationIntegrationTests(WebApplicationFactory<Startup> factory)

_agent = new ApmAgent(
new AgentComponents(payloadSender: capturedPayload, configurationReader: config, logger: _logger));
_client = Helper.GetClient(_agent, _factory, true);
_client = Helper.GetClient(_agent, _factory);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,12 @@ private ApmAgent CreateAspNetCoreAgent(out MockPayloadSender payloadSender)
/// <summary>
/// Simulates an HTTP GET call to /home/simplePage and asserts on what the agent should send to the server
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task HomeSimplePageTransactionTest(bool withDiagnosticSourceOnly)
[Fact]
public async Task HomeSimplePageTransactionTest()
{
using var agent = CreateAspNetCoreAgent(out var payloadSender);
await using var factory = new WebApplicationFactory<Startup>();
using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);

var headerKey = "X-Additional-Header";
var headerValue = "For-Elastic-Apm-Agent";
Expand Down Expand Up @@ -149,19 +148,17 @@ public async Task HomeSimplePageTransactionTest(bool withDiagnosticSourceOnly)
/// <summary>
/// Creates an agent with Enabled=false and makes sure the agent does not capture anything.
/// </summary>
/// <param name="withDiagnosticSourceOnly"></param>
/// <returns></returns>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task HomeIndexTransactionWithEnabledFalse(bool withDiagnosticSourceOnly)
[Fact]
public async Task HomeIndexTransactionWithEnabledFalse()
{
var payloadSender = new MockPayloadSender();
await using var factory = new WebApplicationFactory<Startup>();
using var agent = new ApmAgent(new TestAgentComponents(
_logger,
new MockConfiguration(_logger, enabled: "false", exitSpanMinDuration: "0"), payloadSender));

using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);

var response = await client.GetAsync("/Home/Index");

Expand All @@ -173,16 +170,15 @@ public async Task HomeIndexTransactionWithEnabledFalse(bool withDiagnosticSource
payloadSender.Errors.Should().BeNullOrEmpty();
}

[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task HomeIndexTransactionWithToggleRecording(bool withDiagnosticSourceOnly)
[Fact]
public async Task HomeIndexTransactionWithToggleRecording()
{
var payloadSender = new MockPayloadSender();
await using var factory = new WebApplicationFactory<Startup>();
using var agent = new ApmAgent(new TestAgentComponents(
_logger, new MockConfiguration(recording: "false", exitSpanMinDuration: "0"), payloadSender));

using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);

var response = await client.GetAsync("/Home/Index");

Expand Down Expand Up @@ -214,13 +210,12 @@ public async Task HomeIndexTransactionWithToggleRecording(bool withDiagnosticSou
/// Simulates an HTTP POST call to /home/simplePage and asserts on what the agent should send to the server
/// to test the 'CaptureBody' configuration option
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task HomeSimplePagePostTransactionTest(bool withDiagnosticSourceOnly)
[FactRequiresMvcTestingFix]
public async Task HomeSimplePagePostTransactionTest()
{
using var agent = CreateAspNetCoreAgent(out var payloadSender);
await using var factory = new WebApplicationFactory<Startup>();
using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);
var headerKey = "X-Additional-Header";
var headerValue = "For-Elastic-Apm-Agent";
client.DefaultRequestHeaders.Add(headerKey, headerValue);
Expand Down Expand Up @@ -310,13 +305,12 @@ public async Task HomeSimplePagePostTransactionTest(bool withDiagnosticSourceOnl
/// Simulates an HTTP GET call to /home/index and asserts that the agent captures spans.
/// Prerequisite: The /home/index has to generate spans (which should be the case).
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task HomeIndexSpanTest(bool withDiagnosticSourceOnly)
[Fact]
public async Task HomeIndexSpanTest()
{
using var agent = CreateAspNetCoreAgent(out var payloadSender);
await using var factory = new WebApplicationFactory<Startup>();
using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);
var response = await client.GetAsync("/Home/Index");

response.IsSuccessStatusCode.Should().BeTrue();
Expand All @@ -331,13 +325,12 @@ public async Task HomeIndexSpanTest(bool withDiagnosticSourceOnly)
/// Prerequisite: The /home/index has to generate spans (which should be the case).
/// It also assumes that /home/index makes a requrst to github.com
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task HomeIndexDestinationTest(bool withDiagnosticSourceOnly)
[Fact]
public async Task HomeIndexDestinationTest()
{
using var agent = CreateAspNetCoreAgent(out var payloadSender);
await using var factory = new WebApplicationFactory<Startup>();
using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);
var response = await client.GetAsync("/Home/Index");

response.IsSuccessStatusCode.Should().BeTrue();
Expand All @@ -357,13 +350,12 @@ public async Task HomeIndexDestinationTest(bool withDiagnosticSourceOnly)
/// Simulates an HTTP GET call to /Home/Index?captureControllerActionAsSpan=true
/// and asserts that all automatically captured spans are children of the span for controller's action.
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task HomeIndexAutoCapturedSpansAreChildrenOfControllerActionAsSpan(bool withDiagnosticSourceOnly)
[Fact]
public async Task HomeIndexAutoCapturedSpansAreChildrenOfControllerActionAsSpan()
{
using var agent = CreateAspNetCoreAgent(out var payloadSender);
await using var factory = new WebApplicationFactory<Startup>();
using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);
var response = await client.GetAsync("/Home/Index?captureControllerActionAsSpan=true");

response.IsSuccessStatusCode.Should().BeTrue();
Expand Down Expand Up @@ -398,13 +390,12 @@ public async Task HomeIndexAutoCapturedSpansAreChildrenOfControllerActionAsSpan(
/// With other words: there is no error page with an exception handler configured in the ASP.NET Core pipeline.
/// Makes sure that we still capture the failed request.
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task FailingRequestWithoutConfiguredExceptionPage(bool withDiagnosticSourceOnly)
[Fact]
public async Task FailingRequestWithoutConfiguredExceptionPage()
{
using var agent = CreateAspNetCoreAgent(out var payloadSender);
await using var factory = new WebApplicationFactory<Startup>();
using var client = Helper.ConfigureHttpClient(false, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(false, agent, factory);

Func<Task> act = async () => await client.GetAsync("Home/TriggerError");
await act.Should().ThrowAsync<Exception>();
Expand Down Expand Up @@ -436,13 +427,12 @@ public async Task FailingRequestWithoutConfiguredExceptionPage(bool withDiagnost
/// With other words: there is no error page with an exception handler configured in the ASP.NET Core pipeline.
/// Makes sure that we still capture the failed request along with the request body
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task FailingPostRequestWithoutConfiguredExceptionPage(bool withDiagnosticSourceOnly)
[FactRequiresMvcTestingFix]
public async Task FailingPostRequestWithoutConfiguredExceptionPage()
{
using var agent = CreateAspNetCoreAgent(out var payloadSender);
await using var factory = new WebApplicationFactory<Startup>();
using var client = Helper.ConfigureHttpClient(false, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(false, agent, factory);

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Expand Down Expand Up @@ -494,13 +484,12 @@ public async Task AspNetCoreDiagnosticSubscriber_Should_Be_Registered_Only_Once(
/// An HTTP call to an action method which manually sets <see cref="IExecutionSegment.Outcome"/>.
/// Makes sure auto instrumentation does not overwrite the outcome.
/// </summary>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task ManualTransactionOutcomeTest(bool withDiagnosticSourceOnly)
[Fact]
public async Task ManualTransactionOutcomeTest()
{
await using var factory = new WebApplicationFactory<Startup>();
using var agent = CreateAspNetCoreAgent(out var payloadSender);
using var client = Helper.ConfigureHttpClient(true, withDiagnosticSourceOnly, agent, factory);
using var client = Helper.ConfigureHttpClient(true, agent, factory);

await client.GetAsync("/Home/SampleWithManuallySettingOutcome");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,13 @@ public class AspNetCoreDiagnosticListenerTest : IClassFixture<WebApplicationFact
/// and makes sure that the error is captured.
/// </summary>
/// <returns>The error in ASP net core.</returns>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task TestErrorInAspNetCore(bool useOnlyDiagnosticSource)
[Fact]
public async Task TestErrorInAspNetCore()
{
var capturedPayload = new MockPayloadSender();
using (var agent = new ApmAgent(new TestAgentComponents(payloadSender: capturedPayload, configuration: new MockConfiguration(exitSpanMinDuration: "0"))))
{
var client = Helper.GetClient(agent, _factory, useOnlyDiagnosticSource);
var client = Helper.GetClient(agent, _factory);

try
{
Expand Down Expand Up @@ -90,9 +89,8 @@ public async Task TestErrorInAspNetCore(bool useOnlyDiagnosticSource)
/// retrieved from the HttpRequest
/// </summary>
/// <returns>The error in ASP net core.</returns>
[Theory]
[MemberData(nameof(MemberData.TestWithDiagnosticSourceOnly), MemberType = typeof(MemberData))]
public async Task TestJsonBodyRetrievalOnRequestFailureInAspNetCore(bool useOnlyDiagnosticSource)
[Fact]
public async Task TestJsonBodyRetrievalOnRequestFailureInAspNetCore()
{
var capturedPayload = new MockPayloadSender();
using (var agent = new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(
Expand All @@ -101,7 +99,7 @@ public async Task TestJsonBodyRetrievalOnRequestFailureInAspNetCore(bool useOnly
captureBodyContentTypes: ConfigConsts.DefaultValues.CaptureBodyContentTypes),
payloadSender: capturedPayload)))
{
var client = Helper.GetClient(agent, _factory, useOnlyDiagnosticSource);
var client = Helper.GetClient(agent, _factory);

var body = "{\"id\" : \"1\"}";
await client.PostAsync("api/Home/PostError", new StringContent(body, Encoding.UTF8, "application/json"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@
using System.Threading.Tasks;
using Elastic.Apm.AspNetCore.DiagnosticListener;
using Elastic.Apm.EntityFrameworkCore;
using Elastic.Apm.Logging;
using Elastic.Apm.Tests.Utilities;
using Elastic.Apm.Tests.Utilities.XUnit;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using SampleAspNetCoreApp;
using Xunit;
using Xunit.Abstractions;

namespace Elastic.Apm.AspNetCore.Tests
{
Expand All @@ -26,14 +29,21 @@ public class DiagnosticListenerTests : IClassFixture<WebApplicationFactory<Start

private readonly HttpClient _client;

public DiagnosticListenerTests(WebApplicationFactory<Startup> factory)
public DiagnosticListenerTests(WebApplicationFactory<Startup> factory, ITestOutputHelper output)
{
_agent = new ApmAgent(new TestAgentComponents(configuration: new MockConfiguration(exitSpanMinDuration: "0")));
_capturedPayload = _agent.PayloadSender as MockPayloadSender;
var logger = new XUnitLogger(LogLevel.Trace, output);
_capturedPayload = new MockPayloadSender(logger);
_agent = new ApmAgent(
new TestAgentComponents(
configuration: new MockConfiguration(exitSpanMinDuration: "0", flushInterval: "0"),
payloadSender: _capturedPayload,
logger: logger
)
);

//This registers the middleware without activating any listeners,
//so no error capturing and no EFCore listener.
_client = Helper.GetClientWithoutDiagnosticListeners(_agent, factory);
_client = Helper.GetClientWithoutDiagnosticListeners(factory);
}

/// <summary>
Expand Down Expand Up @@ -65,6 +75,8 @@ public async Task SubscribeAndUnsubscribeAspNetCoreDiagnosticListener()

await _client.GetAsync("/Home/TriggerError");

_capturedPayload.WaitForTransactions(TimeSpan.FromSeconds(10));

_capturedPayload.Transactions.Should().ContainSingle();
_capturedPayload.Errors.Should().BeEmpty();
}
Expand All @@ -83,6 +95,8 @@ public async Task SubscribeAndUnsubscribeEfCoreDiagnosticListener()
{
await _client.GetAsync("/Home/Index");

_capturedPayload.WaitForTransactions(TimeSpan.FromSeconds(10));

_capturedPayload.Transactions.Should().ContainSingle();

_capturedPayload.SpansOnFirstTransaction.Should()
Expand All @@ -94,6 +108,8 @@ public async Task SubscribeAndUnsubscribeEfCoreDiagnosticListener()

await _client.GetAsync("/Home/Index");

_capturedPayload.WaitForTransactions(TimeSpan.FromSeconds(10));

_capturedPayload.Transactions.Should().ContainSingle();

_capturedPayload.SpansOnFirstTransaction.Should().BeEmpty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

<ItemGroup>
<PackageReference Include="Moq" Version="4.12.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.14" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="7.0.0" />
</ItemGroup>
Expand Down
Loading

0 comments on commit 7a2b3a7

Please sign in to comment.