Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions samples/public/MTPOTel/MTPOTel.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
<PackageReference Include="OpenTelemetry.Exporter.Console" VersionOverride="1.13.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.13.1" />
</ItemGroup>

<ItemGroup>
Expand Down
57 changes: 38 additions & 19 deletions samples/public/MTPOTel/Program.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -21,29 +25,44 @@ public class Program
{
public static async Task<int> 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;
}
}
13 changes: 10 additions & 3 deletions samples/public/MTPOTel/SimpleTestFramework.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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);

Expand Down Expand Up @@ -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(
Expand Down
6 changes: 6 additions & 0 deletions samples/public/README.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ internal sealed class OpenTelemetryPlatformService : IPlatformOpenTelemetryServi
public bool HasCurrentActivity => Activity.Current is not null;

public IPlatformActivity? StartActivity([CallerMemberName] string name = "", IEnumerable<KeyValuePair<string, object?>>? 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<KeyValuePair<string, object?>>? 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;
}
Expand All @@ -41,6 +41,11 @@ internal sealed class OpenTelemetryPlatformService : IPlatformOpenTelemetryServi
return new ActivityWrapper(Stamp(activity), isAmbient: false);
}

private Activity? StartActivityCore(string name, IEnumerable<KeyValuePair<string, object?>>? 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);

/// <summary>
/// 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.
Expand Down
29 changes: 21 additions & 8 deletions src/Platform/Microsoft.Testing.Extensions.OpenTelemetry/PACKAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading