diff --git a/.github/workflows/build-cli-e2e-image.yml b/.github/workflows/build-cli-e2e-image.yml index 60337f5b15b..71a806f8c16 100644 --- a/.github/workflows/build-cli-e2e-image.yml +++ b/.github/workflows/build-cli-e2e-image.yml @@ -23,6 +23,8 @@ env: CLI_E2E_POLYGLOT_IMAGE_TAG: aspire-cli-e2e-polyglot:prebuilt CLI_E2E_POLYGLOT_JAVA_IMAGE_ARTIFACT: cli-e2e-polyglot-java-image CLI_E2E_POLYGLOT_JAVA_IMAGE_TAG: aspire-cli-e2e-polyglot-java:prebuilt + CLI_E2E_POLYGLOT_GO_IMAGE_ARTIFACT: cli-e2e-polyglot-go-image + CLI_E2E_POLYGLOT_GO_IMAGE_TAG: aspire-cli-e2e-polyglot-go:prebuilt CLI_E2E_POLYGLOT_BASE_IMAGE_TAG: aspire-e2e-polyglot-base:latest CLI_E2E_POLYGLOT_BASE_IMAGE_CACHE_SCOPE: cli-e2e-polyglot-base CLI_E2E_INCLUDE_POLYGLOT_IMAGES: ${{ inputs.includePolyglotImages }} @@ -104,6 +106,24 @@ jobs: . } + build_go_image() { + local mirror="$1" + local -a build_args=() + + if [[ -n "$mirror" ]]; then + echo "Building Go polyglot image with Ubuntu apt mirror: $mirror" + build_args+=(--build-arg "UBUNTU_APT_MIRROR=$mirror") + else + echo "Building Go polyglot image with the default Ubuntu apt sources" + fi + + DOCKER_BUILDKIT=1 docker build \ + "${build_args[@]}" \ + -f tests/Shared/Docker/Dockerfile.e2e-polyglot-go \ + -t "$CLI_E2E_POLYGLOT_GO_IMAGE_TAG" \ + . + } + build_with_mirror_retry() { local display_name="$1" local dockerfile="$2" @@ -126,6 +146,11 @@ jobs: echo "Java polyglot image build failed with the Azure Ubuntu apt mirror; retrying with default Ubuntu apt sources" build_java_image "" fi + + if ! build_go_image "http://azure.archive.ubuntu.com/ubuntu/"; then + echo "Go polyglot image build failed with the Azure Ubuntu apt mirror; retrying with default Ubuntu apt sources" + build_go_image "" + fi fi - name: Save CLI E2E Docker image tarballs @@ -139,6 +164,7 @@ jobs: if [[ "$CLI_E2E_INCLUDE_POLYGLOT_IMAGES" == "true" ]]; then docker save "$CLI_E2E_POLYGLOT_IMAGE_TAG" | gzip > artifacts/cli-e2e-image/aspire-cli-e2e-polyglot.tar.gz docker save "$CLI_E2E_POLYGLOT_JAVA_IMAGE_TAG" | gzip > artifacts/cli-e2e-image/aspire-cli-e2e-polyglot-java.tar.gz + docker save "$CLI_E2E_POLYGLOT_GO_IMAGE_TAG" | gzip > artifacts/cli-e2e-image/aspire-cli-e2e-polyglot-go.tar.gz fi - name: Upload CLI E2E .NET Docker image @@ -164,3 +190,11 @@ jobs: name: ${{ env.CLI_E2E_POLYGLOT_JAVA_IMAGE_ARTIFACT }} path: artifacts/cli-e2e-image/aspire-cli-e2e-polyglot-java.tar.gz retention-days: 1 + + - name: Upload CLI E2E Go Docker image + if: ${{ inputs.uploadImageArtifacts && inputs.includePolyglotImages }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ${{ env.CLI_E2E_POLYGLOT_GO_IMAGE_ARTIFACT }} + path: artifacts/cli-e2e-image/aspire-cli-e2e-polyglot-go.tar.gz + retention-days: 1 diff --git a/.github/workflows/reproduce-flaky-tests.yml b/.github/workflows/reproduce-flaky-tests.yml index 694d9e47192..2f244a22fa1 100644 --- a/.github/workflows/reproduce-flaky-tests.yml +++ b/.github/workflows/reproduce-flaky-tests.yml @@ -197,6 +197,13 @@ jobs: name: cli-e2e-polyglot-java-image path: ${{ github.workspace }}/cli-e2e-image + - name: Download prebuilt CLI E2E Go Docker image + if: ${{ needs.setup.outputs.is_cli_e2e == 'true' && runner.os == 'Linux' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: cli-e2e-polyglot-go-image + path: ${{ github.workspace }}/cli-e2e-image + - name: Download prebuilt CLI E2E polyglot Docker image if: ${{ needs.setup.outputs.is_cli_e2e == 'true' && runner.os == 'Linux' }} uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 @@ -213,7 +220,8 @@ jobs: --image-dir "${{ github.workspace }}/cli-e2e-image" \ --require-dotnet true \ --require-polyglot true \ - --require-java true + --require-java true \ + --require-go true - name: Unlock macOS keychain if: runner.os == 'macOS' diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 591d474f2e7..ae922c57e00 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -162,6 +162,15 @@ jobs: name: cli-e2e-polyglot-java-image path: ${{ github.workspace }}/cli-e2e-image + # Go CLI E2E classes are named Go*, so '-Go' matches the class suffix of the split job name + # (Cli.EndToEnd-GoStarterTemplateTests) without matching names that merely contain "go" (MongoDB, Config). + - name: Download prebuilt CLI E2E Go Docker image + if: ${{ fromJson(inputs.properties).requiresCliArchive == true && runner.os == 'Linux' && contains(inputs.testShortName, '-Go') }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: cli-e2e-polyglot-go-image + path: ${{ github.workspace }}/cli-e2e-image + - name: Load prebuilt CLI E2E Docker images if: ${{ fromJson(inputs.properties).requiresCliArchive == true && runner.os == 'Linux' }} shell: bash @@ -171,7 +180,8 @@ jobs: --image-dir "${{ github.workspace }}/cli-e2e-image" \ --require-dotnet true \ --require-polyglot true \ - --require-java "${{ contains(inputs.testShortName, 'Java') }}" + --require-java "${{ contains(inputs.testShortName, 'Java') }}" \ + --require-go "${{ contains(inputs.testShortName, '-Go') }}" - name: Download built nugets if: ${{ fromJson(inputs.properties).requiresNugets == true }} diff --git a/.github/workflows/warm-cli-e2e-image-cache.yml b/.github/workflows/warm-cli-e2e-image-cache.yml index 4a36f717639..0f4d88e9162 100644 --- a/.github/workflows/warm-cli-e2e-image-cache.yml +++ b/.github/workflows/warm-cli-e2e-image-cache.yml @@ -18,6 +18,7 @@ on: - 'eng/scripts/get-aspire-cli-pr.sh' - 'tests/Shared/Docker/Dockerfile.e2e' - 'tests/Shared/Docker/Dockerfile.e2e-polyglot-base' + - 'tests/Shared/Docker/Dockerfile.e2e-polyglot-go' - 'tests/Shared/Docker/Dockerfile.e2e-polyglot-java' - 'tests/Shared/Docker/NuGet.DotnetTool.config' - 'tests/Shared/Docker/configure-ubuntu-apt-mirror.sh' diff --git a/docs/ci/cli-e2e-images.md b/docs/ci/cli-e2e-images.md index 26d7f6d93a1..8a315f11684 100644 --- a/docs/ci/cli-e2e-images.md +++ b/docs/ci/cli-e2e-images.md @@ -11,6 +11,7 @@ The reusable `.github/workflows/build-cli-e2e-image.yml` workflow produces these | DotNet | `tests/Shared/Docker/Dockerfile.e2e` | `cli-e2e-dotnet-image` | `aspire-cli-e2e-dotnet:prebuilt` | `ASPIRE_E2E_DOTNET_IMAGE` | `ASPIRE_E2E_REQUIRE_DOTNET_IMAGE` | | Polyglot | `tests/Shared/Docker/Dockerfile.e2e-polyglot-base` | `cli-e2e-polyglot-image` | `aspire-cli-e2e-polyglot:prebuilt` | `ASPIRE_E2E_POLYGLOT_IMAGE` | `ASPIRE_E2E_REQUIRE_POLYGLOT_IMAGE` | | Polyglot Java | `tests/Shared/Docker/Dockerfile.e2e-polyglot-java` | `cli-e2e-polyglot-java-image` | `aspire-cli-e2e-polyglot-java:prebuilt` | `ASPIRE_E2E_POLYGLOT_JAVA_IMAGE` | `ASPIRE_E2E_REQUIRE_POLYGLOT_JAVA_IMAGE` | +| Polyglot Go | `tests/Shared/Docker/Dockerfile.e2e-polyglot-go` | `cli-e2e-polyglot-go-image` | `aspire-cli-e2e-polyglot-go:prebuilt` | `ASPIRE_E2E_POLYGLOT_GO_IMAGE` | `ASPIRE_E2E_REQUIRE_POLYGLOT_GO_IMAGE` | `Dockerfile.e2e-podman` is not part of this contract because it uses a separate privileged Podman-in-Docker runtime path. @@ -22,9 +23,9 @@ This preserves the local development path while making opted-in CI jobs fail ear ## Workflow behavior -The image build workflow has an `includePolyglotImages` input. It defaults to `true` and builds all three shared images. Daily CLI smoke tests set it to `false` because they only need the DotNet image. +The image build workflow has an `includePolyglotImages` input. It defaults to `true` and builds all four shared images. Daily CLI smoke tests set it to `false` because they only need the DotNet image. -Consumer workflows download image artifacts into `${{ github.workspace }}/cli-e2e-image` and call `eng/scripts/load-cli-e2e-images.sh` to load the images and export the matching environment variables. Regular split CLI E2E jobs always require DotNet and Polyglot images. Java image download and loading is conditional on Java test jobs to avoid transferring the larger Java tarball to every split job. +Consumer workflows download image artifacts into `${{ github.workspace }}/cli-e2e-image` and call `eng/scripts/load-cli-e2e-images.sh` to load the images and export the matching environment variables. Regular split CLI E2E jobs always require DotNet and Polyglot images. Java and Go image download and loading is conditional on the split job name to avoid transferring the larger tarballs to every split job: Java jobs match `Java` and Go jobs match `-Go`, so Go CLI E2E test classes must be named `Go*` (for example `Cli.EndToEnd-GoStarterTemplateTests`). Specialized quarantine and outerloop runs are named after the test project, so a Go or Java class that is quarantined or marked outerloop does not receive its prebuilt image. The reusable image build workflow also has an `uploadImageArtifacts` input. It defaults to `true` for test workflows because each isolated test job needs the image tarballs. Cache-warming workflows set it to `false` so they only build the images and export BuildKit cache layers. @@ -39,7 +40,7 @@ The image build workflow exports BuildKit layers to the GitHub Actions cache wit GitHub Actions does not let one pull request restore cache entries written by a sibling pull request. Pull request runs can restore cache entries from the current PR ref and from the base/default branch. The `.github/workflows/warm-cli-e2e-image-cache.yml` workflow runs on `main` by schedule, manual dispatch, and relevant `main` pushes so new PRs can restore layers seeded from `main`. -The Java image is built from the local polyglot base image and does not use a separate shared BuildKit cache scope. +The Java and Go images are built from the local polyglot base image and do not use a separate shared BuildKit cache scope. ## Adding another variant diff --git a/eng/github-ci/test-trigger-map.yml b/eng/github-ci/test-trigger-map.yml index c244428335b..08d82c8aa99 100644 --- a/eng/github-ci/test-trigger-map.yml +++ b/eng/github-ci/test-trigger-map.yml @@ -744,12 +744,14 @@ affected_project_rules: - Aspire.Hosting - Aspire.Hosting.AppHost - Aspire.Hosting.Blazor + - Aspire.Hosting.CodeGeneration.Go - Aspire.Hosting.CodeGeneration.Java - Aspire.Hosting.CodeGeneration.TypeScript - Aspire.Hosting.Docker - Aspire.Hosting.Dotnet - Aspire.Hosting.EntityFrameworkCore - Aspire.Hosting.Garnet + - Aspire.Hosting.Go - Aspire.Hosting.Java - Aspire.Hosting.JavaScript - Aspire.Hosting.Kubernetes diff --git a/eng/scripts/load-cli-e2e-images.sh b/eng/scripts/load-cli-e2e-images.sh index 49d3975c4f2..321f8cc969c 100755 --- a/eng/scripts/load-cli-e2e-images.sh +++ b/eng/scripts/load-cli-e2e-images.sh @@ -7,6 +7,7 @@ github_env="${GITHUB_ENV:-}" require_dotnet="false" require_polyglot="false" require_java="false" +require_go="false" usage() { cat <<'EOF' @@ -21,6 +22,7 @@ Options: --require-dotnet true, false, or auto. Defaults to false. --require-polyglot true, false, or auto. Defaults to false. --require-java true, false, or auto. Defaults to false. + --require-go true, false, or auto. Defaults to false. Mode behavior: true The tarball must exist. Load it, export IMAGE and REQUIRE=true. @@ -105,6 +107,14 @@ while [[ $# -gt 0 ]]; do require_java="$(normalize_mode "--require-java" "${1#*=}")" shift ;; + --require-go) + require_go="$(normalize_mode "$1" "$(read_value_arg "$1" "${2:-}")")" + shift 2 + ;; + --require-go=*) + require_go="$(normalize_mode "--require-go" "${1#*=}")" + shift + ;; -h|--help) usage exit 0 @@ -184,3 +194,9 @@ load_image "Java polyglot" "$require_java" \ "aspire-cli-e2e-polyglot-java:prebuilt" \ "ASPIRE_E2E_POLYGLOT_JAVA_IMAGE" \ "ASPIRE_E2E_REQUIRE_POLYGLOT_JAVA_IMAGE" + +load_image "Go polyglot" "$require_go" \ + "aspire-cli-e2e-polyglot-go.tar.gz" \ + "aspire-cli-e2e-polyglot-go:prebuilt" \ + "ASPIRE_E2E_POLYGLOT_GO_IMAGE" \ + "ASPIRE_E2E_REQUIRE_POLYGLOT_GO_IMAGE" diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoCodegenValidationTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoCodegenValidationTests.cs new file mode 100644 index 00000000000..b8cf57922cd --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoCodegenValidationTests.cs @@ -0,0 +1,84 @@ +// 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 Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +/// +/// End-to-end tests that validate aspire restore for Go AppHosts by creating a +/// Go AppHost with multiple integrations and verifying the generated Go SDK files. +/// +public sealed class GoCodegenValidationTests(ITestOutputHelper output) +{ + [Fact] + [CaptureWorkspaceOnFailure] + public async Task RestoreGeneratesSdkFiles() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, workspace: workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + await auto.AspireInitGoAppHostAsync(counter); + + await auto.AspireAddPackageAsync("Aspire.Hosting.Redis", counter); + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + + var modulesDir = Path.Combine(workspace.WorkspaceRoot.FullName, ".aspire", "modules"); + Assert.True(Directory.Exists(modulesDir), $".aspire/modules directory was not created at {modulesDir}"); + + // aspire.go is the whole generated SDK in one file, so assert on substrings and keep it out of failure messages. + var sdkPath = Path.Combine(modulesDir, "aspire.go"); + var codegenHashPath = Path.Combine(modulesDir, ".codegen-hash"); + Assert.True(File.Exists(sdkPath), $"Expected generated file not found: {sdkPath}"); + Assert.True(File.Exists(codegenHashPath), $"Expected generated file not found: {codegenHashPath}"); + Assert.False( + File.ReadAllText(sdkPath).Contains("AddSqlServer", StringComparison.Ordinal), + "Baseline SDK already exposes AddSqlServer; test cannot verify refresh behavior after adding Aspire.Hosting.SqlServer."); + var initialCodegenHash = File.ReadAllText(codegenHashPath); + + // `aspire add` regenerates the SDK itself, so once it returns aspire.go already exposes AddSqlServer and + // .codegen-hash has already changed, and the restore below would have nothing left to prove. Putting the + // baseline copies back leaves a stale SDK next to an aspire.config.json that lists SqlServer, which is + // the state a restore has to refresh. The copies run inside the container: the workspace is bind-mounted + // and its files belong to the container's root user, so a write from the host can fail on Linux. + await auto.RunCommandAsync("mkdir -p ~/sdk-baseline && cp .aspire/modules/aspire.go .aspire/modules/.codegen-hash ~/sdk-baseline/", counter); + await auto.AspireAddPackageAsync("Aspire.Hosting.SqlServer", counter); + await auto.RunCommandAsync("cp ~/sdk-baseline/aspire.go ~/sdk-baseline/.codegen-hash .aspire/modules/", counter); + + Assert.False( + File.ReadAllText(sdkPath).Contains("AddSqlServer", StringComparison.Ordinal), + "The baseline SDK was not put back after aspire add, so restore would have nothing to refresh."); + Assert.Equal(initialCodegenHash, File.ReadAllText(codegenHashPath)); + + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + + var expectedFiles = new[] { "aspire.go", "base.go", "transport.go", "go.mod" }; + + foreach (var file in expectedFiles) + { + var filePath = Path.Combine(modulesDir, file); + Assert.True(File.Exists(filePath), $"Expected generated file not found: {filePath}"); + Assert.False(string.IsNullOrWhiteSpace(File.ReadAllText(filePath)), $"Generated file is empty: {filePath}"); + } + + var sdk = File.ReadAllText(sdkPath); + Assert.True(sdk.Contains("AddRedis", StringComparison.Ordinal), "aspire.go does not contain AddRedis from Aspire.Hosting.Redis"); + Assert.True( + sdk.Contains("AddSqlServer", StringComparison.Ordinal), + "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)); + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoEmptyAppHostTemplateTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoEmptyAppHostTemplateTests.cs new file mode 100644 index 00000000000..41d7b30b832 --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoEmptyAppHostTemplateTests.cs @@ -0,0 +1,90 @@ +// 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 Hex1b; +using Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +/// +/// End-to-end tests for the Go Empty AppHost template (aspire-go-empty). +/// Validates that aspire new creates a Go AppHost project that restores, compiles +/// and starts, both through the interactive template picker and the direct template command. +/// +public sealed class GoEmptyAppHostTemplateTests(ITestOutputHelper output) +{ + [Fact] + [CaptureWorkspaceOnFailure] + public async Task CreateAndRunGoEmptyAppHostProjectFromTemplatePicker() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CreateTerminal(repoRoot, strategy, workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + await auto.AspireNewAsync("GoEmptyApp", counter, template: AspireTemplate.GoEmptyAppHost); + + await RestoreBuildAndRunAsync(auto, counter, workspace, "GoEmptyApp"); + } + + [Fact] + [CaptureWorkspaceOnFailure] + public async Task CreateAndRunGoEmptyAppHostProjectFromDirectTemplate() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CreateTerminal(repoRoot, strategy, workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + await auto.AspireNewGoEmptyAppHostAsync("GoDirectApp", counter); + + await RestoreBuildAndRunAsync(auto, counter, workspace, "GoDirectApp"); + } + + private Hex1bTerminal CreateTerminal(string repoRoot, CliInstallStrategy strategy, TemporaryWorkspace workspace) => + CliE2ETestHelpers.CreateDockerTestTerminal( + repoRoot, + strategy, + output, + variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, + mountDockerSocket: true, + workspace: workspace); + + private static async Task RestoreBuildAndRunAsync( + Hex1bTerminalAutomator auto, + SequenceCounter counter, + TemporaryWorkspace workspace, + string projectName) + { + var projectRoot = Path.Combine(workspace.WorkspaceRoot.FullName, projectName); + Assert.True(File.Exists(Path.Combine(projectRoot, "apphost.go")), $"Expected apphost.go in {projectRoot}"); + Assert.True(File.Exists(Path.Combine(projectRoot, "go.mod")), $"Expected go.mod in {projectRoot}"); + + await auto.RunCommandAsync($"cd {projectName}", counter); + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + + // 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.AspireStartAsync(counter, startTimeout: TimeSpan.FromMinutes(3)); + await auto.AspireStopAsync(counter); + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoKubernetesDeployTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoKubernetesDeployTests.cs new file mode 100644 index 00000000000..75790a88ef3 --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoKubernetesDeployTests.cs @@ -0,0 +1,134 @@ +// 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 Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +/// +/// E2E test for aspire deploy to Kubernetes with a Go AppHost created from the starter template. +/// Creates a Go API + Redis project, adds Kubernetes support, and deploys to a KinD cluster. +/// +public sealed class GoKubernetesDeployTests(ITestOutputHelper output) +{ + private const string ProjectName = "K8sGoTest"; + + [Fact] + [CaptureWorkspaceOnFailure] + public async Task DeployGoAppToKubernetes() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + var clusterName = KubernetesDeployTestHelpers.GenerateUniqueClusterName(); + const string k8sNamespace = "default"; + + output.WriteLine($"Cluster name: {clusterName}"); + output.WriteLine($"Namespace: {k8sNamespace}"); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, mountDockerSocket: true, workspace: workspace); + 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); + + await auto.VerifyPullRequestCliVersionAsync(counter); + await auto.EnableExperimentalGoSupportAsync(counter); + + try + { + // ===================================================================== + // Phase 1: Install KinD + Helm, create cluster with local registry + // ===================================================================== + + await auto.InstallKindAndHelmAsync(counter); + await auto.CreateKindClusterWithRegistryAsync(counter, clusterName); + + // ===================================================================== + // Phase 2: Create Go project from template + // ===================================================================== + + await auto.AspireNewAsync(ProjectName, counter, template: AspireTemplate.GoStarter); + + await auto.TypeAsync($"cd {ProjectName}"); + await auto.EnterAsync(); + await auto.WaitForSuccessPromptAsync(counter); + + // Add Kubernetes hosting package + await auto.AspireAddPackageAsync("Aspire.Hosting.Kubernetes", counter); + + // Regenerate the Go SDK with Kubernetes types + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + + // The starter ships api/go.mod without a go.sum, and its "go mod tidy" resource only runs + // under "aspire run". The generated Dockerfile builds from go.mod and go.sum alone, so + // the container build needs the go.sum that "go mod tidy" writes. + await auto.RunCommandAsync("(cd api && go mod tidy)", counter, TimeSpan.FromMinutes(3)); + + // ===================================================================== + // Phase 3: Modify apphost.go to add Kubernetes environment + // ===================================================================== + + var appHostFilePath = Path.Combine(workspace.WorkspaceRoot.FullName, ProjectName, "apphost.go"); + + output.WriteLine($"Looking for apphost.go at: {appHostFilePath}"); + + // The AppHost passes no WithHelm callback: a Configure func inside the generated Go options + // struct panics the options merge (https://github.com/microsoft/aspire/issues/18080), so the + // Helm defaults apply (namespace "default", chart version 0.1.0). + GoAppHostTestHelpers.InsertBeforeBuild( + appHostFilePath, + """ + // Add container registry for image push + registryEndpoint := builder.AddParameter("registryendpoint") + builder.AddContainerRegistry("registry", registryEndpoint) + + // Add Kubernetes environment (Helm is the default deployment engine) + builder.AddKubernetesEnvironment("env") + """); + output.WriteLine("Modified apphost.go with Kubernetes environment configuration"); + + // ===================================================================== + // Phase 4: Run aspire deploy interactively + // ===================================================================== + + await auto.AspireDeployInteractiveAsync( + counter, + parameterResponses: + [ + ("registryendpoint", "localhost:5001"), + ]); + + // ===================================================================== + // Phase 5: Verify the deployment + // ===================================================================== + + // The publisher labels each workload and its pods with app.kubernetes.io/component=. + // Selecting by that label makes a chart without the workload fail the test: "kubectl wait" exits 1 with + // "no matching resources found" when nothing matches, whereas "kubectl get pods" succeeds on an empty + // namespace and Helm's --wait only waits for workloads that are in the chart. + foreach (var resourceName in new[] { "api", "cache" }) + { + await auto.RunCommandAsync( + $"kubectl wait --for=condition=Ready pod -n {k8sNamespace} -l app.kubernetes.io/component={resourceName} --timeout=180s", + counter, + TimeSpan.FromMinutes(4)); + } + + // ===================================================================== + // Phase 6: Cleanup + // ===================================================================== + + await auto.CleanupKubernetesDeploymentAsync(counter, clusterName); + } + finally + { + await KubernetesDeployTestHelpers.CleanupKindClusterOutOfBandAsync(clusterName, output); + } + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoPolyglotApphostDirectoryTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoPolyglotApphostDirectoryTests.cs new file mode 100644 index 00000000000..2127e0253e8 --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoPolyglotApphostDirectoryTests.cs @@ -0,0 +1,63 @@ +// 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.Resources; +using Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +/// +/// Polyglot (non-.NET) AppHosts run under a generic host process, so the Go SDK forwards the +/// AppHost path and project directory the CLI provides (ASPIRE_APPHOST_FILEPATH and +/// ASPIRE_PROJECT_DIRECTORY) when it creates the builder. Without them the running AppHost +/// would report the wrong path and aspire <cmd> --apphost <directory> could not +/// match it. This test starts a Go AppHost in the background and then issues +/// aspire stop --non-interactive --apphost <directory> from an unrelated cwd so the stop +/// command is forced to resolve the AppHost via the path the host reported over the backchannel. +/// Each test class runs as a separate CI job for parallelization. +/// +public sealed class GoPolyglotApphostDirectoryTests(ITestOutputHelper output) +{ + [Fact] + [CaptureWorkspaceOnFailure] + public async Task StopGoPolyglotAppHostUsingApphostDirectory() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, mountDockerSocket: true, workspace: workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + // Put the AppHost in a subdirectory so we can `cd ..` away from it and then resolve it + // back via `--apphost goapp`. That forces AppHost discovery through the path the running + // host reported over the backchannel rather than through the current working directory. + await auto.RunCommandAsync("mkdir goapp && cd goapp", counter); + await auto.AspireInitGoAppHostAsync(counter); + + // Start the AppHost in the background (returns to the prompt once the AppHost reports it + // has started over the backchannel). The scaffolded AppHost has no resources, which is + // all this scenario needs. + await auto.TypeAsync("aspire start"); + await auto.EnterAsync(); + await auto.WaitUntilTextAsync(RunCommandStrings.AppHostStartedSuccessfully, timeout: TimeSpan.FromMinutes(3)); + await auto.WaitForSuccessPromptAsync(counter); + + await auto.ClearScreenAsync(counter); + + await auto.RunCommandAsync("cd ..", counter); + + await auto.TypeAsync("aspire stop --non-interactive --apphost goapp"); + await auto.EnterAsync(); + await auto.WaitUntilAppHostStoppedSuccessfullyAsync(timeout: TimeSpan.FromMinutes(1)); + await auto.WaitForSuccessPromptAsync(counter); + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoPublishTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoPublishTests.cs new file mode 100644 index 00000000000..4c1647897e1 --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoPublishTests.cs @@ -0,0 +1,152 @@ +// 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 Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +/// +/// End-to-end tests for Aspire CLI publish flows with a Go AppHost. +/// +public sealed class GoPublishTests(ITestOutputHelper output) +{ + [Fact] + [CaptureWorkspaceOnFailure] + public async Task PublishWithDockerComposeServiceCallbackSucceeds() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, mountDockerSocket: true, workspace: workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + await auto.AspireInitGoAppHostAsync(counter); + await auto.AspireAddPackageAsync("Aspire.Hosting.Docker", counter); + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + + WriteDockerComposeContainerAppHost(workspace); + + await auto.RunCommandAsync("unset ASPIRE_PLAYGROUND", counter); + await auto.RunCommandAsync("aspire publish -o artifacts --non-interactive", counter, TimeSpan.FromMinutes(5)); + + await auto.RunCommandAsync("ls -la artifacts/docker-compose.yaml", counter); + await auto.RunCommandAsync("grep -F \"api:\" artifacts/docker-compose.yaml", counter); + await auto.RunCommandAsync("grep -F \"validation-api\" artifacts/docker-compose.yaml", counter); + } + + [Fact] + [CaptureWorkspaceOnFailure] + public async Task PublishWithoutOutputPathUsesAppHostDirectoryDefault() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, mountDockerSocket: true, workspace: workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + await auto.AspireInitGoAppHostAsync(counter); + await auto.AspireAddPackageAsync("Aspire.Hosting.Docker", counter); + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + + WriteDockerComposeContainerAppHost(workspace); + + await auto.RunCommandAsync("unset ASPIRE_PLAYGROUND", counter); + await auto.RunCommandAsync("aspire publish --non-interactive", counter, TimeSpan.FromMinutes(5)); + + var dockerComposePath = Path.Combine(workspace.WorkspaceRoot.FullName, "aspire-output", "docker-compose.yaml"); + Assert.True(File.Exists(dockerComposePath), $"Expected docker-compose output at {dockerComposePath}"); + + var dockerComposeContent = await File.ReadAllTextAsync(dockerComposePath); + Assert.Contains("api:", dockerComposeContent); + } + + [Fact] + [CaptureWorkspaceOnFailure] + public async Task PublishGoStarterGeneratesGoAppDockerfile() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, mountDockerSocket: true, workspace: workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + const string projectName = "GoPublishApp"; + await auto.AspireNewAsync(projectName, counter, template: AspireTemplate.GoStarter); + await auto.RunCommandAsync($"cd {projectName}", counter); + await auto.AspireAddPackageAsync("Aspire.Hosting.Docker", counter); + await auto.RunCommandAsync("aspire restore --non-interactive", counter, TimeSpan.FromMinutes(3)); + + // The starter has no compute environment; the Go API and the Redis cache both target this one. + GoAppHostTestHelpers.InsertBeforeBuild( + Path.Combine(workspace.WorkspaceRoot.FullName, projectName, "apphost.go"), + "builder.AddDockerComposeEnvironment(\"compose\")"); + + await auto.RunCommandAsync("unset ASPIRE_PLAYGROUND", counter); + await auto.RunCommandAsync("aspire publish -o artifacts --non-interactive", counter, TimeSpan.FromMinutes(5)); + + var artifactsPath = Path.Combine(workspace.WorkspaceRoot.FullName, projectName, "artifacts"); + var composeContent = await File.ReadAllTextAsync(Path.Combine(artifactsPath, "docker-compose.yaml")); + + Assert.Contains("api:", composeContent); + Assert.Contains("cache:", composeContent); + + // The Go version in the FROM line comes from api/go.mod, so only the stable parts are asserted. + AssertDockerfileContains( + artifactsPath, + "api", + "FROM golang:", + " AS build", + "USER app", + "ENTRYPOINT [\"/app/api\"]"); + } + + private static void WriteDockerComposeContainerAppHost(TemporaryWorkspace workspace) + { + GoAppHostTestHelpers.InsertBeforeBuild( + Path.Combine(workspace.WorkspaceRoot.FullName, "apphost.go"), + """ + compose := builder.AddDockerComposeEnvironment("compose") + api := builder.AddContainer("api", "nginx:alpine") + api.WithComputeEnvironment(compose) + _ = api.PublishAsDockerComposeService(func(composeService aspire.DockerComposeServiceResource, service aspire.Service) { + service.SetContainerName(aspire.StringPtr("validation-api")) + }) + """); + } + + private static void AssertDockerfileContains(string artifactsPath, string resourceName, params string[] expectedFragments) + { + var dockerfilePath = Path.Combine(artifactsPath, $"{resourceName}.Dockerfile"); + Assert.True(File.Exists(dockerfilePath), $"Expected Dockerfile for resource '{resourceName}' at {dockerfilePath}"); + + var content = File.ReadAllText(dockerfilePath); + + foreach (var expectedFragment in expectedFragments) + { + Assert.Contains(expectedFragment, content); + } + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoSecretAppHostTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoSecretAppHostTests.cs new file mode 100644 index 00000000000..1bde93dd3c9 --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoSecretAppHostTests.cs @@ -0,0 +1,81 @@ +// 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; +using Aspire.Cli.EndToEnd.Tests.Helpers; +using Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +/// +/// Tests aspire secret CRUD operations on a Go (polyglot) AppHost. +/// +public sealed class GoSecretAppHostTests(ITestOutputHelper output) +{ + [Fact] + [CaptureWorkspaceOnFailure] + public async Task SecretCrudOnGoAppHost() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal(repoRoot, strategy, output, variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, mountDockerSocket: true, workspace: workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + // Create the Go AppHost via aspire init + await auto.AspireInitGoAppHostAsync(counter); + + // Set secrets using --apphost + await auto.TypeAsync("aspire secret set MyConfig:ApiKey test-key-123 --apphost apphost.go"); + await auto.EnterAsync(); + await auto.WaitUntilTextAsync("set successfully", timeout: TimeSpan.FromSeconds(30)); + await auto.WaitForSuccessPromptAsync(counter); + + await auto.TypeAsync("aspire secret set ConnectionStrings:Db Server=localhost --apphost apphost.go"); + await auto.EnterAsync(); + await auto.WaitUntilTextAsync("set successfully", timeout: TimeSpan.FromSeconds(30)); + await auto.WaitForSuccessPromptAsync(counter); + + // Get and list are checked with grep because the secret keys and values also appear in the earlier + // `secret set` command lines that are still on screen, so waiting for that text would pass without + // any output. The numbered prompt reports grep's exit status, which is what validates the output. + await auto.RunCommandAsync("aspire secret get MyConfig:ApiKey --apphost apphost.go | grep -qx 'test-key-123'", counter, TimeSpan.FromSeconds(30)); + await auto.RunCommandAsync("aspire secret list --apphost apphost.go | grep 'ConnectionStrings:Db' | grep 'Server=localhost' >/dev/null", counter, TimeSpan.FromSeconds(30)); + + // Delete + await auto.TypeAsync("aspire secret delete MyConfig:ApiKey --apphost apphost.go"); + await auto.EnterAsync(); + await auto.WaitUntilTextAsync("deleted successfully", timeout: TimeSpan.FromSeconds(30)); + await auto.WaitForSuccessPromptAsync(counter); + + // Verify deletion: waiting for screen text can only prove a secret is present, so list as JSON + // (keyed by secret name) and assert the whole collection. + await auto.RunCommandAsync("aspire secret list --apphost apphost.go --format json > listed-secrets.json", counter, TimeSpan.FromSeconds(30)); + var listedSecrets = JsonSerializer.Deserialize>( + await File.ReadAllTextAsync(Path.Combine(workspace.WorkspaceRoot.FullName, "listed-secrets.json"), TestContext.Current.CancellationToken)); + Assert.Equal(new Dictionary { ["ConnectionStrings:Db"] = "Server=localhost" }, listedSecrets); + + await auto.TypeAsync("aspire secret set MyConfig:ApiKey staging-go-secret --environment Staging --apphost apphost.go"); + await auto.EnterAsync(); + await auto.WaitUntilTextAsync("set successfully", timeout: TimeSpan.FromSeconds(30)); + await auto.WaitForSuccessPromptAsync(counter); + + await auto.TypeAsync("aspire secret set MyConfig:ApiKey production-go-secret --environment Production --apphost apphost.go"); + await auto.EnterAsync(); + await auto.WaitUntilTextAsync("set successfully", timeout: TimeSpan.FromSeconds(30)); + await auto.WaitForSuccessPromptAsync(counter); + + await auto.RunCommandAsync("aspire secret get MyConfig:ApiKey --environment Staging --apphost apphost.go | grep -qx 'staging-go-secret'", counter, TimeSpan.FromSeconds(30)); + await auto.RunCommandAsync("aspire secret get MyConfig:ApiKey --environment Production --apphost apphost.go | grep -qx 'production-go-secret'", counter, TimeSpan.FromSeconds(30)); + await auto.RunCommandAsync("aspire secret list --all --apphost apphost.go | grep 'staging-go-secret' | grep 'Staging' >/dev/null", counter, TimeSpan.FromSeconds(30)); + await auto.RunCommandAsync("aspire secret list --all --apphost apphost.go | grep 'production-go-secret' | grep 'Production' >/dev/null", counter, TimeSpan.FromSeconds(30)); + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/GoStarterTemplateTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/GoStarterTemplateTests.cs new file mode 100644 index 00000000000..1b2917fac77 --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/GoStarterTemplateTests.cs @@ -0,0 +1,59 @@ +// 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 Hex1b.Automation; +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests; + +/// +/// End-to-end tests for the Go starter template (aspire-go-starter). +/// Validates that aspire new creates a Go API + Redis project with a restored Go SDK +/// and that aspire start runs it successfully. +/// +public sealed class GoStarterTemplateTests(ITestOutputHelper output) +{ + [CaptureWorkspaceOnFailure] + [Fact] + public async Task CreateAndRunGoStarterProject() + { + var repoRoot = CliE2ETestHelpers.GetRepoRoot(); + var strategy = CliInstallStrategy.Detect(output.WriteLine); + using var workspace = TemporaryWorkspace.Create(output); + + using var terminal = CliE2ETestHelpers.CreateDockerTestTerminal( + repoRoot, + strategy, + output, + variant: CliE2ETestHelpers.DockerfileVariant.PolyglotGo, + mountDockerSocket: true, + workspace: workspace); + 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); + await auto.EnableExperimentalGoSupportAsync(counter); + + await auto.AspireNewAsync("GoStarterApp", counter, template: AspireTemplate.GoStarter); + + // The starter template restores the generated Go SDK as part of aspire new. + var projectRoot = Path.Combine(workspace.WorkspaceRoot.FullName, "GoStarterApp"); + var aspireModulePath = Path.Combine(projectRoot, ".aspire", "modules", "aspire.go"); + Assert.True(File.Exists(aspireModulePath), $"Expected generated Go SDK file not found: {aspireModulePath}"); + + await auto.TypeAsync("cd GoStarterApp"); + await auto.EnterAsync(); + await auto.WaitForSuccessPromptAsync(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)); + + // 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); + } +} diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs index 5422638f590..7a0a3c40fb4 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2EAutomatorHelpers.cs @@ -275,6 +275,37 @@ await auto.WaitForAspireNewEmptyAppHostCompletionAsync( effectiveTimeout); } + /// + /// Creates a Go empty AppHost using the direct aspire new aspire-go-empty command. + /// Requires to have run first. + /// + internal static async Task AspireNewGoEmptyAppHostAsync( + this Hex1bTerminalAutomator auto, + string projectName, + SequenceCounter counter, + string? outputPath = null, + string? channel = null, + bool useLocalhostTld = false, + TimeSpan? timeout = null) + { + var effectiveTimeout = timeout ?? TimeSpan.FromMinutes(2); + var command = BuildAspireNewEmptyAppHostCommand( + "aspire-go-empty", + projectName, + outputPath, + channel, + useLocalhostTld); + + await auto.TypeAsync(command); + await auto.EnterAsync(); + await auto.WaitForAspireNewEmptyAppHostCompletionAsync( + projectName, + "Go", + counter, + AppHostLanguagePromptSelection.Go, + effectiveTimeout); + } + private static string BuildAspireNewEmptyAppHostCommand( string templateName, string projectName, @@ -386,6 +417,16 @@ await auto.WaitUntilAsync( await auto.EnterAsync(); return; + case AppHostLanguagePromptSelection.Go: + // Search by text so the selection does not depend on which other languages the picker lists. + await auto.TypeAsync("Go"); + await auto.WaitUntilAsync( + s => new CellPatternSearcher().Find("> Go").Search(s).Count > 0, + timeout: TimeSpan.FromSeconds(5), + description: "Go AppHost language selected"); + await auto.EnterAsync(); + return; + default: throw new InvalidOperationException($"Unexpected AppHost language prompt selection: {languagePromptSelection}."); } @@ -429,6 +470,19 @@ await auto.WaitUntilAsync(snapshot => counter.Increment(); } + /// + /// Runs aspire add <packageName> and waits for it to finish, answering the version picker when it appears. + /// + internal static async Task AspireAddPackageAsync( + this Hex1bTerminalAutomator auto, + string packageName, + SequenceCounter counter) + { + await auto.TypeAsync($"aspire add {packageName}"); + await auto.EnterAsync(); + await auto.WaitForAspireAddSuccessAsync(counter, TimeSpan.FromMinutes(2)); + } + /// /// Installs the Aspire CLI in a non-Docker shell using the given install strategy. /// @@ -748,6 +802,39 @@ internal static async Task EnableExperimentalJavaSupportAsync( await auto.WaitForSuccessPromptAsync(counter); } + /// + /// Enables experimental Go polyglot support for CLI tests. + /// + /// + /// Go AppHosts are gated behind the experimentalPolyglotGo feature, which hides both the Go starter template + /// and the Go entry in the language picker. Every Go test goes through this helper so that dropping the gate only + /// requires turning this method into a no-op like . + /// + internal static async Task EnableExperimentalGoSupportAsync( + this Hex1bTerminalAutomator auto, + SequenceCounter counter) + { + await auto.TypeAsync("aspire config set features:experimentalPolyglotGo true --global --non-interactive"); + await auto.EnterAsync(); + await auto.WaitForSuccessPromptAsync(counter); + } + + /// + /// Creates a Go AppHost in the current directory through the interactive aspire init language picker. + /// Requires to have run first. + /// + internal static async Task AspireInitGoAppHostAsync( + this Hex1bTerminalAutomator auto, + SequenceCounter counter) + { + await auto.TypeAsync("aspire init"); + await auto.EnterAsync(); + await auto.WaitUntilTextAsync("Which language would you like to use?", timeout: TimeSpan.FromSeconds(30)); + await auto.SelectAppHostLanguageAsync(AppHostLanguagePromptSelection.Go); + await auto.WaitUntilTextAsync("Created apphost.go", timeout: TimeSpan.FromMinutes(2)); + await auto.DeclineAgentInitPromptAsync(counter); + } + /// /// Installs a specific GA version of the Aspire CLI using the install script. /// @@ -1239,6 +1326,7 @@ private enum AspireNewEmptyAppHostResult private enum AppHostLanguagePromptSelection { DefaultCSharp, - TypeScript + TypeScript, + Go } } diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2ETestHelpers.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2ETestHelpers.cs index 70d0cbe91a1..f902a0acf94 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2ETestHelpers.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliE2ETestHelpers.cs @@ -25,6 +25,8 @@ internal static class CliE2ETestHelpers internal const string RequirePolyglotImageEnvironmentVariableName = "ASPIRE_E2E_REQUIRE_POLYGLOT_IMAGE"; internal const string PolyglotJavaImageEnvironmentVariableName = "ASPIRE_E2E_POLYGLOT_JAVA_IMAGE"; internal const string RequirePolyglotJavaImageEnvironmentVariableName = "ASPIRE_E2E_REQUIRE_POLYGLOT_JAVA_IMAGE"; + internal const string PolyglotGoImageEnvironmentVariableName = "ASPIRE_E2E_POLYGLOT_GO_IMAGE"; + internal const string RequirePolyglotGoImageEnvironmentVariableName = "ASPIRE_E2E_REQUIRE_POLYGLOT_GO_IMAGE"; internal const string CliVersionOutputDirEnvironmentVariableName = "ASPIRE_E2E_CLI_VERSION_OUTPUT_DIR"; internal const string ContainerCliVersionOutputDir = "/tmp/aspire-cli-versions"; private static readonly Regex s_commitShaPattern = new("^[0-9a-fA-F]{40}$", RegexOptions.Compiled); @@ -192,6 +194,11 @@ internal enum DockerfileVariant /// Docker + Node.js + Java (no .NET SDK). For Java polyglot AppHost tests. /// PolyglotJava, + + /// + /// Docker + Node.js + Go (no .NET SDK). For Go polyglot AppHost tests. + /// + PolyglotGo, } private const string PolyglotBaseImageName = "aspire-e2e-polyglot-base"; @@ -231,7 +238,8 @@ internal static Hex1bTerminal CreateDockerTestTerminal( var dockerfilePath = GetDockerfilePath(repoRoot, variant); var prebuiltImageName = GetPrebuiltImageName(variant); - if (variant is DockerfileVariant.PolyglotJava && prebuiltImageName is null) + // The Java and Go variants extend the shared polyglot base image, which must exist locally before their Dockerfiles build. + if (variant is (DockerfileVariant.PolyglotJava or DockerfileVariant.PolyglotGo) && prebuiltImageName is null) { EnsurePolyglotBaseImage(repoRoot, output); } @@ -333,6 +341,11 @@ internal static void ConfigureDockerContainerSource(DockerContainerOptions optio throw new InvalidOperationException($"{PolyglotJavaImageEnvironmentVariableName} must be set when the prebuilt CLI E2E Java image is required."); } + if (variant is DockerfileVariant.PolyglotGo && IsPolyglotGoImageRequired()) + { + throw new InvalidOperationException($"{PolyglotGoImageEnvironmentVariableName} must be set when the prebuilt CLI E2E Go image is required."); + } + options.DockerfilePath = GetDockerfilePath(repoRoot, variant); options.BuildContext = repoRoot; } @@ -344,6 +357,7 @@ internal static void ConfigureDockerContainerSource(DockerContainerOptions optio DockerfileVariant.DotNet => DotNetImageEnvironmentVariableName, DockerfileVariant.Polyglot => PolyglotImageEnvironmentVariableName, DockerfileVariant.PolyglotJava => PolyglotJavaImageEnvironmentVariableName, + DockerfileVariant.PolyglotGo => PolyglotGoImageEnvironmentVariableName, _ => throw new ArgumentOutOfRangeException(nameof(variant)), }; @@ -358,6 +372,7 @@ private static string GetDockerfilePath(string repoRoot, DockerfileVariant varia DockerfileVariant.DotNet => "Dockerfile.e2e", DockerfileVariant.Polyglot => "Dockerfile.e2e-polyglot-base", DockerfileVariant.PolyglotJava => "Dockerfile.e2e-polyglot-java", + DockerfileVariant.PolyglotGo => "Dockerfile.e2e-polyglot-go", _ => throw new ArgumentOutOfRangeException(nameof(variant)), }; @@ -379,6 +394,11 @@ private static bool IsPolyglotJavaImageRequired() return IsImageRequired(RequirePolyglotJavaImageEnvironmentVariableName); } + private static bool IsPolyglotGoImageRequired() + { + return IsImageRequired(RequirePolyglotGoImageEnvironmentVariableName); + } + private static bool IsImageRequired(string environmentVariableName) { var value = Environment.GetEnvironmentVariable(environmentVariableName); diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs index 945726b8fea..cd5a15ee623 100644 --- a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/CliInstallStrategyTests.cs @@ -356,6 +356,67 @@ public void ConfigureDockerContainerSource_IgnoresPolyglotJavaImageForPolyglotVa Assert.Equal("/repo", options.BuildContext); } + [Fact] + public void ConfigureDockerContainerSource_UsesPolyglotGoImageWhenEnvironmentVariableIsSet() + { + using var environment = WithCleanCliE2ETestEnvironment( + (CliE2ETestHelpers.PolyglotGoImageEnvironmentVariableName, "aspire-cli-e2e-polyglot-go:prebuilt"), + (CliE2ETestHelpers.RequirePolyglotGoImageEnvironmentVariableName, "true"), + ("GITHUB_ACTIONS", "true")); + var options = new DockerContainerOptions(); + + CliE2ETestHelpers.ConfigureDockerContainerSource(options, "/repo", CliE2ETestHelpers.DockerfileVariant.PolyglotGo); + + Assert.Equal("aspire-cli-e2e-polyglot-go:prebuilt", options.Image); + Assert.True(string.IsNullOrEmpty(options.DockerfilePath)); + Assert.True(string.IsNullOrEmpty(options.BuildContext)); + } + + [Fact] + public void ConfigureDockerContainerSource_RequiresPolyglotGoImageWhenConfigured() + { + using var environment = WithCleanCliE2ETestEnvironment( + (CliE2ETestHelpers.PolyglotGoImageEnvironmentVariableName, null), + (CliE2ETestHelpers.RequirePolyglotGoImageEnvironmentVariableName, "true"), + ("GITHUB_ACTIONS", "true")); + var options = new DockerContainerOptions(); + + var exception = Assert.Throws(() => + CliE2ETestHelpers.ConfigureDockerContainerSource(options, "/repo", CliE2ETestHelpers.DockerfileVariant.PolyglotGo)); + + Assert.Contains(CliE2ETestHelpers.PolyglotGoImageEnvironmentVariableName, exception.Message); + } + + [Fact] + public void ConfigureDockerContainerSource_FallsBackToPolyglotGoDockerfileWhenImageIsNotRequired() + { + using var environment = WithCleanCliE2ETestEnvironment( + (CliE2ETestHelpers.PolyglotGoImageEnvironmentVariableName, null), + (CliE2ETestHelpers.RequirePolyglotGoImageEnvironmentVariableName, null), + ("GITHUB_ACTIONS", null)); + var options = new DockerContainerOptions(); + + CliE2ETestHelpers.ConfigureDockerContainerSource(options, "/repo", CliE2ETestHelpers.DockerfileVariant.PolyglotGo); + + Assert.Equal(Path.Combine("/repo", "tests", "Shared", "Docker", "Dockerfile.e2e-polyglot-go"), options.DockerfilePath); + Assert.Equal("/repo", options.BuildContext); + } + + [Fact] + public void ConfigureDockerContainerSource_IgnoresPolyglotGoImageForPolyglotJavaVariant() + { + using var environment = WithCleanCliE2ETestEnvironment( + (CliE2ETestHelpers.PolyglotGoImageEnvironmentVariableName, "aspire-cli-e2e-polyglot-go:prebuilt"), + (CliE2ETestHelpers.RequirePolyglotGoImageEnvironmentVariableName, "true"), + ("GITHUB_ACTIONS", null)); + var options = new DockerContainerOptions(); + + CliE2ETestHelpers.ConfigureDockerContainerSource(options, "/repo", CliE2ETestHelpers.DockerfileVariant.PolyglotJava); + + Assert.Equal(Path.Combine("/repo", "tests", "Shared", "Docker", "Dockerfile.e2e-polyglot-java"), options.DockerfilePath); + Assert.Equal("/repo", options.BuildContext); + } + [Fact] public void ConfigureDockerContainerSource_FallsBackToDockerfileOutsideCI() { @@ -1045,6 +1106,8 @@ private static EnvironmentVariableScope WithCleanCliE2ETestEnvironment(params (s (CliE2ETestHelpers.RequirePolyglotImageEnvironmentVariableName, null), (CliE2ETestHelpers.PolyglotJavaImageEnvironmentVariableName, null), (CliE2ETestHelpers.RequirePolyglotJavaImageEnvironmentVariableName, null), + (CliE2ETestHelpers.PolyglotGoImageEnvironmentVariableName, null), + (CliE2ETestHelpers.RequirePolyglotGoImageEnvironmentVariableName, null), ("GITHUB_ACTIONS", null), ]; diff --git a/tests/Aspire.Cli.EndToEnd.Tests/Helpers/GoAppHostTestHelpers.cs b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/GoAppHostTestHelpers.cs new file mode 100644 index 00000000000..d09e25d4fbe --- /dev/null +++ b/tests/Aspire.Cli.EndToEnd.Tests/Helpers/GoAppHostTestHelpers.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace Aspire.Cli.EndToEnd.Tests.Helpers; + +/// +/// Edits the apphost.go generated by aspire init and the Go starter template. +/// +internal static class GoAppHostTestHelpers +{ + // Both templates build the AppHost on this tab-indented line, after the resources are declared. + private const string BuildCall = "\tapp, err := builder.Build()"; + + /// + /// Inserts Go statements right before the AppHost is built. Builder calls record their errors on the + /// builder instead of returning them, so any failure in the inserted statements is reported by the + /// template's own error handling around Build(). Go ignores indentation, so the statements + /// can be written unindented. + /// + internal static void InsertBeforeBuild(string appHostPath, string statements) + { + var content = File.ReadAllText(appHostPath); + Assert.True(content.Contains(BuildCall, StringComparison.Ordinal), $"Expected '{BuildCall.Trim()}' in {appHostPath}"); + + File.WriteAllText(appHostPath, content.Replace(BuildCall, $"{statements}\n\n{BuildCall}", StringComparison.Ordinal)); + } +} diff --git a/tests/Infrastructure.Tests/TestTriggerMap/SelectTestsAcceptanceTests.cs b/tests/Infrastructure.Tests/TestTriggerMap/SelectTestsAcceptanceTests.cs index e5ca63e5f53..dcc231a0ecc 100644 --- a/tests/Infrastructure.Tests/TestTriggerMap/SelectTestsAcceptanceTests.cs +++ b/tests/Infrastructure.Tests/TestTriggerMap/SelectTestsAcceptanceTests.cs @@ -1010,6 +1010,8 @@ public void RealMapUnrelatedHostingProjectDoesNotSelectExtensionOrCliE2e() [Theory] [InlineData("Aspire.Hosting.Redis")] [InlineData("Aspire.StackExchange.Redis")] + [InlineData("Aspire.Hosting.Go")] + [InlineData("Aspire.Hosting.CodeGeneration.Go")] public void RealMapRepresentativeCliE2eRuntimeConsumerSelectsCliE2e(string project) { var mapPath = Path.Combine(RepoRoot.Path, "eng", "github-ci", "test-trigger-map.yml"); diff --git a/tests/Shared/Docker/Dockerfile.e2e-polyglot-go b/tests/Shared/Docker/Dockerfile.e2e-polyglot-go new file mode 100644 index 00000000000..db0844867ff --- /dev/null +++ b/tests/Shared/Docker/Dockerfile.e2e-polyglot-go @@ -0,0 +1,25 @@ +# Polyglot Dockerfile for Go AppHost E2E tests. +# Extends the shared polyglot base with the Go toolchain required by Go AppHosts. + +# DisableDockerDetector "Extends a locally built aspire-e2e-polyglot-base image; the GitHub image workflow and local CLI E2E helper build it first from the separately scanned Dockerfile.e2e-polyglot-base. The Go toolchain image copied below with COPY --from is registered through .github/workflows/polyglot-validation/Dockerfile.golang." + +FROM aspire-e2e-polyglot-base + +ARG UBUNTU_APT_MIRROR= + +# The Microsoft Go image is Debian bookworm based (glibc 2.36) but the native Aspire CLI needs +# glibc 2.38+, so only the toolchain is copied onto the Ubuntu 24.04 polyglot base. This is the +# same image and version the polyglot-validation Go job uses. +COPY --from=mcr.microsoft.com/oss/go/microsoft/golang:1.26-bookworm /usr/local/go /usr/local/go + +# Microsoft Go's system crypto backend needs the C toolchain and the OpenSSL development files. +# `aspire deploy` builds the app image with `docker buildx`; the polyglot base installs docker.io +# without recommended packages, so the buildx plugin is absent unless it is installed here. +COPY tests/Shared/Docker/configure-ubuntu-apt-mirror.sh /usr/local/bin/ +RUN sh /usr/local/bin/configure-ubuntu-apt-mirror.sh "$UBUNTU_APT_MIRROR" +RUN apt-get update -qq && \ + apt-get install -y --no-install-recommends build-essential pkg-config libssl-dev docker-buildx && \ + rm -rf /var/lib/apt/lists/* + +ENV GOPATH=/go +ENV PATH="/usr/local/go/bin:/go/bin:${PATH}" diff --git a/tests/Shared/Hex1bAutomatorTestHelpers.cs b/tests/Shared/Hex1bAutomatorTestHelpers.cs index cd22a5125fd..fffdb2d1fe5 100644 --- a/tests/Shared/Hex1bAutomatorTestHelpers.cs +++ b/tests/Shared/Hex1bAutomatorTestHelpers.cs @@ -622,6 +622,31 @@ await auto.WaitUntilAsync( await auto.EnterAsync(); break; + case AspireTemplate.GoStarter: + // The list omits the C# starters when the image has no .NET SDK, so search by text instead of counting Downs. + await auto.TypeAsync("Go API"); + await auto.WaitUntilAsync( + s => new CellPatternSearcher().Find("> Starter App (Go API + Redis, Go AppHost)").Search(s).Count > 0, + timeout: TimeSpan.FromSeconds(5), + description: "Go starter template selected"); + await auto.EnterAsync(); + break; + + case AspireTemplate.GoEmptyAppHost: + await auto.TypeAsync("Empty AppHost"); + await auto.EnterAsync(); + await auto.WaitUntilAsync( + s => new CellPatternSearcher().Find("Which language would you like to use?").Search(s).Count > 0, + timeout: TimeSpan.FromSeconds(10), + description: "AppHost language prompt"); + await auto.TypeAsync("Go"); + await auto.WaitUntilAsync( + s => new CellPatternSearcher().Find("> Go").Search(s).Count > 0, + timeout: TimeSpan.FromSeconds(5), + description: "Go AppHost language selected"); + await auto.EnterAsync(); + break; + default: throw new ArgumentOutOfRangeException(nameof(template), template, $"Unsupported template: {template}"); } diff --git a/tests/Shared/Hex1bTestHelpers.cs b/tests/Shared/Hex1bTestHelpers.cs index 3abbc0a848b..9535c451e70 100644 --- a/tests/Shared/Hex1bTestHelpers.cs +++ b/tests/Shared/Hex1bTestHelpers.cs @@ -67,6 +67,18 @@ internal enum AspireTemplate /// Prompts: template, language, project name, output path, URLs. No Redis or test project prompt. /// JavaEmptyAppHost, + + /// + /// Starter App (Go API + Redis, Go AppHost) — visible only when experimental Go support is enabled. + /// Prompts: template, project name, output path, URLs. No Redis or test project prompt because the template always includes Redis. + /// + GoStarter, + + /// + /// Empty (Go AppHost) — visible only in the language picker when experimental Go support is enabled. + /// Prompts: template, language, project name, output path, URLs. No Redis or test project prompt. + /// + GoEmptyAppHost, } /// @@ -441,6 +453,26 @@ internal static Hex1bTerminalInputSequenceBuilder AspireNew( .Type("Java") .Enter(); break; + + case AspireTemplate.GoStarter: + // The list omits the C# starters when the image has no .NET SDK, so search by text instead of counting Downs. + var goStarterSelected = new CellPatternSearcher() + .Find("> Starter App (Go API + Redis, Go AppHost)"); + builder.Type("Go API") + .WaitUntil(s => goStarterSelected.Search(s).Count > 0, TimeSpan.FromSeconds(5)) + .Enter(); + break; + + case AspireTemplate.GoEmptyAppHost: + var goLanguageSelected = new CellPatternSearcher() + .Find("> Go"); + builder.Type("Empty AppHost") + .Enter() + .WaitUntil(s => waitingForAppHostLanguagePrompt.Search(s).Count > 0, TimeSpan.FromSeconds(10)) + .Type("Go") + .WaitUntil(s => goLanguageSelected.Search(s).Count > 0, TimeSpan.FromSeconds(5)) + .Enter(); + break; } // Step 3: Enter project name