Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
58017af
Add dashboard support to testing builders
Aug 7, 2026
e07a461
Merge microsoft/main into adamint/feature-15575-testing-dashboard
Aug 7, 2026
8ef74cd
Finish testing dashboard support
Aug 7, 2026
51f8c6b
Address review findings for dashboard-in-tests support
Aug 7, 2026
8ae0f6d
Fix dashboard testing regressions found by CI
Aug 7, 2026
10b6337
Pin the AppHost browser token boundary with a test
Aug 7, 2026
d776ba6
Do not dispose an application a concurrent build still owns
Aug 7, 2026
b08bf91
Restore the browser token an AppHost cleared
Aug 7, 2026
9880d13
Merge remote-tracking branch 'microsoft/main' into adamint/feature-15…
Aug 7, 2026
b1a1fd4
Close a disposal race that could leave the application running
adamint Aug 9, 2026
0524c70
Restore resource-service authentication after AppHost configuration
adamint Aug 9, 2026
d608e0a
Keep the dashboard browser token out of AppHost logs in testing mode
adamint Aug 9, 2026
7942f43
Merge branch 'main' into adamint/feature-15575-testing-dashboard
adamint Aug 10, 2026
3bca434
Keep dashboard testing focused
Aug 10, 2026
4da93af
Merge upstream/main into adamint/feature-15575-testing-dashboard
Aug 14, 2026
d29d255
Address remaining dashboard testing review feedback
Aug 14, 2026
9e532fc
Suppress dashboard tokens in forwarded test logs
Aug 14, 2026
38ced12
Support running the dashboard from tests
adamint Aug 17, 2026
1e32ada
Fix dashboard testing target host URL
Aug 18, 2026
0d37444
Use direct dashboard endpoint host resolution
Aug 18, 2026
14ad8e3
Drop the product-to-product IVT and promote the target-host helper
Aug 18, 2026
07ab893
Substitute the localhost TLD only for loopback addresses
adamint Aug 18, 2026
10bbdf1
Validate the endpoint argument on the public target-host helper
adamint Aug 18, 2026
5ab19de
Describe the endpoint URL resolution on the helper type summary
adamint Aug 18, 2026
6884e13
Clarify dashboard testing isolation and wait behavior
adamint Aug 18, 2026
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
7 changes: 0 additions & 7 deletions src/Aspire.Hosting.Testing/Aspire.Hosting.Testing.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,6 @@
<IsAspireHost>false</IsAspireHost>
</PropertyGroup>

<ItemGroup>
<Compile Include="$(SharedDir)LaunchProfiles\LaunchSettingsReader.cs" Link="LaunchSettingsReader.cs" />
<Compile Include="$(SharedDir)LaunchProfiles\LaunchSettingsSerializerContext.cs" Link="LaunchSettingsSerializerContext.cs" />
<Compile Include="$(SharedDir)\KnownAspNetCoreConfigNames.cs" Link="KnownAspNetCoreConfigNames.cs" />
<Compile Include="$(SharedDir)\KnownConfigNames.cs" Link="KnownConfigNames.cs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Aspire.Hosting.AppHost\Aspire.Hosting.AppHost.csproj" />
<ProjectReference Include="..\Aspire.Hosting\Aspire.Hosting.csproj" />
Expand Down
31 changes: 27 additions & 4 deletions src/Aspire.Hosting.Testing/DistributedApplicationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ public class DistributedApplicationFactory(Type entryPoint, string[] args) : IDi
private readonly TaskCompletionSource<DistributedApplicationBuilder> _builderTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<DistributedApplication> _appTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource _disposingCts = new();

// Disposal must be claimed atomically. Reading _disposingCts.IsCancellationRequested is not enough because
// OnDisposed() cancels it only after the guard, so two concurrent disposers could both run the teardown
// below and race on StopAsync()/DisposeAsync() of the same application.
private int _disposeClaimed;
private TimeSpan _shutdownTimeout = TimeSpan.FromSeconds(10);
private readonly object _lockObj = new();
private bool _entryPointStarted;
Expand Down Expand Up @@ -166,10 +171,28 @@ private static string[] ThrowIfNullOrContainsIsNullOrEmpty(string[] args)
return args;
}

private void OnBuiltCore(DistributedApplication application)
private async Task OnBuiltCoreAsync(DistributedApplication application)
{
_shutdownTimeout = application.Services.GetService<IOptions<HostOptions>>()?.Value.ShutdownTimeout ?? _shutdownTimeout;
_appTcs.TrySetResult(application);

if (!_appTcs.TrySetResult(application))
{
// The factory was disposed, or the entry point already faulted, while this application was still
// being built. No caller will ever receive it, so nothing else holds a reference that would tear
// down the host, its service provider, or the orchestrator processes it owns. Reclaim it here
// instead of leaving it running for the lifetime of the test process.
try
{
await application.DisposeAsync().ConfigureAwait(false);
}
catch
{
// No owner remains to observe a disposal failure for an application nobody asked for.
}

return;
}

OnBuilt(application);
}

Expand Down Expand Up @@ -409,7 +432,7 @@ private async Task InvokeEntryPoint(Func<string[], CancellationToken, Task<Distr
var app = await factory(_args, cts.Token).ConfigureAwait(false);
_hostApplicationLifetime = app.Services.GetService<IHostApplicationLifetime>()
?? throw new InvalidOperationException($"Application did not register an implementation of {typeof(IHostApplicationLifetime)}.");
OnBuiltCore(app);
await OnBuiltCoreAsync(app).ConfigureAwait(false);
}
catch (Exception exception)
{
Expand Down Expand Up @@ -481,7 +504,7 @@ private void OnDisposed()
/// <inheritdoc/>
public virtual async ValueTask DisposeAsync()
{
if (_disposingCts.IsCancellationRequested)
if (Interlocked.Exchange(ref _disposeClaimed, 1) == 1)
Comment thread
adamint marked this conversation as resolved.
Resolved
{
// Dispose already called.
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Backchannel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Aspire.Hosting.Testing;

Expand All @@ -12,6 +14,93 @@ namespace Aspire.Hosting.Testing;
/// </summary>
public static class DistributedApplicationHostingTestingExtensions
{
/// <summary>
/// Gets the authenticated login URL for the running Aspire dashboard.
/// </summary>
/// <param name="app">The distributed application.</param>
/// <param name="cancellationToken">A token used to cancel the operation.</param>
/// <returns>
/// An absolute <see cref="Uri"/> that authenticates the browser with the running dashboard.
/// </returns>
/// <remarks>
/// <para>
/// Enable dashboard support with <see cref="DistributedApplicationTestingBuilderOptions.EnableDashboard"/> when creating
/// the testing builder.
/// </para>
/// <para>
/// This method does not start the distributed application. Call <see cref="DistributedApplication.StartAsync(CancellationToken)"/>
/// before requesting the dashboard login URL.
/// </para>
/// <para>
/// This method waits for the dashboard resource to become healthy. Pass a cancellation token when the wait must
/// be bounded. The returned URI contains an authentication credential and should be treated as sensitive.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="app"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown when the application is in publish mode, the dashboard is disabled, the application has not started,
/// anonymous dashboard access is enabled, or a dashboard login URL is unavailable.
/// </exception>
/// <exception cref="DistributedApplicationException">Thrown when the dashboard reaches a terminal failure state.</exception>
/// <exception cref="OperationCanceledException">Thrown when <paramref name="cancellationToken"/> is canceled.</exception>
/// <exception cref="ObjectDisposedException">Thrown when the distributed application has been disposed.</exception>
/// <example>
/// <code lang="csharp">
/// var options = new DistributedApplicationTestingBuilderOptions
/// {
/// EnableDashboard = true
/// };
///
/// var builder = await DistributedApplicationTestingBuilder.CreateAsync&lt;Projects.MyAppHost_AppHost&gt;(options, []);
/// await using var app = await builder.BuildAsync();
/// await app.StartAsync();
///
/// var dashboardLoginUrl = await app.GetDashboardLoginUrlAsync();
/// </code>
/// </example>
[AspireExportIgnore(Reason = "Dashboard URLs are only available to .NET test code and may contain authentication credentials.")]
public static async Task<Uri> GetDashboardLoginUrlAsync(
this DistributedApplication app,
CancellationToken cancellationToken = default)
Comment thread
adamint marked this conversation as resolved.
Resolved
{
ArgumentNullException.ThrowIfNull(app);

var executionContext = app.Services.GetRequiredService<DistributedApplicationExecutionContext>();
if (executionContext.IsPublishMode)
{
throw new InvalidOperationException(Properties.Resources.DashboardLoginUrlPublishModeExceptionMessage);
}

var applicationOptions = app.Services.GetRequiredService<DistributedApplicationOptions>();
if (applicationOptions.DisableDashboard)
{
throw new InvalidOperationException(Properties.Resources.DashboardDisabledExceptionMessage);
}

ThrowIfNotStarted(app, Properties.Resources.DashboardLoginUrlApplicationNotStartedExceptionMessage);
cancellationToken.ThrowIfCancellationRequested();

var logger = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger(
"Aspire.Hosting.Testing.DistributedApplicationDashboard");
var dashboardInfo = await DashboardUrlsHelper.GetDashboardConnectionInfoOrThrowAsync(
app.Services,
logger,
cancellationToken).ConfigureAwait(false);

var dashboardUrl = dashboardInfo.CodespacesUrlWithLoginToken ?? dashboardInfo.BaseUrlWithLoginToken;
if (!dashboardInfo.IsHealthy || !Uri.TryCreate(dashboardUrl, UriKind.Absolute, out var dashboardUri))
{
throw new InvalidOperationException(Properties.Resources.DashboardLoginUrlUnavailableExceptionMessage);
}

if (!dashboardInfo.HasBrowserToken)
{
throw new InvalidOperationException(Properties.Resources.DashboardLoginUrlAnonymousExceptionMessage);
}

return dashboardUri;
}

/// <summary>
/// Creates an <see cref="HttpClient"/> configured to communicate with the specified resource.
/// </summary>
Expand Down Expand Up @@ -127,7 +216,7 @@ internal static Uri GetEndpointForNetworkExport(this DistributedApplication app,

static IResource GetResource(DistributedApplication app, string resourceName)
{
ThrowIfNotStarted(app);
ThrowIfNotStarted(app, Properties.Resources.ApplicationNotStartedExceptionMessage);
var applicationModel = app.Services.GetRequiredService<DistributedApplicationModel>();

if (!applicationModel.Resources.TryGetByName(resourceName, out var resource))
Expand Down Expand Up @@ -166,12 +255,12 @@ static string GetEndpointUriStringCore(DistributedApplication app, string resour
return endpoint.Url;
}

static void ThrowIfNotStarted(DistributedApplication app)
static void ThrowIfNotStarted(DistributedApplication app, string exceptionMessage)
{
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
if (!lifetime.ApplicationStarted.IsCancellationRequested)
{
throw new InvalidOperationException(Properties.Resources.ApplicationNotStartedExceptionMessage);
throw new InvalidOperationException(exceptionMessage);
}
}

Expand Down
Loading
Loading