Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
@@ -1 +1,3 @@
#nullable enable
static Microsoft.Testing.Extensions.OpenTelemetry.TestingPlatformResourceDetector.GetCiResourceAttributes() -> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string!, object!>>!
static Microsoft.Testing.Extensions.OpenTelemetry.TestingPlatformResourceDetector.GetTestResourceAttributes() -> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string!, object!>>!
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)
Comment thread
Evangelink marked this conversation as resolved.
Resolved
{
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
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,14 @@ public static MeterProviderBuilder AddTestingPlatformInstrumentation(this MeterP
/// Adds the Microsoft Testing Platform resource attributes (test assembly, host, OS, runtime and the detected
/// CI provider, pipeline and commit) to the resource of a tracer, meter or logger provider.
/// </summary>
/// <remarks>Resource attributes are attached once to every span and metric point exported by the provider, which
/// is what lets you slice a dashboard by branch, pipeline or machine without adding those values to every span.
/// <remarks>This is the standalone aggregate convenience path. It configures service identity and adds host, OS,
/// process, test assembly, CI and source-control attributes.
/// <para>Applications that already configure their own service, host, OS or process identity through Aspire
/// ServiceDefaults, <c>HostApplicationBuilder</c> or another application-level OpenTelemetry composition root
/// should use <see cref="AddTestingPlatformTestResource(ResourceBuilder)"/> and
/// <see cref="AddTestingPlatformCiResource(ResourceBuilder)"/> instead.</para>
/// <para>Resource attributes are attached once to every span and metric point exported by the provider, which
/// is what lets you slice a dashboard by branch, pipeline or machine without adding those values to every span.</para>
/// <para>The CI attributes follow the OpenTelemetry <c>cicd.*</c> and <c>vcs.*</c> conventions and are detected
/// from GitHub Actions, Azure Pipelines, GitLab CI and Jenkins environment variables.</para></remarks>
/// <param name="builder">The resource builder to enrich.</param>
Expand All @@ -126,6 +132,39 @@ public static ResourceBuilder AddTestingPlatformResource(this ResourceBuilder bu
.AddAttributes(TestingPlatformResourceDetector.GetResourceAttributes());
}

/// <summary>
/// Adds Microsoft Testing Platform test-specific resource attributes to the resource of a tracer, meter or logger
/// provider.
/// </summary>
/// <remarks>This focused helper currently adds the test assembly name. It does not configure or overwrite
/// <c>service.*</c>, <c>host.*</c>, <c>os.*</c>, <c>process.*</c>, <c>cicd.*</c> or <c>vcs.*</c> attributes,
/// so it can be composed with application-owned OpenTelemetry resource configuration.</remarks>
/// <param name="builder">The resource builder to enrich.</param>
/// <returns>The same <see cref="ResourceBuilder"/> instance.</returns>
public static ResourceBuilder AddTestingPlatformTestResource(this ResourceBuilder builder)
{
_ = builder ?? throw new ArgumentNullException(nameof(builder));

return builder.AddAttributes(TestingPlatformResourceDetector.GetTestResourceAttributes());
}

/// <summary>
/// Adds CI and source-control provenance for the current test run to the resource of a tracer, meter or logger
/// provider.
/// </summary>
/// <remarks>The attributes follow the OpenTelemetry <c>cicd.*</c> and <c>vcs.*</c> conventions and are detected
/// from GitHub Actions, Azure Pipelines, GitLab CI and Jenkins environment variables. User-info credentials are
/// removed from repository URLs. This focused helper does not configure or overwrite <c>service.*</c>,
/// <c>host.*</c>, <c>os.*</c>, <c>process.*</c> or <c>test.*</c> attributes.</remarks>
/// <param name="builder">The resource builder to enrich.</param>
/// <returns>The same <see cref="ResourceBuilder"/> instance.</returns>
public static ResourceBuilder AddTestingPlatformCiResource(this ResourceBuilder builder)
{
_ = builder ?? throw new ArgumentNullException(nameof(builder));

return builder.AddAttributes(TestingPlatformResourceDetector.GetCiResourceAttributes());
}

/// <summary>
/// Registers OpenTelemetry tracing and metrics providers configured entirely from the standard <c>OTEL_*</c>
/// environment variables, so a test run can be exported to an observability backend without any code change.
Expand Down
Loading
Loading