Skip to content
Closed
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
26 changes: 26 additions & 0 deletions docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,32 @@ To test changes from a specific pull request locally, see [dogfooding-pull-reque

To validate how the CLI resolves `Aspire.*` packages for **staging** and **stable** release-branch builds (including making an installed PR build behave like a staging build), see [cli-staging-validation.md](/docs/cli-staging-validation.md).

The Go CLI E2E scenarios in `GoCodegenValidationTests` cover interactive initialization,
non-interactive initialization in an empty directory and alongside an existing Go application,
SDK refresh, and Go build/vet checks. `GoStarterTemplateTests.RestoreAndBuildGoStarterFromStablePackages`
requires a stable-shaped local hive; normal prerelease PR archives skip that test.

**Prerequisite:** use an already-built stable-shaped local-hive archive containing the CLI
and matching packages at an unpublished stable version. Building one with
`localhive --version 17.0.99 --archive` currently fails during packing with `NU5104`
because stable component packages depend on prerelease .NET 11 packages. This also
affects Linux; changing the RID does not avoid the package-version restriction.
The test command below does not prepare that archive or validate a stable native bundle.

Given such an archive, exercise both classes on Linux with Docker:

```bash
ASPIRE_E2E_ARCHIVE="/path/to/stable-shaped-localhive.tar.gz" \
dotnet test --project tests/Aspire.Cli.EndToEnd.Tests/Aspire.Cli.EndToEnd.Tests.csproj --no-launch-profile -- \
--filter-class "*.GoCodegenValidationTests" --filter-class "*.GoStarterTemplateTests" \
--filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true"
```

Use an unpublished stable version for the local hive. The stable starter test runs the CLI
with a stable identity, an isolated NuGet cache and the hive as its package source. It checks
the exact Go and Redis package pins, regenerates the SDK and compiles/vets it. The separate
`CreateAndRunGoStarterProject` scenario verifies startup using the archive's normal channel.

### NuGet configuration in CLI unit tests

Use `NuGetTestHelper.CreateClient()` or `CreateService()` for tests that compose real NuGet configuration, and `NuGetTestHelper.LoadSettings()` for native settings assertions. These helpers preserve directory-level configuration inheritance while replacing the runner's user-wide settings with a controlled baseline and excluding machine-wide settings by default. Supply `TestMachineWideSettings` explicitly when testing machine-wide policy.
Expand Down
71 changes: 68 additions & 3 deletions tests/Aspire.Cli.EndToEnd.Tests/GoCodegenValidationTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.Json.Nodes;
using Aspire.Cli.EndToEnd.Tests.Helpers;
using Hex1b.Automation;
using Xunit;
Expand All @@ -13,9 +14,12 @@ namespace Aspire.Cli.EndToEnd.Tests;
/// </summary>
public sealed class GoCodegenValidationTests(ITestOutputHelper output)
{
[Fact]
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(true, true)]
[CaptureWorkspaceOnFailure]
public async Task RestoreGeneratesSdkFiles()
public async Task RestoreGeneratesSdkFiles(bool nonInteractive, bool existingProject)
{
var repoRoot = CliE2ETestHelpers.GetRepoRoot();
var strategy = CliInstallStrategy.Detect(output.WriteLine);
Expand All @@ -29,7 +33,60 @@ public async Task RestoreGeneratesSdkFiles()
await auto.PrepareDockerEnvironmentAsync(counter, workspace);
await auto.InstallAspireCliAsync(strategy, counter);

await auto.AspireInitGoAppHostAsync(counter);
var existingFiles = new Dictionary<string, string>();
if (existingProject)
{
var apiDirectory = workspace.CreateDirectory("api");
existingFiles[Path.Combine(apiDirectory.FullName, "go.mod")] = """
module example.com/existing-api

go 1.26
""";
existingFiles[Path.Combine(apiDirectory.FullName, "main.go")] = """
package main

import "fmt"

func main() {
fmt.Println("existing Go application")
}
""";
foreach (var (path, content) in existingFiles)
{
await File.WriteAllTextAsync(path, content);
}
}

if (nonInteractive)
{
await auto.RunCommandAsync(
"aspire init --language go --non-interactive --suppress-agent-init < /dev/null",
counter,
TimeSpan.FromMinutes(3));
}
else
{
await auto.AspireInitGoAppHostAsync(counter);
}

var configPath = Path.Combine(workspace.WorkspaceRoot.FullName, "aspire.config.json");
var config = JsonNode.Parse(await File.ReadAllTextAsync(configPath));
Assert.NotNull(config);
Assert.Equal("go", config["appHost"]?["language"]?.GetValue<string>());
Assert.Equal("apphost.go", config["appHost"]?["path"]?.GetValue<string>());
Assert.False(string.IsNullOrEmpty(config["packages"]?["Aspire.Hosting.Go"]?.GetValue<string>()));

foreach (var (path, content) in existingFiles)
{
Assert.Equal(content, await File.ReadAllTextAsync(path));
}

if (existingProject)
{
GoAppHostTestHelpers.InsertBeforeBuild(
Path.Combine(workspace.WorkspaceRoot.FullName, "apphost.go"),
"""builder.AddGoApp("existing-api", "./api")""");
}

await auto.AspireAddPackageAsync("Aspire.Hosting.Redis", counter);
await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3));
Expand Down Expand Up @@ -79,5 +136,13 @@ public async Task RestoreGeneratesSdkFiles()
"aspire.go does not contain AddSqlServer from Aspire.Hosting.SqlServer; restore did not refresh an already-populated .aspire/modules");

Assert.NotEqual(initialCodegenHash, File.ReadAllText(codegenHashPath));

// Build the consumer and vet the generated module explicitly: ./... skips the hidden .aspire directory.
await auto.RunCommandAsync("go build -buildvcs=false ./... && go vet ./...", counter, TimeSpan.FromMinutes(3));
await auto.RunCommandAsync("(cd .aspire/modules && go vet ./...)", counter, TimeSpan.FromMinutes(3));
if (existingProject)
{
await auto.RunCommandAsync("(cd api && go build -buildvcs=false ./... && go vet ./...)", counter, TimeSpan.FromMinutes(3));
}
}
}
94 changes: 88 additions & 6 deletions tests/Aspire.Cli.EndToEnd.Tests/GoStarterTemplateTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.Json.Nodes;
using Aspire.Cli.EndToEnd.Tests.Helpers;
using Hex1b.Automation;
using Xunit;
Expand All @@ -16,10 +17,27 @@ public sealed class GoStarterTemplateTests(ITestOutputHelper output)
{
[CaptureWorkspaceOnFailure]
[Fact]
public async Task CreateAndRunGoStarterProject()
public Task CreateAndRunGoStarterProject() => CreateRestoreAndBuildGoStarterAsync(emulateStableRelease: false);

[CaptureWorkspaceOnFailure]
[Fact]
public Task RestoreAndBuildGoStarterFromStablePackages() => CreateRestoreAndBuildGoStarterAsync(emulateStableRelease: true);

private async Task CreateRestoreAndBuildGoStarterAsync(bool emulateStableRelease)
{
var repoRoot = CliE2ETestHelpers.GetRepoRoot();
var strategy = CliInstallStrategy.Detect(output.WriteLine);
string? stableVersion = null;
if (emulateStableRelease)
{
Assert.SkipUnless(strategy.Mode == CliInstallMode.LocalHive,
"Stable Go starter coverage requires a localhive --version X.Y.Z --archive build.");
Assert.NotNull(strategy.ArchivePath);
stableVersion = CliE2ETestHelpers.TryGetStableAspireVersionFromArchive(strategy.ArchivePath);
Assert.SkipWhen(stableVersion is null,
"Build a stable-shaped local hive and set ASPIRE_E2E_ARCHIVE to its archive.");
}

using var workspace = TemporaryWorkspace.Create(output);

using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(
Expand All @@ -34,7 +52,29 @@ public async Task CreateAndRunGoStarterProject()
await using var terminalRun = CliE2ETestHelpers.StartRun(terminal, workspace, auto, counter, output, TestContext.Current.CancellationToken);

await auto.PrepareDockerEnvironmentAsync(counter, workspace);
await auto.InstallAspireCliAsync(strategy, counter);
if (emulateStableRelease)
{
// Do not configure the local channel: package resolution must honor the stable identity
// and its invocation-scoped hive, rather than a persisted channel or warm NuGet cache.
await auto.ExtractLocalHiveArchiveAsync("/tmp/aspire-localhive.tar.gz", counter);
await auto.SourceAspireCliEnvironmentAsync(counter);
await auto.RunCommandAsync(
$"export ASPIRE_CLI_CHANNEL=stable ASPIRE_CLI_VERSION={stableVersion} " +
"ASPIRE_CLI_PACKAGES=\"$HOME/.aspire/hives/local/packages\" " +
"NUGET_PACKAGES=\"$PWD/.stable-nuget-packages\"",
counter);
await auto.TypeAsync("aspire --version");
await auto.EnterAsync();
await auto.WaitUntilAsync(
snapshot => snapshot.ContainsText(stableVersion!) && snapshot.ContainsText("emulating identity"),
timeout: TimeSpan.FromSeconds(30),
description: "stable CLI identity before creating the Go starter");
await auto.WaitForSuccessPromptAsync(counter);
}
else
{
await auto.InstallAspireCliAsync(strategy, counter);
}

await auto.AspireNewAsync("GoStarterApp", counter, template: AspireTemplate.GoStarter);

Expand All @@ -43,16 +83,58 @@ public async Task CreateAndRunGoStarterProject()
var aspireModulePath = Path.Combine(projectRoot, ".aspire", "modules", "aspire.go");
Assert.True(File.Exists(aspireModulePath), $"Expected generated Go SDK file not found: {aspireModulePath}");

if (emulateStableRelease)
{
var config = JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(projectRoot, "aspire.config.json")));
Assert.NotNull(config);
Assert.Equal(stableVersion, config["packages"]?["Aspire.Hosting.Go"]?.GetValue<string>());
Assert.Equal(stableVersion, config["packages"]?["Aspire.Hosting.Redis"]?.GetValue<string>());
Assert.Null(config["channel"]);
}

await auto.TypeAsync("cd GoStarterApp");
await auto.EnterAsync();
await auto.WaitForSuccessPromptAsync(counter);

if (emulateStableRelease)
{
await auto.RunCommandAsync("rm -rf ../.stable-nuget-packages", counter);
}

// A second restore must regenerate the SDK, not succeed by reusing the template's output.
await auto.RunCommandAsync("rm -rf .aspire/modules && aspire restore --non-interactive < /dev/null", counter, TimeSpan.FromMinutes(3));
Assert.True(File.Exists(aspireModulePath), $"Restore did not regenerate {aspireModulePath}");

if (emulateStableRelease)
{
foreach (var packageId in new[] { "aspire.hosting.go", "aspire.hosting.redis" })
{
var metadata = $"../.stable-nuget-packages/{packageId}/{stableVersion}/.nupkg.metadata";
await auto.RunCommandAsync(
$"node -e 'const fs = require(\"node:fs\"), assert = require(\"node:assert/strict\"); " +
$"const metadata = JSON.parse(fs.readFileSync(\"{metadata}\", \"utf8\")); " +
"const expected = fs.realpathSync(process.env.HOME + \"/.aspire/hives/local/packages\"); " +
"assert.equal(fs.realpathSync(metadata.source), expected);'",
counter);
}
}

// The workspace is not a git repository, so VCS stamping would fail the build.
await auto.RunCommandAsync("go build -buildvcs=false ./...", counter, TimeSpan.FromMinutes(3));
await auto.RunCommandAsync("go vet ./... && (cd .aspire/modules && go vet ./...)", counter, TimeSpan.FromMinutes(3));

// The Go API runs `go mod tidy` before it starts, which downloads the OpenTelemetry modules.
await auto.AspireStartAsync(counter, startTimeout: TimeSpan.FromMinutes(4));
await auto.AssertResourcesExistAsync(counter, "cache", "api");
await auto.AspireStopAsync(counter);
if (!emulateStableRelease)
{
// The Go API runs `go mod tidy` before it starts, which downloads the OpenTelemetry modules.
await auto.AspireStartAsync(counter, startTimeout: TimeSpan.FromMinutes(4));
try
{
await auto.AssertResourcesExistAsync(counter, "cache", "api");
}
finally
{
await auto.AspireStopAsync(counter);
}
}
}
}
31 changes: 31 additions & 0 deletions tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2ETestHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
Expand Down Expand Up @@ -1157,6 +1159,35 @@ private static LocalChannelInfo PrepareLocalChannelCore(
return bestRaw;
}

internal static string? TryGetStableAspireVersionFromArchive(string archivePath)
{
using var archive = File.OpenRead(archivePath);
using var gzip = new GZipStream(archive, CompressionMode.Decompress);
using var tar = new TarReader(gzip);

// Local-hive entries look like "hives/local/packages/Aspire.Hosting.17.0.99.nupkg".
// Some tar writers prefix entries with "./"; prerelease packages must not enable this lane.
var stablePackageRegex = new Regex(@"^(?:\./)?hives/local/packages/Aspire\.Hosting\.(?<version>\d+\.\d+\.\d+)\.nupkg$", RegexOptions.IgnoreCase);
Version? bestVersion = null;
while (tar.GetNextEntry() is { } entry)
{
if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile))
{
continue;
}

var match = stablePackageRegex.Match(entry.Name);
if (match.Success &&
Version.TryParse(match.Groups["version"].Value, out var version) &&
(bestVersion is null || version > bestVersion))
{
bestVersion = version;
}
}

return bestVersion?.ToString();
}

internal static void WriteLocalChannelSettings(string projectRoot, string sdkVersion)
{
var configPath = Path.Combine(projectRoot, "aspire.config.json");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Formats.Tar;
using System.IO.Compression;
using Hex1b;
using Xunit;

namespace Aspire.Cli.EndToEnd.Tests.Helpers;

[Collection(CliInstallEnvironmentCollection.Name)]
public class CliInstallStrategyTests
public class CliInstallStrategyTests(ITestOutputHelper output)
{
[Theory]
[InlineData("hives/local/packages/Aspire.Hosting.17.0.99.nupkg", "17.0.99")]
[InlineData("./hives/local/packages/Aspire.Hosting.17.0.99.nupkg", "17.0.99")]
[InlineData("hives/local/packages/Aspire.Hosting.17.0.0-dev.nupkg", null)]
[InlineData("hives/local/packages/Aspire.Hosting.Go.17.0.99.nupkg", null)]
[InlineData("other/Aspire.Hosting.17.0.99.nupkg", null)]
public void TryGetStableAspireVersionFromArchive_UsesSelectedHive(string packageEntry, string? expectedVersion)
{
using var workspace = TemporaryWorkspace.Create(output);
var archivePath = Path.Combine(workspace.WorkspaceRoot.FullName, "selected.tar.gz");
using (var file = File.Create(archivePath))
using (var gzip = new GZipStream(file, CompressionLevel.Fastest))
using (var tar = new TarWriter(gzip))
{
tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, packageEntry));
}

Assert.Equal(expectedVersion, CliE2ETestHelpers.TryGetStableAspireVersionFromArchive(archivePath));
}

[Fact]
public void GetPullRequestInstallArgs_ReturnsPrNumber()
{
Expand Down
Loading