-
Notifications
You must be signed in to change notification settings - Fork 462
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Aspire.Hosting.Testing to facilitate integration testing #2310
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
47271b2
Add Aspire.Hosting.Testing to facilitate integration testing
ReubenBond 79983ca
Rearrange disposal
ReubenBond fc7b7ef
Add missing members
ReubenBond b3f962d
Make tests local-only for now
ReubenBond 4d21459
Review feedback
ReubenBond fea6f72
Defer initiating app host launch until InitializeAsync
ReubenBond 832a2c5
xUnit fixtures are initialized even when the tests are all skipped, s…
ReubenBond File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>$(NetCurrent)</TargetFramework> | ||
<OutputType>Library</OutputType> | ||
<IsPackable>true</IsPackable> | ||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> | ||
<NoWarn>$(NoWarn);CS8002</NoWarn> | ||
<PackageTags>aspire testing</PackageTags> | ||
<Description>Testing support for the .NET Aspire application model.</Description> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\Aspire.Hosting\Aspire.Hosting.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.Extensions.Http.Resilience" /> | ||
</ItemGroup> | ||
|
||
</Project> |
208 changes: 208 additions & 0 deletions
208
src/Aspire.Hosting.Testing/DistributedApplicationEntryPointInvoker.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,208 @@ | ||
using System.Diagnostics; | ||
using System.Reflection; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace Aspire.Hosting.Testing; | ||
|
||
internal sealed class DistributedApplicationEntryPointInvoker | ||
{ | ||
// This helpers encapsulates all of the complex logic required to: | ||
// 1. Execute the entry point of the specified assembly in a different thread. | ||
// 2. Wait for the diagnostic source events to fire | ||
// 3. Give the caller a chance to execute logic to mutate the IDistributedApplicationBuilder | ||
// 4. Resolve the instance of the DistributedApplication | ||
// 5. Allow the caller to determine if the entry point has completed | ||
public static Func<string[], CancellationToken, Task<DistributedApplication>>? ResolveEntryPoint( | ||
Assembly assembly, | ||
Action<DistributedApplicationOptions, HostApplicationBuilderSettings>? onConstructing = null, | ||
Action<DistributedApplicationBuilder>? onConstructed = null, | ||
Action<DistributedApplicationBuilder>? onBuilding = null, | ||
Action<Exception?>? entryPointCompleted = null) | ||
{ | ||
if (assembly.EntryPoint is null) | ||
{ | ||
return null; | ||
} | ||
|
||
return async (args, ct) => | ||
{ | ||
var invoker = new EntryPointInvoker( | ||
args, | ||
assembly.EntryPoint, | ||
onConstructing, | ||
onConstructed, | ||
onBuilding, | ||
entryPointCompleted); | ||
return await invoker.InvokeAsync(ct).ConfigureAwait(false); | ||
}; | ||
} | ||
|
||
private sealed class EntryPointInvoker : IObserver<DiagnosticListener> | ||
{ | ||
private static readonly AsyncLocal<EntryPointInvoker> s_currentListener = new(); | ||
private readonly string[] _args; | ||
private readonly MethodInfo _entryPoint; | ||
private readonly TaskCompletionSource<DistributedApplication> _appTcs = new(); | ||
private readonly ApplicationBuilderDiagnosticListener _applicationBuilderListener; | ||
private readonly Action<DistributedApplicationOptions, HostApplicationBuilderSettings>? _onConstructing; | ||
private readonly Action<DistributedApplicationBuilder>? _onConstructed; | ||
private readonly Action<DistributedApplicationBuilder>? _onBuilding; | ||
private readonly Action<Exception?>? _entryPointCompleted; | ||
|
||
public EntryPointInvoker( | ||
string[] args, | ||
MethodInfo entryPoint, | ||
Action<DistributedApplicationOptions, HostApplicationBuilderSettings>? onConstructing, | ||
Action<DistributedApplicationBuilder>? onConstructed, | ||
Action<DistributedApplicationBuilder>? onBuilding, | ||
Action<Exception?>? entryPointCompleted) | ||
{ | ||
_args = args; | ||
_entryPoint = entryPoint; | ||
_onConstructing = onConstructing; | ||
_onConstructed = onConstructed; | ||
_onBuilding = onBuilding; | ||
_entryPointCompleted = entryPointCompleted; | ||
_applicationBuilderListener = new(this); | ||
} | ||
|
||
public async Task<DistributedApplication> InvokeAsync(CancellationToken cancellationToken) | ||
{ | ||
using var subscription = DiagnosticListener.AllListeners.Subscribe(this); | ||
|
||
// Kick off the entry point on a new thread so we don't block the current one | ||
// in case we need to timeout the execution | ||
var thread = new Thread(() => | ||
{ | ||
Exception? exception = null; | ||
try | ||
{ | ||
// Set the async local to the instance of the HostingListener so we can filter events that | ||
// aren't scoped to this execution of the entry point. | ||
s_currentListener.Value = this; | ||
var parameters = _entryPoint.GetParameters(); | ||
object? result; | ||
if (parameters.Length == 0) | ||
{ | ||
result = _entryPoint.Invoke(null, []); | ||
} | ||
else | ||
{ | ||
result = _entryPoint.Invoke(null, [_args]); | ||
} | ||
// Try to set an exception if the entry point returns gracefully, this will force | ||
// build to throw | ||
_appTcs.TrySetException(new InvalidOperationException($"The entry point exited without building a {nameof(DistributedApplication)}.")); | ||
} | ||
catch (TargetInvocationException tie) when (tie.InnerException?.GetType().Name == "HostAbortedException") | ||
{ | ||
// The host was stopped by our own logic | ||
} | ||
catch (TargetInvocationException tie) | ||
{ | ||
exception = tie.InnerException ?? tie; | ||
// Another exception happened, propagate that to the caller | ||
_appTcs.TrySetException(exception); | ||
} | ||
catch (Exception ex) | ||
{ | ||
exception = ex; | ||
// Another exception happened, propagate that to the caller | ||
_appTcs.TrySetException(exception); | ||
} | ||
finally | ||
{ | ||
// Signal that the entry point is completed | ||
_entryPointCompleted?.Invoke(exception); | ||
} | ||
}) | ||
{ | ||
// Make sure this doesn't hang the process | ||
IsBackground = true, | ||
Name = $"{_entryPoint.DeclaringType?.Assembly.GetName().Name ?? "Unknown"}.EntryPoint" | ||
}; | ||
|
||
// Start the thread | ||
thread.Start(); | ||
|
||
return await _appTcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false); | ||
} | ||
|
||
public void OnCompleted() | ||
{ | ||
} | ||
|
||
public void OnError(Exception error) | ||
{ | ||
|
||
} | ||
|
||
public void OnNext(DiagnosticListener value) | ||
{ | ||
if (s_currentListener.Value != this) | ||
{ | ||
// Ignore events that aren't for this listener | ||
return; | ||
} | ||
|
||
if (value.Name == "Aspire.Hosting") | ||
{ | ||
_applicationBuilderListener.Subscribe(value); | ||
} | ||
} | ||
|
||
private sealed class ApplicationBuilderDiagnosticListener(EntryPointInvoker owner) : IObserver<KeyValuePair<string, object?>> | ||
{ | ||
private IDisposable? _disposable; | ||
|
||
public void Subscribe(DiagnosticListener listener) | ||
{ | ||
_disposable = listener.Subscribe(this); | ||
} | ||
|
||
public void OnCompleted() | ||
{ | ||
_disposable?.Dispose(); | ||
} | ||
|
||
public void OnError(Exception error) | ||
{ | ||
} | ||
|
||
public void OnNext(KeyValuePair<string, object?> value) | ||
{ | ||
if (s_currentListener.Value != owner) | ||
{ | ||
// Ignore events that aren't for this listener | ||
return; | ||
} | ||
|
||
if (value.Key == "DistributedApplicationBuilderConstructing") | ||
{ | ||
var args = ((DistributedApplicationOptions Options, HostApplicationBuilderSettings InnerBuilderOptions))value.Value!; | ||
owner._onConstructing?.Invoke(args.Options, args.InnerBuilderOptions); | ||
} | ||
|
||
if (value.Key == "DistributedApplicationBuilderConstructed") | ||
{ | ||
owner._onConstructed?.Invoke((DistributedApplicationBuilder)value.Value!); | ||
} | ||
|
||
if (value.Key == "DistributedApplicationBuilding") | ||
{ | ||
owner._onBuilding?.Invoke((DistributedApplicationBuilder)value.Value!); | ||
} | ||
|
||
if (value.Key == "DistributedApplicationBuilt") | ||
{ | ||
owner._appTcs.TrySetResult((DistributedApplication)value.Value!); | ||
} | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
???