-
Notifications
You must be signed in to change notification settings - Fork 975
Add persistent container test coverage #17871
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
Merged
David Negstad (danegsta)
merged 15 commits into
main
from
copilot/test-persistent-containers
Jun 3, 2026
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
15fe453
Add per-integration persistence tests
Copilot eb37b4f
Add CLI persistent container E2E test
Copilot fd7746f
Fix persistence test compilation
Copilot 153a527
Address persistence test review feedback
Copilot 57950a2
Add Azure emulator mode coverage
Copilot c8479b4
Address emulator mode test review feedback
Copilot c3d1402
Stabilize persistent container tests
danegsta 3243747
Stop forcing test container registry in persistent helper
danegsta e65d57f
Use start waits in persistent container E2E
danegsta 51ebd05
Compare Docker container IDs in persistent tests
danegsta b2c7c07
Read synthetic user secrets in persistent tests
danegsta f331b48
Allow persistent tests to opt into test registry
danegsta acc3f94
Make persistent test secrets cleanup best effort
danegsta b4189da
Fix persistent container E2E networking
danegsta 9322d65
Propagate CLI E2E start timeout
danegsta 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 hidden or 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 hidden or 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
170 changes: 170 additions & 0 deletions
170
tests/Aspire.Cli.EndToEnd.Tests/PersistentContainerEndToEndTests.cs
This file contains hidden or 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,170 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Aspire.Cli.EndToEnd.Tests.Helpers; | ||
| using Aspire.Cli.Tests.Utils; | ||
| using Hex1b.Automation; | ||
| using Xunit; | ||
|
|
||
| namespace Aspire.Cli.EndToEnd.Tests; | ||
|
|
||
| public sealed class PersistentContainerEndToEndTests(ITestOutputHelper output) | ||
| { | ||
| private const string ProjectName = "PersistenceE2E"; | ||
|
|
||
| [Fact] | ||
| [CaptureWorkspaceOnFailure] | ||
| public async Task PersistentContainersPreserveDataAcrossAppHostRuns() | ||
| { | ||
| var repoRoot = CliE2ETestHelpers.GetRepoRoot(); | ||
| var strategy = CliInstallStrategy.Detect(output.WriteLine); | ||
| using var workspace = TemporaryWorkspace.Create(output); | ||
|
|
||
| // The AppHost runs inside the E2E container while DCP starts backing containers through the host Docker socket. | ||
| // Host networking lets project resources connect to the Docker-published ports that Aspire puts in connection strings. | ||
| using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, mountDockerSocket: true, workspace: workspace, network: "host"); | ||
| var counter = new SequenceCounter(); | ||
| var auto = new Hex1bTerminalAutomator(terminal, defaultTimeout: TimeSpan.FromSeconds(500)); | ||
| await using var terminalRun = CliE2ETestHelpers.StartRun(terminal, workspace, auto, counter, output, TestContext.Current.CancellationToken); | ||
|
|
||
| await auto.PrepareDockerEnvironmentAsync(counter, workspace); | ||
| await auto.InstallAspireCliAsync(strategy, counter); | ||
|
|
||
| var appHostCode = $$""" | ||
| #pragma warning disable ASPIREPERSISTENCE001 | ||
|
|
||
| var builder = DistributedApplication.CreateBuilder(args); | ||
|
|
||
| var redis = builder.AddRedis("redis") | ||
| .WithPersistentLifetime(); | ||
|
|
||
| var postgres = builder.AddPostgres("postgres") | ||
| .WithPersistentLifetime(); | ||
| var postgresDatabase = postgres.AddDatabase("pgdb"); | ||
|
|
||
| var storage = builder.AddAzureStorage("storage") | ||
| .RunAsEmulator(container => container.WithPersistentLifetime()); | ||
| var blobs = storage.AddBlobs("blobs"); | ||
|
|
||
| builder.AddProject<Projects.{{ProjectName}}_ApiService>("server") | ||
| .WithReference(redis) | ||
| .WithReference(postgresDatabase) | ||
| .WithReference(blobs) | ||
| .WaitFor(redis) | ||
| .WaitFor(postgresDatabase) | ||
| .WaitFor(blobs) | ||
| .WithExternalHttpEndpoints(); | ||
|
|
||
| builder.Build().Run(); | ||
| """; | ||
|
|
||
| var apiProgramCode = """ | ||
| using Azure.Storage.Blobs; | ||
| using Npgsql; | ||
| using StackExchange.Redis; | ||
|
|
||
| const string Marker = "persistent-container-value"; | ||
| const string RedisKey = "persistent-container-key"; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
| builder.AddServiceDefaults(); | ||
| builder.AddRedisClient("redis"); | ||
| builder.AddNpgsqlDataSource("pgdb"); | ||
| builder.AddAzureBlobServiceClient("blobs"); | ||
|
|
||
| var app = builder.Build(); | ||
| app.MapDefaultEndpoints(); | ||
|
|
||
| app.MapGet("/write", async (IConnectionMultiplexer redis, NpgsqlDataSource postgres, BlobServiceClient blobService) => | ||
| { | ||
| await redis.GetDatabase().StringSetAsync(RedisKey, Marker); | ||
|
|
||
| await using (var connection = await postgres.OpenConnectionAsync()) | ||
| await using (var command = connection.CreateCommand()) | ||
| { | ||
| command.CommandText = "CREATE TABLE IF NOT EXISTS persistence_check (id integer PRIMARY KEY, value text NOT NULL);" + | ||
| "INSERT INTO persistence_check (id, value) VALUES (1, 'persistent-container-value') " + | ||
| "ON CONFLICT (id) DO UPDATE SET value = EXCLUDED.value;"; | ||
| await command.ExecuteNonQueryAsync(); | ||
| } | ||
|
|
||
| var container = blobService.GetBlobContainerClient("persistence-check"); | ||
| await container.CreateIfNotExistsAsync(); | ||
| await container.GetBlobClient("marker").UploadAsync(BinaryData.FromString(Marker), overwrite: true); | ||
|
|
||
| return Results.Ok("PERSISTENCE_WRITE_OK"); | ||
| }); | ||
|
|
||
| app.MapGet("/verify", async (IConnectionMultiplexer redis, NpgsqlDataSource postgres, BlobServiceClient blobService) => | ||
| { | ||
| var redisValue = await redis.GetDatabase().StringGetAsync(RedisKey); | ||
| if (redisValue != Marker) | ||
| { | ||
| return Results.Problem($"Redis value was '{redisValue}'."); | ||
| } | ||
|
|
||
| await using (var connection = await postgres.OpenConnectionAsync()) | ||
| await using (var command = connection.CreateCommand()) | ||
| { | ||
| command.CommandText = "SELECT value FROM persistence_check WHERE id = 1"; | ||
| var postgresValue = (await command.ExecuteScalarAsync())?.ToString(); | ||
| if (!StringComparer.Ordinal.Equals(postgresValue, Marker)) | ||
| { | ||
| return Results.Problem($"PostgreSQL value was '{postgresValue}'."); | ||
| } | ||
| } | ||
|
|
||
| var blob = blobService.GetBlobContainerClient("persistence-check").GetBlobClient("marker"); | ||
| var blobContent = (await blob.DownloadContentAsync()).Value.Content.ToString(); | ||
| if (blobContent != Marker) | ||
| { | ||
| return Results.Problem($"Azure Storage blob value was '{blobContent}'."); | ||
| } | ||
|
|
||
| return Results.Ok("PERSISTENCE_VERIFY_OK"); | ||
| }); | ||
|
|
||
| app.Run(); | ||
| """; | ||
|
|
||
| await auto.ScaffoldK8sDeployProjectAsync( | ||
| counter, | ||
| ProjectName, | ||
| Path.Combine(workspace.WorkspaceRoot.FullName, ProjectName), | ||
| appHostHostingPackages: ["Aspire.Hosting.Redis", "Aspire.Hosting.PostgreSQL", "Aspire.Hosting.Azure.Storage"], | ||
| apiClientPackages: ["Aspire.StackExchange.Redis", "Aspire.Npgsql", "Aspire.Azure.Storage.Blobs"], | ||
| appHostCode: appHostCode, | ||
| apiProgramCode: apiProgramCode, | ||
| output: output); | ||
|
|
||
| await auto.AspireStartAsync(counter, TimeSpan.FromMinutes(5)); | ||
| await VerifyEndpointAsync(auto, counter, "/write", "PERSISTENCE_WRITE_OK"); | ||
| await auto.AspireStopAsync(counter); | ||
|
|
||
| await auto.AspireStartAsync(counter, TimeSpan.FromMinutes(5)); | ||
| await VerifyEndpointAsync(auto, counter, "/verify", "PERSISTENCE_VERIFY_OK"); | ||
| await auto.AspireStopAsync(counter); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Waits for the server resource and verifies that the endpoint returns the expected marker. | ||
| /// </summary> | ||
| /// <param name="auto">The terminal automator used to run CLI and shell commands.</param> | ||
| /// <param name="counter">The prompt sequence counter used to synchronize command completion.</param> | ||
| /// <param name="path">The server endpoint path to call.</param> | ||
| /// <param name="marker">The marker text expected in the endpoint response.</param> | ||
| private static async Task VerifyEndpointAsync(Hex1bTerminalAutomator auto, SequenceCounter counter, string path, string marker) | ||
| { | ||
| await auto.TypeAsync("aspire wait server --status up --timeout 300"); | ||
| await auto.EnterAsync(); | ||
| await auto.WaitForSuccessPromptAsync(counter, TimeSpan.FromMinutes(5)); | ||
|
|
||
| await auto.TypeAsync("aspire describe server --format json > server.json"); | ||
| await auto.EnterAsync(); | ||
| await auto.WaitForSuccessPromptAsync(counter, TimeSpan.FromSeconds(30)); | ||
|
|
||
| await auto.TypeAsync($"SERVER_URL=$(jq -er '.resources[0].urls[0].url' server.json) && for i in $(seq 1 30); do result=$(curl -ksS \"$SERVER_URL{path}\" 2>/dev/null || true); echo \"$result\"; echo \"$result\" | grep -q '{marker}' && break; sleep 2; done && echo \"$result\" | grep -q '{marker}'"); | ||
| await auto.EnterAsync(); | ||
| await auto.WaitForSuccessPromptAsync(counter, TimeSpan.FromMinutes(2)); | ||
| } | ||
| } | ||
53 changes: 53 additions & 0 deletions
53
tests/Aspire.Hosting.Azure.Tests/AzureRunAsEmulatorModeTests.cs
This file contains hidden or 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,53 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| #pragma warning disable ASPIRECOSMOSDB001 | ||
|
|
||
| using Aspire.Hosting.ApplicationModel; | ||
| using Aspire.Hosting.Utils; | ||
|
|
||
| namespace Aspire.Hosting.Azure.Tests; | ||
|
|
||
| public class AzureRunAsEmulatorModeTests | ||
| { | ||
| public static TheoryData<string, Func<IDistributedApplicationBuilder, Action, IResource>> RunAsEmulatorResources => new() | ||
| { | ||
| { "Azure App Configuration", (builder, configure) => builder.AddAzureAppConfiguration("appconfig").RunAsEmulator(_ => configure()).Resource }, | ||
| { "Azure Cosmos DB", (builder, configure) => builder.AddAzureCosmosDB("cosmos").RunAsEmulator(_ => configure()).Resource }, | ||
| { "Azure Cosmos DB preview", (builder, configure) => builder.AddAzureCosmosDB("cosmos").RunAsPreviewEmulator(_ => configure()).Resource }, | ||
| { "Azure Event Hubs", (builder, configure) => builder.AddAzureEventHubs("eventhubs").RunAsEmulator(_ => configure()).Resource }, | ||
| { "Azure Kusto", (builder, configure) => builder.AddAzureKustoCluster("kusto").RunAsEmulator(_ => configure()).Resource }, | ||
| { "Azure Service Bus", (builder, configure) => builder.AddAzureServiceBus("servicebus").RunAsEmulator(_ => configure()).Resource }, | ||
| { "Azure SignalR", (builder, configure) => builder.AddAzureSignalR("signalr").RunAsEmulator(_ => configure()).Resource }, | ||
| { "Azure Storage", (builder, configure) => builder.AddAzureStorage("storage").RunAsEmulator(_ => configure()).Resource }, | ||
| }; | ||
|
|
||
| [Theory] | ||
| [MemberData(nameof(RunAsEmulatorResources))] | ||
| public void RunAsEmulator_InRunMode_ConfiguresLocalContainer(string resourceType, Func<IDistributedApplicationBuilder, Action, IResource> addResource) | ||
| { | ||
| using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Run); | ||
| var callbackInvoked = false; | ||
|
|
||
| var resource = addResource(builder, () => callbackInvoked = true); | ||
|
|
||
| Assert.True(callbackInvoked); | ||
| Assert.True(resource.IsEmulator() || resource.IsContainer(), $"{resourceType} should be configured as an emulator or local container in run mode."); | ||
| Assert.Contains(builder.Resources, resource => resource.Annotations.OfType<ContainerImageAnnotation>().Any()); | ||
| } | ||
|
|
||
| [Theory] | ||
| [MemberData(nameof(RunAsEmulatorResources))] | ||
| public void RunAsEmulator_InPublishMode_DoesNotConfigureLocalContainer(string resourceType, Func<IDistributedApplicationBuilder, Action, IResource> addResource) | ||
| { | ||
| using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish); | ||
| var callbackInvoked = false; | ||
|
|
||
| var resource = addResource(builder, () => callbackInvoked = true); | ||
|
|
||
| Assert.False(callbackInvoked); | ||
| Assert.False(resource.IsEmulator(), $"{resourceType} should not be configured as an emulator in publish mode."); | ||
| Assert.False(resource.IsContainer(), $"{resourceType} should not be configured as a local container in publish mode."); | ||
| Assert.DoesNotContain(builder.Resources, resource => resource.Annotations.OfType<ContainerImageAnnotation>().Any()); | ||
| } | ||
| } |
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.