diff --git a/docs/glossary.md b/docs/glossary.md
index 02547d1077..c767044459 100644
--- a/docs/glossary.md
+++ b/docs/glossary.md
@@ -418,7 +418,7 @@ A component in MTP that coordinates multi-process test execution. The orchestrat
### OpenTelemetry extension
-An MTP extension (`Microsoft.Testing.Extensions.OpenTelemetry`) that exports test session telemetry using the [OpenTelemetry](https://opentelemetry.io/) standard, enabling integration with distributed tracing and observability platforms.
+An MTP extension (`Microsoft.Testing.Extensions.OpenTelemetry`) that exposes test-session activities and metrics using the [OpenTelemetry](https://opentelemetry.io/) standard. `AddTestingPlatformDiagnostics()` activates the MTP diagnostics producer; application-owned providers configured through `HostApplicationBuilder`, Aspire ServiceDefaults, or another composition root subscribe with `AddTestingPlatformInstrumentation()`. The focused `AddTestingPlatformTestResource()` and `AddTestingPlatformCiResource()` helpers add test and CI metadata without replacing application-owned `service.*`, host, OS, or process identity. See the [`HostApplicationBuilder` sample](../samples/public/MTPOTel).
### OSConditionAttribute
diff --git a/samples/public/MTPOTel/MTPOTel.csproj b/samples/public/MTPOTel/MTPOTel.csproj
index 6f9c1a2484..bedca1b9f7 100644
--- a/samples/public/MTPOTel/MTPOTel.csproj
+++ b/samples/public/MTPOTel/MTPOTel.csproj
@@ -18,7 +18,9 @@
+
+
diff --git a/samples/public/MTPOTel/Program.cs b/samples/public/MTPOTel/Program.cs
index a1f6ac433d..2744f095f9 100644
--- a/samples/public/MTPOTel/Program.cs
+++ b/samples/public/MTPOTel/Program.cs
@@ -1,18 +1,22 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
+// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
+using System.Diagnostics;
using System.Threading.Tasks;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
using Microsoft.Testing.Extensions;
using Microsoft.Testing.Platform.Builder;
+using Microsoft.Testing.Platform.Capabilities.TestFramework;
using Microsoft.Testing.Platform.Extensions.Messages;
using Microsoft.Testing.Platform.Extensions.TestFramework;
using Microsoft.Testing.Platform.Messages;
-using Microsoft.Testing.Platform.Capabilities.TestFramework;
using Microsoft.Testing.Platform.Services;
using Microsoft.Testing.Platform.TestHost;
using OpenTelemetry.Metrics;
+using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
namespace MTPOTel;
@@ -21,29 +25,44 @@ public class Program
{
public static async Task Main(string[] args)
{
+ using var testActivitySource = new ActivitySource("MTPOTel.Tests");
+ HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
+
+ // The host owns the OpenTelemetry providers, just like an Aspire ServiceDefaults project or any other
+ // application composition root. The focused MTP resource helpers add test/CI identity without replacing
+ // the service.name, host, OS, or process identity already configured by the application.
+ hostBuilder.Services.AddOpenTelemetry()
+ .ConfigureResource(resource => resource
+ .AddService("MTPOTel")
+ .AddTestingPlatformTestResource()
+ .AddTestingPlatformCiResource())
+ .WithTracing(tracing => tracing
+ .AddSource(testActivitySource.Name)
+ .AddTestingPlatformInstrumentation()
+ .AddConsoleExporter())
+ .WithMetrics(metrics => metrics
+ .AddTestingPlatformInstrumentation()
+ .AddConsoleExporter());
+
+ using IHost host = hostBuilder.Build();
+ await host.StartAsync();
+
ITestApplicationBuilder testApplicationBuilder = await TestApplication.CreateBuilderAsync(args);
// Register our simple test framework
testApplicationBuilder.RegisterTestFramework(
_ => new TestFrameworkCapabilities(),
- (capabilities, serviceProvider) => new SimpleTestFramework(serviceProvider));
-
- // Enable OpenTelemetry with console exporter. AddOpenTelemetryProvider does not register any instrumentation
- // or exporter by default, so the delegates must call AddTestingPlatformInstrumentation() to subscribe to the
- // Microsoft Testing Platform source/meter and wire whatever exporter(s) you want.
- testApplicationBuilder.AddOpenTelemetryProvider(
- tracing =>
- {
- tracing.AddTestingPlatformInstrumentation();
- tracing.AddConsoleExporter();
- },
- metrics =>
- {
- metrics.AddTestingPlatformInstrumentation();
- metrics.AddConsoleExporter();
- });
+ (capabilities, serviceProvider) => new SimpleTestFramework(serviceProvider, testActivitySource));
+
+ // Activate only MTP's ActivitySource and Meter. The application host above remains responsible for creating,
+ // flushing, and disposing the providers that subscribe to those diagnostics.
+ testApplicationBuilder.AddTestingPlatformDiagnostics();
using ITestApplication testApplication = await testApplicationBuilder.BuildAsync();
- return await testApplication.RunAsync();
+ int exitCode = await testApplication.RunAsync();
+
+ // Keep the host alive until after the test application has shut down so final spans and metrics can be exported.
+ await host.StopAsync();
+ return exitCode;
}
}
diff --git a/samples/public/MTPOTel/SimpleTestFramework.cs b/samples/public/MTPOTel/SimpleTestFramework.cs
index a782e85aca..57acb73c73 100644
--- a/samples/public/MTPOTel/SimpleTestFramework.cs
+++ b/samples/public/MTPOTel/SimpleTestFramework.cs
@@ -1,7 +1,8 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
+// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
+using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Testing.Platform.Extensions.Messages;
using Microsoft.Testing.Platform.Extensions.TestFramework;
@@ -12,9 +13,13 @@ namespace MTPOTel;
internal sealed class SimpleTestFramework : ITestFramework, IDataProducer
{
private readonly IServiceProvider _serviceProvider;
+ private readonly ActivitySource _activitySource;
- public SimpleTestFramework(IServiceProvider serviceProvider)
- => _serviceProvider = serviceProvider;
+ public SimpleTestFramework(IServiceProvider serviceProvider, ActivitySource activitySource)
+ {
+ _serviceProvider = serviceProvider;
+ _activitySource = activitySource;
+ }
public string Uid => nameof(SimpleTestFramework);
@@ -43,6 +48,8 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context)
{
string testId = $"Test{i}";
string testName = $"Simple Test {i}";
+ using Activity? testActivity = _activitySource.StartActivity("MTPOTel.Test");
+ testActivity?.SetTag("test.name", testName);
// Publish test node as in-progress
await context.MessageBus.PublishAsync(
diff --git a/samples/public/README.md b/samples/public/README.md
index bbaaf9a2db..78f098c18c 100644
--- a/samples/public/README.md
+++ b/samples/public/README.md
@@ -1,5 +1,11 @@
# Public samples
+## Observability
+
+| Scenario | Sample |
+| --- | --- |
+| Use application-owned OpenTelemetry providers from `HostApplicationBuilder` to collect MTP diagnostics and custom test activities while preserving the application's resource identity | [`MTPOTel`](MTPOTel) |
+
## Windows application testing
The sample name identifies the Windows application model, test host, and packaging mode.
diff --git a/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/OpenTelemetryPlatformService.cs b/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/OpenTelemetryPlatformService.cs
index 9c64a7178e..cb14b27f2f 100644
--- a/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/OpenTelemetryPlatformService.cs
+++ b/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/OpenTelemetryPlatformService.cs
@@ -23,14 +23,14 @@ internal sealed class OpenTelemetryPlatformService : IPlatformOpenTelemetryServi
public bool HasCurrentActivity => Activity.Current is not null;
public IPlatformActivity? StartActivity([CallerMemberName] string name = "", IEnumerable>? tags = null, string? parentId = null, DateTimeOffset startTime = default)
- => _activitySource.StartActivity(name, ActivityKind.Internal, tags: tags, startTime: startTime, parentId: parentId) is Activity activity
+ => StartActivityCore(name, tags, parentId, startTime) is Activity activity
? new ActivityWrapper(Stamp(activity))
: null;
public IPlatformActivity? StartNonAmbientActivity(string name, IEnumerable>? tags = null, string? parentId = null)
{
Activity? ambientBeforeStart = Activity.Current;
- if (_activitySource.StartActivity(name, ActivityKind.Internal, tags: tags, parentId: parentId) is not Activity activity)
+ if (StartActivityCore(name, tags, parentId, startTime: default) is not Activity activity)
{
return null;
}
@@ -41,6 +41,11 @@ internal sealed class OpenTelemetryPlatformService : IPlatformOpenTelemetryServi
return new ActivityWrapper(Stamp(activity), isAmbient: false);
}
+ private Activity? StartActivityCore(string name, IEnumerable>? tags, string? parentId, DateTimeOffset startTime)
+ => parentId is null && Activity.Current is { IdFormat: ActivityIdFormat.W3C } ambientActivity
+ ? _activitySource.StartActivity(name, ActivityKind.Internal, ambientActivity.Context, tags, links: null, startTime)
+ : _activitySource.StartActivity(name, ActivityKind.Internal, tags: tags, startTime: startTime, parentId: parentId ?? Activity.Current?.Id);
+
///
/// Activity only derives tracestate from an in-process parent reference, which an explicit parent id string
/// does not provide. Stamp it on so the caller's vendor sampling state survives down to the test spans.
diff --git a/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/PACKAGE.md b/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/PACKAGE.md
index 02bc521b65..e8706bfd18 100644
--- a/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/PACKAGE.md
+++ b/src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/PACKAGE.md
@@ -36,28 +36,41 @@ This package extends Microsoft.Testing.Platform with:
### Use an application-owned OpenTelemetry provider
-When the test application already configures OpenTelemetry through Aspire ServiceDefaults, `OpenTelemetry.Extensions.Hosting`, or another application-level composition root, activate only the MTP diagnostics producer in the test application's `Program.cs`:
+When the test application already configures OpenTelemetry through Aspire ServiceDefaults, `OpenTelemetry.Extensions.Hosting`, or another application-level composition root, configure and start that host before building the test application:
```csharp
-ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args);
-builder.AddTestingPlatformDiagnostics();
-```
-
-Then subscribe the application-owned providers to the MTP source and meter alongside the rest of the application's instrumentation:
+HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
-```csharp
-services.AddOpenTelemetry()
+hostBuilder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource
+ .AddService("MyTestApplication")
.AddTestingPlatformTestResource()
.AddTestingPlatformCiResource())
.WithTracing(tracing => tracing.AddTestingPlatformInstrumentation())
.WithMetrics(metrics => metrics.AddTestingPlatformInstrumentation());
+
+using IHost host = hostBuilder.Build();
+await host.StartAsync();
+
+ITestApplicationBuilder testBuilder = await TestApplication.CreateBuilderAsync(args);
+testBuilder.AddTestingPlatformDiagnostics();
+
+using ITestApplication testApplication = await testBuilder.BuildAsync();
+int exitCode = await testApplication.RunAsync();
+
+await host.StopAsync();
+return exitCode;
```
`AddTestingPlatformDiagnostics()` does not build, configure, flush, or dispose a `TracerProvider` or `MeterProvider`. The application keeps full ownership of those providers and their exporters. The older `AddOpenTelemetryProvider()` and `AddOpenTelemetryProviderFromEnvironment()` helpers remain available as standalone convenience paths when the test application wants MTP to own the provider lifetime.
The focused resource helpers are recommended when Aspire ServiceDefaults, `HostApplicationBuilder`, or another application-level composition root already owns `service.*`, `host.*`, `os.*`, and `process.*`. Use `AddTestingPlatformResource()` only when the test application wants the extension to configure that complete standalone resource identity.
+See the complete [`HostApplicationBuilder` sample](../../../samples/public/MTPOTel).
+It also subscribes to a custom `ActivitySource` used inside test execution. The custom activity and MTP's test-case
+result span share the run trace and are siblings under the `TestFramework` span; MTP does not make user test code
+ambient to its asynchronously produced result span.
+
## Emitted metrics
| Instrument | Type | Unit | Description |
diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs
index 3743adc6c3..3972931cab 100644
--- a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs
+++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/Helpers/AcceptanceTestBase.cs
@@ -22,6 +22,8 @@ static AcceptanceTestBase()
var cpmPropFileDoc = XDocument.Load(Path.Combine(RootFinder.Find(), "Directory.Packages.props"));
MicrosoftNETTestSdkVersion = cpmPropFileDoc.Descendants("MicrosoftNETTestSdkVersion").Single().Value;
MicrosoftNETCoreUniversalWindowsPlatformVersion = cpmPropFileDoc.Descendants("MicrosoftNETCoreUniversalWindowsPlatformVersion").Single().Value;
+ MicrosoftExtensionsHostingVersion = GetPackageVersion(cpmPropFileDoc, "Microsoft.Extensions.Logging");
+ OpenTelemetryVersion = GetPackageVersion(cpmPropFileDoc, "OpenTelemetry");
using var globalJson = JsonDocument.Parse(File.ReadAllText(Path.Combine(RootFinder.Find(), "global.json")));
MSBuildSdkExtrasVersion = globalJson.RootElement
@@ -86,6 +88,10 @@ await clone.CopyDirectoryAsync(
public static string MicrosoftNETCoreUniversalWindowsPlatformVersion { get; private set; }
+ public static string MicrosoftExtensionsHostingVersion { get; private set; }
+
+ public static string OpenTelemetryVersion { get; private set; }
+
public static string MSBuildSdkExtrasVersion { get; private set; }
// Keep this known-working Windows App SDK/BuildTools pair together. Generated WinUI assets use
@@ -155,6 +161,13 @@ private static string ExtractVersionFromPackage(string rootFolder, string packag
return packageFullName.Substring(packagePrefixName.Length, packageFullName.Length - packagePrefixName.Length - NuGetPackageExtensionName.Length);
}
+ private static string GetPackageVersion(XDocument centralPackageManagementDocument, string packageName)
+ => centralPackageManagementDocument
+ .Descendants("PackageVersion")
+ .Single(element => string.Equals(element.Attribute("Include")?.Value, packageName, StringComparison.Ordinal))
+ .Attribute("Version")?.Value
+ ?? throw new InvalidOperationException($"Directory.Packages.props does not define a version for '{packageName}'.");
+
internal static IEnumerable<(string Tfm, BuildConfiguration BuildConfiguration)> GetBuildMatrixTfmBuildConfiguration()
{
foreach (string tfm in TargetFrameworks.All)
diff --git a/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/OpenTelemetryTests.cs b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/OpenTelemetryTests.cs
new file mode 100644
index 0000000000..84a99dcac2
--- /dev/null
+++ b/test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/OpenTelemetryTests.cs
@@ -0,0 +1,330 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+namespace Microsoft.Testing.Platform.Acceptance.IntegrationTests;
+
+[TestClass]
+public sealed class OpenTelemetryTests : AcceptanceTestBase
+{
+ private const string AssetName = "ApplicationOwnedOpenTelemetry";
+
+ [TestMethod]
+ public async Task HostApplicationBuilderProviders_ConsumeMtpDiagnosticsAndPreserveApplicationResource()
+ {
+ var testHost = TestInfrastructure.TestHost.LocateFrom(AssetFixture.TargetAssetPath, AssetName, TargetFrameworks.NetCurrent);
+ TestHostResult result = await testHost.ExecuteAsync(cancellationToken: TestContext.CancellationToken);
+
+ result.AssertExitCodeIs(ExitCode.Success);
+ result.AssertOutputContains("[APP-OWNED-TRACE] TestHostBuilder");
+ result.AssertOutputContains("[APP-OWNED-TEST-TRACE] application-test-activity");
+ result.AssertOutputContains("[APP-OWNED-METRIC] test.run.duration");
+ result.AssertOutputContains("[APP-OWNED-RESOURCE] service.name=application-owned-tests");
+ result.AssertOutputContains("[APP-OWNED-PARENT] inherited");
+ result.AssertOutputContains("[APP-OWNED-TOPOLOGY] sibling-under-TestFramework");
+ }
+
+ public TestContext TestContext { get; set; } = null!;
+
+ public sealed class TestAssetFixture() : TestAssetFixtureBase()
+ {
+ private const string TestCode = """
+#file ApplicationOwnedOpenTelemetry.csproj
+
+
+ $TargetFrameworks$
+ enable
+ enable
+ Exe
+ true
+ preview
+
+
+
+
+
+
+
+
+
+
+#file Program.cs
+using System.Diagnostics;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Testing.Extensions;
+using Microsoft.Testing.Platform.Builder;
+using Microsoft.Testing.Platform.Capabilities.TestFramework;
+using Microsoft.Testing.Platform.Extensions.Messages;
+using Microsoft.Testing.Platform.Extensions.TestFramework;
+using Microsoft.Testing.Platform.Messages;
+using Microsoft.Testing.Platform.Services;
+using Microsoft.Testing.Platform.TestHost;
+using OpenTelemetry;
+using OpenTelemetry.Metrics;
+using OpenTelemetry.Resources;
+using OpenTelemetry.Trace;
+
+internal static class Program
+{
+ private const string ApplicationActivitySourceName = "ApplicationOwnedOpenTelemetry";
+ private const string ApplicationServiceName = "application-owned-tests";
+
+ public static async Task Main(string[] args)
+ {
+ var activityExporter = new CapturingActivityExporter();
+ var metricExporter = new CapturingMetricExporter();
+ HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
+
+ hostBuilder.Services.AddOpenTelemetry()
+ .ConfigureResource(resource => resource
+ .AddService(ApplicationServiceName)
+ .AddTestingPlatformTestResource()
+ .AddTestingPlatformCiResource())
+ .WithTracing(tracing => tracing
+ .AddSource(ApplicationActivitySourceName)
+ .AddTestingPlatformInstrumentation()
+ .AddProcessor(new SimpleActivityExportProcessor(activityExporter)))
+ .WithMetrics(metrics => metrics
+ .AddTestingPlatformInstrumentation()
+ .AddReader(new PeriodicExportingMetricReader(metricExporter, exportIntervalMilliseconds: 10)));
+
+ using IHost host = hostBuilder.Build();
+ await host.StartAsync();
+
+ using var applicationActivitySource = new ActivitySource(ApplicationActivitySourceName);
+ using Activity? applicationActivity = applicationActivitySource.StartActivity("application-test-run");
+ if (applicationActivity is null)
+ {
+ throw new InvalidOperationException("The application-owned provider did not subscribe to its activity source.");
+ }
+
+ ActivityTraceId applicationTraceId = applicationActivity.TraceId;
+ ActivitySpanId applicationSpanId = applicationActivity.SpanId;
+
+ ITestApplicationBuilder testBuilder = await TestApplication.CreateBuilderAsync(args);
+ testBuilder.RegisterTestFramework(
+ _ => new TestFrameworkCapabilities(),
+ (_, _) => new SingleTestFramework(applicationActivitySource));
+ testBuilder.AddTestingPlatformDiagnostics();
+
+ int exitCode;
+ using (ITestApplication testApplication = await testBuilder.BuildAsync())
+ {
+ exitCode = await testApplication.RunAsync();
+ }
+
+ applicationActivity.Stop();
+ ServiceProviderServiceExtensions.GetRequiredService(host.Services).ForceFlush();
+ ServiceProviderServiceExtensions.GetRequiredService(host.Services).ForceFlush();
+
+ Activity applicationRootActivity = activityExporter.Single(
+ activity => activity.Source.Name == ApplicationActivitySourceName
+ && activity.OperationName == "application-test-run");
+ Activity customTestActivity = activityExporter.Single(
+ activity => activity.Source.Name == ApplicationActivitySourceName
+ && activity.OperationName == "application-test-activity");
+ Activity builderActivity = activityExporter.Single(
+ activity => activity.Source.Name == "Microsoft.Testing.Platform"
+ && activity.OperationName == "TestHostBuilder");
+ Activity testFrameworkActivity = activityExporter.Single(
+ activity => activity.Source.Name == "Microsoft.Testing.Platform"
+ && activity.OperationName == "TestFramework");
+ Activity testResultActivity = activityExporter.Single(
+ activity => activity.Source.Name == "Microsoft.Testing.Platform"
+ && activity.OperationName == "Application-owned telemetry test");
+
+ if (applicationRootActivity.TraceId != applicationTraceId
+ || applicationRootActivity.SpanId != applicationSpanId)
+ {
+ throw new InvalidOperationException("The application-owned root activity was not exported.");
+ }
+
+ if (builderActivity.TraceId != applicationTraceId || builderActivity.ParentSpanId != applicationSpanId)
+ {
+ throw new InvalidOperationException(
+ $"MTP did not inherit the application trace context. Expected {applicationTraceId}/{applicationSpanId}, " +
+ $"actual {builderActivity.TraceId}/{builderActivity.ParentSpanId}.");
+ }
+
+ if (testFrameworkActivity.TraceId != applicationTraceId
+ || customTestActivity.TraceId != testFrameworkActivity.TraceId
+ || testResultActivity.TraceId != testFrameworkActivity.TraceId
+ || customTestActivity.ParentSpanId != testFrameworkActivity.SpanId
+ || testResultActivity.ParentSpanId != testFrameworkActivity.SpanId)
+ {
+ throw new InvalidOperationException(
+ "The application test activity and MTP test-result activity must be siblings under TestFramework.");
+ }
+
+ if (!metricExporter.Contains("test.run.duration"))
+ {
+ throw new InvalidOperationException("The application-owned meter provider did not export test.run.duration.");
+ }
+
+ string traceServiceName = GetServiceName(activityExporter.GetCapturedResource(), "trace");
+ _ = GetServiceName(metricExporter.GetCapturedResource(), "metric");
+
+ Console.WriteLine($"[APP-OWNED-TRACE] {builderActivity.OperationName}");
+ Console.WriteLine($"[APP-OWNED-TEST-TRACE] {customTestActivity.OperationName}");
+ Console.WriteLine("[APP-OWNED-METRIC] test.run.duration");
+ Console.WriteLine($"[APP-OWNED-RESOURCE] service.name={traceServiceName}");
+ Console.WriteLine("[APP-OWNED-PARENT] inherited");
+ Console.WriteLine("[APP-OWNED-TOPOLOGY] sibling-under-TestFramework");
+
+ await host.StopAsync();
+ return exitCode;
+ }
+
+ private static string GetServiceName(Resource? resource, string signal)
+ {
+ Dictionary attributes = (resource
+ ?? throw new InvalidOperationException($"The application-owned {signal} exporter did not receive a resource."))
+ .Attributes
+ .ToDictionary(attribute => attribute.Key, attribute => attribute.Value);
+ if (!attributes.TryGetValue("service.name", out object? serviceName)
+ || !string.Equals(serviceName?.ToString(), ApplicationServiceName, StringComparison.Ordinal))
+ {
+ throw new InvalidOperationException(
+ $"The application service.name was not preserved by the {signal} provider: '{serviceName}'.");
+ }
+
+ return ApplicationServiceName;
+ }
+}
+
+internal sealed class CapturingActivityExporter : BaseExporter
+{
+ private readonly object _syncRoot = new();
+ private readonly List _activities = [];
+ private Resource? _capturedResource;
+
+ public override ExportResult Export(in Batch batch)
+ {
+ lock (_syncRoot)
+ {
+ _capturedResource ??= ParentProvider?.GetResource();
+ foreach (Activity activity in batch)
+ {
+ _activities.Add(activity);
+ }
+ }
+
+ return ExportResult.Success;
+ }
+
+ public Activity Single(Func predicate)
+ {
+ lock (_syncRoot)
+ {
+ return _activities.Single(predicate);
+ }
+ }
+
+ public Resource? GetCapturedResource()
+ {
+ lock (_syncRoot)
+ {
+ return _capturedResource;
+ }
+ }
+}
+
+internal sealed class CapturingMetricExporter : BaseExporter
+{
+ private readonly object _syncRoot = new();
+ private readonly HashSet _metricNames = new(StringComparer.Ordinal);
+ private Resource? _capturedResource;
+
+ public override ExportResult Export(in Batch batch)
+ {
+ lock (_syncRoot)
+ {
+ _capturedResource ??= ParentProvider?.GetResource();
+ foreach (Metric metric in batch)
+ {
+ _metricNames.Add(metric.Name);
+ }
+ }
+
+ return ExportResult.Success;
+ }
+
+ public bool Contains(string metricName)
+ {
+ lock (_syncRoot)
+ {
+ return _metricNames.Contains(metricName);
+ }
+ }
+
+ public Resource? GetCapturedResource()
+ {
+ lock (_syncRoot)
+ {
+ return _capturedResource;
+ }
+ }
+}
+
+internal sealed class SingleTestFramework(ActivitySource activitySource) : ITestFramework, IDataProducer
+{
+ public string Uid => nameof(SingleTestFramework);
+ public string Version => "1.0.0";
+ public string DisplayName => nameof(SingleTestFramework);
+ public string Description => "Publishes one passing test.";
+ public Type[] DataTypesProduced => [typeof(TestNodeUpdateMessage)];
+
+ public Task IsEnabledAsync() => Task.FromResult(true);
+
+ public Task CreateTestSessionAsync(CreateTestSessionContext context)
+ => Task.FromResult(new CreateTestSessionResult { IsSuccess = true });
+
+ public Task CloseTestSessionAsync(CloseTestSessionContext context)
+ => Task.FromResult(new CloseTestSessionResult { IsSuccess = true });
+
+ public async Task ExecuteRequestAsync(ExecuteRequestContext context)
+ {
+ using Activity? testActivity = activitySource.StartActivity("application-test-activity");
+ if (testActivity is null)
+ {
+ throw new InvalidOperationException("The application-owned provider did not subscribe to the test activity source.");
+ }
+
+ var sessionUid = new SessionUid("application-owned-session");
+ await context.MessageBus.PublishAsync(
+ this,
+ new TestNodeUpdateMessage(
+ sessionUid,
+ new TestNode
+ {
+ Uid = "application-owned-test",
+ DisplayName = "Application-owned telemetry test",
+ Properties = new PropertyBag(new InProgressTestNodeStateProperty()),
+ }));
+ await context.MessageBus.PublishAsync(
+ this,
+ new TestNodeUpdateMessage(
+ sessionUid,
+ new TestNode
+ {
+ Uid = "application-owned-test",
+ DisplayName = "Application-owned telemetry test",
+ Properties = new PropertyBag(PassedTestNodeStateProperty.CachedInstance),
+ }));
+ context.Complete();
+ }
+}
+""";
+
+ public string TargetAssetPath => GetAssetPath(AssetName);
+
+ public override (string ID, string Name, string Code) GetAssetsToGenerate() => (
+ AssetName,
+ AssetName,
+ TestCode
+ .PatchTargetFrameworks(TargetFrameworks.NetCurrent)
+ .PatchCodeWithReplace("$MicrosoftExtensionsHostingVersion$", MicrosoftExtensionsHostingVersion)
+ .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion)
+ .PatchCodeWithReplace("$OpenTelemetryVersion$", OpenTelemetryVersion));
+ }
+}
diff --git a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/OpenTelemetryPlatformServiceTests.cs b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/OpenTelemetryPlatformServiceTests.cs
index d38c3bea11..2aba91dbb2 100644
--- a/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/OpenTelemetryPlatformServiceTests.cs
+++ b/test/UnitTests/Microsoft.Testing.Extensions.UnitTests/OpenTelemetryPlatformServiceTests.cs
@@ -71,6 +71,21 @@ public void StartActivity_ByDefault_PublishesTheActivityAsCurrent()
Assert.AreSame(_ambientAtStart, Activity.Current);
}
+ [TestMethod]
+ public void StartActivity_WithoutExplicitParent_InheritsTheAmbientActivity()
+ {
+ using IPlatformActivity? parent = _service.StartActivity(Name("parent"));
+ Assert.IsNotNull(parent);
+
+ using (IPlatformActivity? child = _service.StartActivity(Name("child")))
+ {
+ Assert.IsNotNull(child);
+ Assert.AreEqual(parent.TraceId, child.TraceId);
+ }
+
+ Assert.AreEqual(parent.SpanId, Single().ParentSpanId.ToHexString());
+ }
+
[TestMethod]
public void StartNonAmbientActivity_NeverBecomesCurrent()
{
@@ -95,11 +110,15 @@ public void StartNonAmbientActivity_DoesNotDisturbAnExistingAmbientActivity()
Activity? ambient = Activity.Current;
Assert.IsNotNull(ambient);
- using (_service.StartNonAmbientActivity(Name("inner")))
+ using (IPlatformActivity? inner = _service.StartNonAmbientActivity(Name("inner")))
{
+ Assert.IsNotNull(inner);
+ Assert.AreEqual(ambient.TraceId.ToHexString(), inner.TraceId);
Assert.AreSame(ambient, Activity.Current);
}
+ Assert.AreEqual(ambient.SpanId, Single().ParentSpanId);
+
// Stopping a non-ambient activity must not pop the ambient one.
Assert.AreSame(ambient, Activity.Current);
}