// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Aspire.Cli.Agents;
using Aspire.Cli.Backchannel;
using Aspire.Cli.Commands;
using Aspire.Cli.Configuration;
using Aspire.Cli.Git;
using Aspire.Cli.Interaction;
using Aspire.Cli.Projects;
using Aspire.Cli.Resources;
using Aspire.Cli.Tests.Agents;
using Aspire.Cli.Tests.TestServices;
using Aspire.Cli.Tests.Utils;
using Aspire.Shared.Telemetry;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.AspNetCore.InternalTesting;
using Spectre.Console;
namespace Aspire.Cli.Tests.Commands;
public class ConfigSourceCommandTests(ITestOutputHelper outputHelper)
{
private static readonly ConfigSource s_source = new()
{
Repository = "https://git.example/configuration",
Path = "aspire.config.json",
AppliedVersion = "version-1"
};
[Theory]
[InlineData("stop", true, false)]
[InlineData("ps --format json", false, false)]
[InlineData("stop", true, true)]
[InlineData("ps --format json", false, true)]
public async Task CompletedCheck_RealGitDiagnosticsAreDeferredUnlessMachineReadable(string commandLine, bool notify, bool fetch)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var source = new ConfigSource
{
Repository = Path.Combine(workspace.Path, "missing-repository"),
Path = AspireConfigFile.FileName,
Ref = fetch ? TestGitCommandRunner.DefaultCommitSha : null,
AppliedVersion = "version-1"
};
await TestConfigSourceServices.SaveBindingAsync(source, workspace.WorkspaceRoot, TestContext.Current.CancellationToken);
var interaction = new TestInteractionService();
var cliNoticeShown = false;
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
options.GitClientFactory = services => new GitClient(services.GetRequiredService<IGitCommandRunner>());
options.CliUpdateNotifierFactory = _ => new TestCliUpdateNotifier
{
NotifyIfUpdateAvailableCallback = () =>
{
Assert.Empty(interaction.DisplayedRawText);
cliNoticeShown = true;
}
};
}).BuildServiceProvider();
var service = provider.GetRequiredService<ConfigSourceService>();
service.CheckForConfigSourceUpdates(workspace.WorkspaceRoot, TestContext.Current.CancellationToken);
await service.WaitForChecksAsync().DefaultTimeout();
Assert.Empty(interaction.DisplayedMessages);
Assert.Empty(interaction.DisplayedRawText);
await provider.GetRequiredService<RootCommand>().Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(notify, cliNoticeShown);
var failure = string.Format(System.Globalization.CultureInfo.CurrentCulture,
ConfigSourceStrings.CheckFailed, ConfigSourceStrings.RepositoryUnavailable);
Assert.Equal(notify ? 1 : 0, interaction.DisplayedMessages.Count(message => message.Message == failure));
if (notify)
{
var diagnostic = Assert.Single(interaction.DisplayedRawText);
Assert.Equal(ConsoleOutput.Error, diagnostic.ConsoleOverride);
Assert.StartsWith("fatal: ", diagnostic.Text);
Assert.Contains(source.Repository, diagnostic.Text);
service.NotifyIfUpdateAvailable();
Assert.Single(interaction.DisplayedRawText);
}
else
{
Assert.Equal(("[]", (ConsoleOutput?)ConsoleOutput.Standard), Assert.Single(interaction.DisplayedRawText));
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ExplicitAcquisition_AfterBackgroundCheckStillDisplaysGitDiagnosticsImmediately(bool fetch)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var source = new ConfigSource
{
Repository = Path.Combine(workspace.Path, "missing-repository"),
Path = AspireConfigFile.FileName,
Ref = fetch ? TestGitCommandRunner.DefaultCommitSha : null,
AppliedVersion = "version-1"
};
await TestConfigSourceServices.SaveBindingAsync(source, workspace.WorkspaceRoot, TestContext.Current.CancellationToken);
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
options.GitClientFactory = services => new GitClient(services.GetRequiredService<IGitCommandRunner>());
}).BuildServiceProvider();
var service = provider.GetRequiredService<ConfigSourceService>();
service.CheckForConfigSourceUpdates(workspace.WorkspaceRoot, TestContext.Current.CancellationToken);
await service.WaitForChecksAsync().DefaultTimeout();
Assert.Empty(interaction.DisplayedRawText);
var exception = await Assert.ThrowsAsync<ConfigSourceException>(() =>
service.CheckProjectAsync(workspace.WorkspaceRoot, force: true, TestContext.Current.CancellationToken));
Assert.Equal(ConfigSourceStrings.RepositoryUnavailable, exception.Message);
var diagnostic = Assert.Single(interaction.DisplayedRawText);
Assert.Equal(ConsoleOutput.Error, diagnostic.ConsoleOverride);
Assert.StartsWith("fatal: ", diagnostic.Text);
Assert.Contains(source.Repository, diagnostic.Text);
service.NotifyIfUpdateAvailable();
Assert.Equal([diagnostic, diagnostic], interaction.DisplayedRawText);
}
[Theory]
[InlineData("stop", true, false)]
[InlineData("ps --format json", false, false)]
[InlineData("stop", true, true)]
[InlineData("ps --format json", false, true)]
public async Task CompletedCheck_NotifiesAtExitAfterCliUpdateUnlessMachineReadable(string commandLine, bool notify, bool timeout)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var interaction = new TestInteractionService();
var cliNoticeShown = false;
var notifier = new TestCliUpdateNotifier
{
NotifyIfUpdateAvailableCallback = () =>
{
Assert.Equal(0, interaction.DisplayedMessages.Count(message => message.Message == ConfigSourceStrings.UpdateAvailable));
Assert.Empty(interaction.DisplayedRawText);
cliNoticeShown = true;
}
};
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
options.CliUpdateNotifierFactory = _ => notifier;
}).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
var prompt = new string('x', 70 * 1024) + "Enter passphrase: ";
git.InspectConfiguration = (_, _) => timeout
? throw new ConfigSourceException(ConfigSourceStrings.GitTimeout) { GitOutput = prompt }
: Task.FromResult("version-2");
var service = provider.GetRequiredService<ConfigSourceService>();
service.CheckForConfigSourceUpdates(workspace.WorkspaceRoot, CancellationToken.None);
await service.WaitForChecksAsync().DefaultTimeout();
Assert.Empty(interaction.DisplayedMessages);
Assert.Empty(interaction.DisplayedRawText);
await provider.GetRequiredService<RootCommand>().Parse(commandLine).InvokeAsync().DefaultTimeout();
Assert.Equal(notify, cliNoticeShown);
var expectedMessage = timeout
? string.Format(System.Globalization.CultureInfo.CurrentCulture, ConfigSourceStrings.CheckFailed, ConfigSourceStrings.GitTimeout)
: ConfigSourceStrings.UpdateAvailable;
Assert.Equal(notify ? 1 : 0, interaction.DisplayedMessages.Count(message => message.Message == expectedMessage));
if (notify && timeout)
{
Assert.Equal((prompt[^(64 * 1024)..], (ConsoleOutput?)ConsoleOutput.Error), Assert.Single(interaction.DisplayedRawText));
service.NotifyIfUpdateAvailable();
Assert.Single(interaction.DisplayedRawText);
}
else if (!notify)
{
Assert.Equal(("[]", (ConsoleOutput?)ConsoleOutput.Standard), Assert.Single(interaction.DisplayedRawText));
}
else
{
Assert.Empty(interaction.DisplayedRawText);
}
}
[Fact]
public async Task ProjectSelection_DoesNotWaitForAdvisoryCheck()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var projectFile = new FileInfo(Path.Combine(workspace.Path, "apphost.cs"));
await File.WriteAllTextAsync(projectFile.FullName, "#:sdk Aspire.AppHost.Sdk");
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var stopped = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.InspectConfiguration = async (_, token) =>
{
started.SetResult();
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, token);
return "version-2";
}
finally
{
stopped.SetResult();
}
};
var project = await provider.GetRequiredService<IProjectLocator>().UseOrFindAppHostProjectFileAsync(
projectFile, createSettingsFile: false, CancellationToken.None).DefaultTimeout();
await started.Task.DefaultTimeout();
Assert.Equal(projectFile.FullName, project?.FullName);
Assert.False(stopped.Task.IsCompleted);
await provider.GetRequiredService<RootCommand>().Parse("config list").InvokeAsync().DefaultTimeout();
Assert.True(stopped.Task.IsCompletedSuccessfully);
}
[Theory]
[InlineData("copilot", false)]
[InlineData("copilot", true)]
[InlineData("claude", false)]
[InlineData("claude", true)]
[InlineData("opencode", false)]
[InlineData("opencode", true)]
public async Task AgentInit_UsesMaterializedSkillSourcesWithoutAcquisition(string agent, bool localOverride)
{
using var context = new AgentConfigurationTestContext(outputHelper);
var acquired = new TestConfigSourceRepository
{
ReadConfiguration = (_, _) => Task.FromResult(("version-1", JsonNode.Parse("""
{
"skillSources": {
"default": {},
"team": {
"repository": "example/shared",
"openCodeV2Catalog": "https://shared.example/skills/"
}
}
}
""")!.AsObject()))
};
using var sourceService = TestConfigSourceServices.Create(context.ExecutionContext, git: acquired);
await sourceService.MaterializeAsync(s_source, context.Project, CancellationToken.None);
if (localOverride)
{
var path = Path.Combine(context.Project.FullName, AspireConfigFile.FileName);
await ConfigurationService.SetConfigurationInFileAsync(
path, "skillSources.team.repository", "example/local");
await ConfigurationService.SetConfigurationInFileAsync(
path, "skillSources.team.openCodeV2Catalog", "https://local.example/skills/");
}
using var provider = context.CreateServiceCollection(outputHelper).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
var root = provider.GetRequiredService<RootCommand>();
Assert.Equal(0, git.Calls);
var result = root.Parse($"agent init --agents {agent} --scope project --skills aspire --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
var client = agent switch
{
"copilot" => context.Copilot,
"claude" => context.ClaudeCode,
_ => context.OpenCode
};
Assert.Equal(0, git.Calls);
Assert.Equal(0, git.CheckCalls);
await Verify(await File.ReadAllTextAsync(client.GetIntegrationConfigPath(AgentConfigurationScope.Project, context.Project)), "json")
.UseParameters(agent, localOverride);
}
[Theory]
[InlineData("copilot")]
[InlineData("claude")]
[InlineData("opencode")]
public async Task AgentInit_AfterSolutionInit_UsesAppHostSkillSources(string agent)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await File.WriteAllTextAsync(Path.Combine(workspace.Path, "Test.sln"), "Fake solution file");
var services = CreateCreationServices(workspace);
services.AddSingleton(workspace.CreateExecutionContext(identityChannel: "default"));
var cache = new FakeNuGetPackageCache
{
GetTemplatePackagesAsyncCallback = (_, _, _, _) =>
Task.FromResult<IEnumerable<Aspire.Shared.NuGetPackageCli>>(
[new() { Id = "Aspire.ProjectTemplates", Source = "nuget.org", Version = "17.0.0" }])
};
services.AddSingleton<Aspire.Cli.Packaging.IPackagingService>(new TestPackagingService
{
GetChannelsAsyncCallback = _ => Task.FromResult<IEnumerable<Aspire.Cli.Packaging.PackageChannel>>(
[Aspire.Cli.Packaging.PackageChannel.CreateImplicitChannel(cache, new TestFeatures(), NullLogger.Instance)])
});
services.AddSingleton<Aspire.Cli.DotNet.IDotNetCliRunner>(new TestDotNetCliRunner
{
NewProjectAsyncCallback = (_, name, outputPath, _, _) =>
{
Directory.CreateDirectory(outputPath);
File.WriteAllText(Path.Combine(outputPath, $"{name}.csproj"), "<Project />");
File.WriteAllText(Path.Combine(outputPath, AspireConfigFile.FileName), $$"""
{
"appHost": { "path": "{{name}}.csproj" }
}
""");
return 0;
}
});
using (var provider = services.BuildServiceProvider())
{
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) => Task.FromResult(("version-1", JsonNode.Parse("""
{
"skillSources": {
"default": { "enabled": false },
"team": {
"repository": "example/team",
"plugins": ["deployment"],
"openCodeV2Catalog": "https://team.example/skills/"
}
}
}
""")!.AsObject()));
var result = provider.GetRequiredService<RootCommand>().Parse(
"init --language csharp --suppress-agent-init --use-config-source true --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(1, git.Calls);
}
Assert.False(File.Exists(Path.Combine(workspace.Path, AspireConfigFile.FileName)));
var appHostConfigPath = Path.Combine(workspace.Path, "Test.AppHost", AspireConfigFile.FileName);
var appHostConfiguration = await File.ReadAllTextAsync(appHostConfigPath);
var agentServices = CreateCreationServices(workspace);
agentServices.AddSingleton<IAppHostProjectFactory>(new TestAppHostProjectFactory());
using var agentProvider = agentServices.BuildServiceProvider();
var agentGit = Assert.IsType<TestConfigSourceRepository>(agentProvider.GetRequiredService<IGitClient>());
var agentResult = agentProvider.GetRequiredService<RootCommand>().Parse(
$"agent init --workspace-root \"{workspace.Path}\" --agents {agent} --scope project --skills aspire --non-interactive");
Assert.Equal(CliExitCodes.Success, await agentResult.InvokeAsync().DefaultTimeout());
var path = agentProvider.GetServices<IAgentClient>().Single(client => client.Id == agent)
.GetIntegrationConfigPath(AgentConfigurationScope.Project, workspace.WorkspaceRoot);
await Verify(await File.ReadAllTextAsync(path), "json").UseParameters(agent);
Assert.Equal(appHostConfiguration, await File.ReadAllTextAsync(appHostConfigPath));
Assert.False(File.Exists(Path.Combine(workspace.Path, AspireConfigFile.FileName)));
Assert.Equal(0, agentGit.Calls);
Assert.Equal(0, agentGit.CheckCalls);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UpdateConfigSource_DisplaysSavedSourceWithoutExplanation(bool customSelection)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var source = new ConfigSource
{
Repository = "https://git.example/saved-configuration",
Path = customSelection ? "teams/platform.json" : AspireConfigFile.FileName,
Ref = customSelection ? "team/configuration" : null,
AppliedVersion = "version-1"
};
await TestConfigSourceServices.SaveBindingAsync(source, workspace.WorkspaceRoot, CancellationToken.None);
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) =>
{
Assert.Single(interaction.DisplayedRenderables);
return Task.FromResult(("version-1", new JsonObject()));
};
var exitCode = await provider.GetRequiredService<RootCommand>()
.Parse("update --config-source --yes --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equal(
[
$"[yellow]{SharedCommandStrings.SourceTrustWarning}[/]",
$"[blue]{string.Format(CultureInfo.CurrentCulture, SharedCommandStrings.FetchingSource,
SharedCommandStrings.GitFetchConfigurationSource, source.Repository)}[/]",
ConfigSourceStrings.AlreadyUpToDate
],
interaction.DisplayedMessages.Select(message => message.Message));
using var writer = new StringWriter(CultureInfo.InvariantCulture);
var console = AnsiConsole.Create(new AnsiConsoleSettings { Out = new AnsiConsoleOutput(writer), Ansi = AnsiSupport.No });
console.Profile.Capabilities.Ansi = false;
console.Profile.Width = 160;
console.Write(Assert.Single(interaction.DisplayedRenderables));
await Verify(writer.ToString()).UseParameters(customSelection).ScrubLinesWithReplace(line => line.TrimEnd());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UpdateConfigSource_RefreshesFreshCacheWithoutUpdatingPackages(bool changed)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var interaction = new TestInteractionService();
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
options.PackagingServiceFactory = _ => new TestPackagingService
{
GetChannelsAsyncCallback = _ => throw new InvalidOperationException("Refresh-only mode must not resolve package channels.")
};
});
using var provider = services.BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
var service = provider.GetRequiredService<ConfigSourceService>();
await service.CheckProjectAsync(workspace.WorkspaceRoot, force: false, CancellationToken.None);
if (changed)
{
git.ReadConfiguration = (_, _) => Task.FromResult(("version-2", new JsonObject()));
}
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse("update --config-source --yes --non-interactive");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equal(1, git.Calls);
Assert.Equal(1, git.CheckCalls);
Assert.False(Assert.IsType<UpdateCommand>(result.CommandResult.Command).RequiresCliPackageMetadata);
var notice = Assert.Single(interaction.DisplayedMessages,
message => message.Message == (changed ? ConfigSourceStrings.Updated : ConfigSourceStrings.AlreadyUpToDate));
Assert.Equal(changed ? KnownEmojis.CheckMarkButton : KnownEmojis.Information, notice.Emoji);
Assert.Equal(ConsoleOutput.Error, notice.ConsoleOverride);
}
[Theory]
[InlineData(false, 0)]
[InlineData(true, 0)]
[InlineData(true, 64 * 1024)]
[InlineData(true, 64 * 1024 + 1)]
public async Task UpdateConfigSource_AcquisitionFailureRemainsCommandFailure(bool timeout, int outputLength)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
var prompt = outputLength == 0 ? "Enter passphrase: " : new string('x', outputLength - 1) + "?";
git.ReadConfiguration = (_, _) => throw new ConfigSourceException(timeout ? ConfigSourceStrings.GitTimeout : ConfigSourceStrings.AuthenticationFailed)
{
GitOutput = timeout ? prompt : null
};
var path = Path.Combine(workspace.Path, AspireConfigFile.FileName);
var previous = await File.ReadAllTextAsync(path);
var result = provider.GetRequiredService<RootCommand>().Parse("update --config-source --yes --non-interactive");
Assert.NotEqual(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(1, git.Calls);
Assert.Equal(0, git.CheckCalls);
Assert.Equal(previous, await File.ReadAllTextAsync(path));
Assert.Equal(timeout ? ConfigSourceStrings.GitTimeout : ConfigSourceStrings.AuthenticationFailed,
Assert.Single(interaction.DisplayedErrors));
if (timeout)
{
var expectedOutput = outputLength > 64 * 1024 ? prompt[^(64 * 1024)..] : prompt;
Assert.Equal((expectedOutput, (ConsoleOutput?)ConsoleOutput.Error), Assert.Single(interaction.DisplayedRawText));
}
else
{
Assert.Empty(interaction.DisplayedRawText);
}
}
[Theory]
[InlineData(null)]
[InlineData("ref")]
[InlineData("repository")]
[InlineData("path")]
[InlineData("both")]
public async Task ProjectSelection_CheckFailureDoesNotFailOrReplaceSavedSettings(string? invalidField)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(new()
{
Repository = s_source.Repository,
Path = s_source.Path,
Ref = invalidField == "ref" ? "HEAD" : null,
AppliedVersion = s_source.AppliedVersion
}, workspace.WorkspaceRoot, CancellationToken.None);
var path = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await ConfigurationService.SetConfigurationInFileAsync(path, "skillSources.team.repository", "example/local");
await ConfigurationService.SetConfigurationInFileAsync(path, "appHost.path", "apphost.cs");
if (invalidField is "repository" or "path" or "both")
{
var configuration = JsonNode.Parse(await File.ReadAllTextAsync(path))!.AsObject();
var binding = configuration["configSource"]!.AsObject();
foreach (var field in invalidField == "both" ? new[] { "repository", "path" } : [invalidField])
{
Assert.True(binding.Remove(field));
}
await File.WriteAllTextAsync(path, configuration.ToJsonString());
}
var previous = await File.ReadAllTextAsync(path);
var projectFile = new FileInfo(Path.Combine(workspace.Path, "apphost.cs"));
await File.WriteAllTextAsync(projectFile.FullName, "#:sdk Aspire.AppHost.Sdk");
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.InspectConfiguration = (_, _) => throw new ConfigSourceException(ConfigSourceStrings.AuthenticationFailed);
var project = await provider.GetRequiredService<IProjectLocator>().UseOrFindAppHostProjectFileAsync(
projectFile, createSettingsFile: true, CancellationToken.None);
await provider.GetRequiredService<ConfigSourceService>().WaitForChecksAsync().DefaultTimeout();
Assert.Equal(projectFile.FullName, project?.FullName);
var result = provider.GetRequiredService<RootCommand>().Parse("config get skillSources.team.repository");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(previous, await File.ReadAllTextAsync(path));
Assert.Equal(0, git.Calls);
Assert.Equal(invalidField is not null ? 0 : 1, git.CheckCalls);
var expectedError = invalidField switch
{
null => ConfigSourceStrings.AuthenticationFailed,
"ref" => ConfigSourceStrings.InvalidRef,
_ => ConfigSourceStrings.InvalidBinding
};
var warning = Assert.Single(interaction.DisplayedMessages, message => message.ConsoleOverride is Aspire.Cli.Interaction.ConsoleOutput.Error);
Assert.Equal(string.Format(System.Globalization.CultureInfo.CurrentCulture, ConfigSourceStrings.CheckFailed,
expectedError), warning.Message);
if (invalidField is not null)
{
var refresh = provider.GetRequiredService<RootCommand>().Parse("update --config-source --yes --non-interactive");
Assert.Equal(CliExitCodes.InvalidCommand, await refresh.InvokeAsync().DefaultTimeout());
Assert.Equal(expectedError, Assert.Single(interaction.DisplayedErrors));
Assert.Equal(0, git.Calls);
Assert.Equal(previous, await File.ReadAllTextAsync(path));
}
}
[Fact]
public void UpdateConfigSource_NonInteractiveRequiresYes()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse("update --config-source --non-interactive");
Assert.Single(result.Errors);
}
[Theory]
[InlineData("--self")]
[InlineData("--migrate")]
[InlineData("--channel daily")]
[InlineData("--quality stable")]
[InlineData("--nuget-config-dir .")]
[InlineData("--dry-run")]
public void UpdateConfigSource_RejectsIncompatibleOptions(string option)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse($"update --config-source {option}");
Assert.Equal(ConfigSourceStrings.IncompatibleOptions, Assert.Single(result.Errors).Message);
}
[Theory]
[InlineData(false, "implicit")]
[InlineData(false, "file")]
[InlineData(false, "directory")]
[InlineData(true, "implicit")]
[InlineData(true, "file")]
[InlineData(true, "directory")]
public async Task ProjectSelection_ProcessesAncestorSourceForChildAppHost(bool refresh, string selection)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var project = workspace.CreateDirectory("AppHost");
var projectFile = new FileInfo(Path.Combine(project.FullName, "apphost.cs"));
await File.WriteAllTextAsync(projectFile.FullName, "#:sdk Aspire.AppHost.Sdk");
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var rootPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await ConfigurationService.SetConfigurationInFileAsync(rootPath, "appHost.path", "AppHost/apphost.cs");
var original = await File.ReadAllTextAsync(rootPath);
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.InspectConfiguration = (_, _) => Task.FromResult("version-2");
git.ReadConfiguration = (_, _) => Task.FromResult(("version-2", new JsonObject()));
var requested = selection switch
{
"file" => projectFile,
"directory" => new FileInfo(project.FullName),
_ => null
};
if (refresh)
{
var argument = requested is null ? "" : $" --apphost \"{requested.FullName}\"";
var result = provider.GetRequiredService<RootCommand>().Parse($"update --config-source{argument} --yes --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal("version-2", AspireConfigFile.Load(workspace.Path)!.ConfigSource!.AppliedVersion);
}
else
{
var selected = await provider.GetRequiredService<IProjectLocator>().UseOrFindAppHostProjectFileAsync(
requested, createSettingsFile: false, CancellationToken.None);
Assert.Equal(projectFile.FullName, selected?.FullName);
await provider.GetRequiredService<ConfigSourceService>().WaitForChecksAsync().DefaultTimeout();
var service = provider.GetRequiredService<ConfigSourceService>();
service.NotifyIfUpdateAvailable();
Assert.Equal(ConfigSourceStrings.UpdateAvailable, Assert.Single(interaction.DisplayedMessages).Message);
Assert.Equal(original, await File.ReadAllTextAsync(rootPath));
}
Assert.Equal(refresh ? 1 : 0, git.Calls);
Assert.Equal(refresh ? 0 : 1, git.CheckCalls);
Assert.False(File.Exists(Path.Combine(project.FullName, AspireConfigFile.FileName)));
}
[Theory]
[InlineData("missing.cs")]
[InlineData("missing.csproj")]
[InlineData("missing-directory")]
[InlineData("missing-directory/apphost.cs")]
public async Task UpdateConfigSource_MissingExplicitPathFailsWithoutRefreshingBindings(string requestedPath)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var localPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
var originalLocalConfiguration = await File.ReadAllTextAsync(localPath);
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var globalFile = new FileInfo(provider.GetRequiredService<IConfigurationService>().GetSettingsFilePath(isGlobal: true));
globalFile.Directory!.Create();
await TestConfigSourceServices.SaveBindingAsync(s_source, globalFile.Directory, CancellationToken.None);
File.Move(Path.Combine(globalFile.Directory.FullName, AspireConfigFile.FileName), globalFile.FullName);
var originalGlobalConfiguration = await File.ReadAllTextAsync(globalFile.FullName);
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) => Task.FromResult(("version-2", new JsonObject()));
var result = provider.GetRequiredService<RootCommand>().Parse(
$"update --config-source --apphost \"{Path.Combine(workspace.Path, requestedPath)}\" --yes --non-interactive");
Assert.Empty(result.Errors);
Assert.Equal(CliExitCodes.FailedToFindProject, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(InteractionServiceStrings.ProjectOptionDoesntExist, Assert.Single(interaction.DisplayedErrors));
Assert.Equal(0, git.Calls);
Assert.Equal(0, git.CheckCalls);
Assert.Equal(0, Assert.IsType<TestConfigSourceDetector>(provider.GetRequiredService<IInternalMicrosoftDetector>()).Calls);
Assert.Equal(originalLocalConfiguration, await File.ReadAllTextAsync(localPath));
Assert.Equal(originalGlobalConfiguration, await File.ReadAllTextAsync(globalFile.FullName));
}
[Fact]
public async Task UpdateConfigSource_ExplicitAppHostRefreshesNearestBindingOnly()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var project = workspace.CreateDirectory("selected-project");
await File.WriteAllTextAsync(Path.Combine(project.FullName, "apphost.cs"), "#:sdk Aspire.AppHost.Sdk");
await TestConfigSourceServices.SaveBindingAsync(
new ConfigSource { Repository = "https://parent.example/configuration", Path = "parent.json", AppliedVersion = "parent-version" },
workspace.WorkspaceRoot, CancellationToken.None);
var parentPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await ConfigurationService.SetConfigurationInFileAsync(parentPath, "appHost.path", "selected-project/apphost.cs");
var parentConfiguration = await File.ReadAllTextAsync(parentPath);
await TestConfigSourceServices.SaveBindingAsync(s_source, project, CancellationToken.None);
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var command = provider.GetRequiredService<RootCommand>();
var result = command.Parse($"update --config-source --apphost \"{Path.Combine(project.FullName, "apphost.cs")}\" --yes --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(1, Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>()).Calls);
Assert.Equal(0, Assert.IsType<TestConfigSourceDetector>(provider.GetRequiredService<IInternalMicrosoftDetector>()).Calls);
Assert.Equal(parentConfiguration, await File.ReadAllTextAsync(parentPath));
Assert.Equal("version-1", AspireConfigFile.Load(project.FullName)!.ConfigSource!.AppliedVersion);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UpdateConfigSource_MissingOrOptedOutBindingSucceedsWithoutDetectionOrAcquisition(bool optedOut)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
if (optedOut)
{
await TestConfigSourceServices.SaveBindingAsync(new ConfigSource { OptOut = true }, workspace.WorkspaceRoot, CancellationToken.None);
}
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse("update --config-source --yes --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Empty(interaction.DisplayedErrors);
Assert.Empty(interaction.DisplayedRenderables);
var notice = Assert.Single(interaction.DisplayedMessages);
Assert.Equal(ConfigSourceStrings.NoBinding, notice.Message);
Assert.Equal(ConsoleOutput.Error, notice.ConsoleOverride);
Assert.Equal(0, Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>()).Calls);
Assert.Equal(0, Assert.IsType<TestConfigSourceDetector>(provider.GetRequiredService<IInternalMicrosoftDetector>()).Calls);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UpdateConfigSource_IgnoresGlobalBindingWhenNearestConfigurationHasNone(bool explicitAppHost)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var localPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await File.WriteAllTextAsync(localPath, "{}");
if (explicitAppHost)
{
await File.WriteAllTextAsync(Path.Combine(workspace.Path, "apphost.cs"), "#:sdk Aspire.AppHost.Sdk");
}
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var globalFile = new FileInfo(provider.GetRequiredService<IConfigurationService>().GetSettingsFilePath(isGlobal: true));
globalFile.Directory!.Create();
await TestConfigSourceServices.SaveBindingAsync(s_source, globalFile.Directory, CancellationToken.None);
File.Move(Path.Combine(globalFile.Directory.FullName, AspireConfigFile.FileName), globalFile.FullName);
var originalGlobalConfiguration = await File.ReadAllTextAsync(globalFile.FullName);
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) => Task.FromResult(("version-2", new JsonObject()));
var appHostArgument = explicitAppHost ? $" --apphost \"{Path.Combine(workspace.Path, "apphost.cs")}\"" : "";
var result = provider.GetRequiredService<RootCommand>().Parse(
$"update --config-source{appHostArgument} --yes --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(0, git.Calls);
Assert.Equal(0, git.CheckCalls);
Assert.Equal(0, Assert.IsType<TestConfigSourceDetector>(provider.GetRequiredService<IInternalMicrosoftDetector>()).Calls);
Assert.Equal(ConfigSourceStrings.NoBinding, Assert.Single(interaction.DisplayedMessages).Message);
Assert.Equal("{}", await File.ReadAllTextAsync(localPath));
Assert.Equal(originalGlobalConfiguration, await File.ReadAllTextAsync(globalFile.FullName));
}
[Theory]
[InlineData(true, false, false)]
[InlineData(false, false, false)]
[InlineData(true, true, false)]
[InlineData(false, true, false)]
[InlineData(true, false, true)]
[InlineData(false, false, true)]
public async Task Update_OffersSourceForExistingAppHostAndRemembersChoice(bool accepted, bool employeeSource, bool explicitConsent)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var appHostDirectory = workspace.CreateDirectory("AppHost");
var projectFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(projectFile.FullName, "<Project />");
var configPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await File.WriteAllTextAsync(configPath, """{"custom":"keep","docs":{"llmsTxtUrl":"https://local.example/llms.txt"}}""");
var prompts = 0;
var interaction = new TestInteractionService
{
ConfirmCallback = (prompt, _) =>
{
Assert.Equal(ConfigSourceStrings.UpdateUseSourcePrompt, prompt);
prompts++;
return accepted;
}
};
for (var attempt = 0; attempt < 2; attempt++)
{
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
options.CliHostEnvironmentFactory = _ => explicitConsent
? TestHelpers.CreateNonInteractiveHostEnvironment()
: TestHelpers.CreateInteractiveHostEnvironment();
options.ProjectLocatorFactory = _ => new TestProjectLocator
{
UseOrFindAppHostProjectFileAsyncCallback = (_, _, _) => Task.FromResult<FileInfo?>(projectFile)
};
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner();
options.ProjectUpdaterFactory = _ => new TestProjectUpdater
{
UpdateProjectAsyncCallback = (_, _) => Task.FromResult(new ProjectUpdateResult { UpdatedApplied = false })
};
options.PackagingServiceFactory = _ => new TestPackagingService();
});
if (!employeeSource)
{
services.AddSingleton<IEnvironment>(new TestEnvironment(new Dictionary<string, string?>
{
[CliConfigNames.InitSourceUrl] = s_source.Repository
}));
}
services.AddSingleton<IInternalMicrosoftDetector>(new TestConfigSourceDetector { IsInternal = employeeSource });
var git = new TestConfigSourceRepository
{
ReadConfiguration = (_, _) => Task.FromResult(("version-1", new JsonObject
{
["skillSources"] = new JsonObject { ["team"] = new JsonObject { ["repository"] = "example/team" } },
["docs"] = new JsonObject { ["llmsTxtUrl"] = "https://docs.example/llms.txt" }
}))
};
services.AddSingleton<IGitClient>(git);
using var provider = services.BuildServiceProvider();
var consent = explicitConsent ? $" --use-config-source{(accepted ? "" : " false")} --non-interactive" : "";
var result = provider.GetRequiredService<RootCommand>().Parse($"update --apphost \"{projectFile.FullName}\" --yes{consent}");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
var configuration = JsonNode.Parse(await File.ReadAllTextAsync(configPath))!;
var expectedSource = accepted
? new ConfigSource
{
Repository = employeeSource ? ConfigSourceService.MicrosoftRepository : s_source.Repository,
Path = s_source.Path,
AppliedVersion = s_source.AppliedVersion
}
: new ConfigSource { OptOut = true };
Assert.Equivalent(expectedSource, AspireConfigFile.Load(workspace.Path)!.ConfigSource, strict: true);
Assert.Equal("keep", configuration["custom"]!.GetValue<string>());
Assert.Equal(accepted ? "example/team" : null, configuration["skillSources"]?["team"]?["repository"]?.GetValue<string>());
Assert.Equal("https://local.example/llms.txt", configuration["docs"]!["llmsTxtUrl"]!.GetValue<string>());
Assert.Equal(accepted && attempt == 0 ? 1 : 0, git.Calls);
Assert.False(File.Exists(Path.Combine(appHostDirectory.FullName, AspireConfigFile.FileName)));
}
Assert.Equal(explicitConsent ? 0 : 1, prompts);
Assert.Empty(interaction.DisplayedErrors);
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public async Task Update_FromSolutionRootPreservesFlattenedAppHostSourceChoice(bool optOut, bool explicitConsent)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var appHostDirectory = workspace.CreateDirectory("AppHost");
var projectFile = new FileInfo(Path.Combine(appHostDirectory.FullName, "AppHost.csproj"));
await File.WriteAllTextAsync(projectFile.FullName, "<Project />");
var configPath = Path.Combine(appHostDirectory.FullName, AspireConfigFile.FileName);
var configuration = optOut
? """{"configSource:optOut":true,"custom":"keep"}"""
: $$"""
{"configSource:repository":"{{s_source.Repository}}","configSource:path":"{{s_source.Path}}","configSource:appliedVersion":"{{s_source.AppliedVersion}}","custom":"keep"}
""";
await File.WriteAllTextAsync(configPath, configuration);
var interaction = new TestInteractionService
{
ConfirmCallback = (_, _) => throw new InvalidOperationException("Unexpected source prompt.")
};
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
options.CliHostEnvironmentFactory = _ => TestHelpers.CreateInteractiveHostEnvironment();
options.ProjectLocatorFactory = _ => new TestProjectLocator
{
UseOrFindAppHostProjectFileAsyncCallback = (_, _, _) => Task.FromResult<FileInfo?>(projectFile)
};
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner();
options.ProjectUpdaterFactory = _ => new TestProjectUpdater
{
UpdateProjectAsyncCallback = (_, _) => Task.FromResult(new ProjectUpdateResult { UpdatedApplied = false })
};
options.PackagingServiceFactory = _ => new TestPackagingService();
});
var detector = new TestConfigSourceDetector { IsInternal = true };
services.AddSingleton<IInternalMicrosoftDetector>(detector);
using var provider = services.BuildServiceProvider();
var consent = explicitConsent ? " --use-config-source" : "";
var result = provider.GetRequiredService<RootCommand>().Parse($"update --apphost \"{projectFile.FullName}\" --yes{consent}");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(configuration, await File.ReadAllTextAsync(configPath));
Assert.Equal(0, detector.Calls);
Assert.Equal(0, Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>()).Calls);
Assert.Empty(interaction.DisplayedErrors);
}
[Fact]
public async Task Update_NonInteractiveDoesNotAdoptSourceWithoutExplicitConsent()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var path = Path.Combine(workspace.Path, AspireConfigFile.FileName);
const string configuration = """{"appHost":{"path":"AppHost.csproj"},"custom":"keep"}""";
await File.WriteAllTextAsync(path, configuration);
await File.WriteAllTextAsync(Path.Combine(workspace.Path, "AppHost.csproj"), "<Project />");
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => new TestInteractionService();
options.DotNetCliRunnerFactory = _ => new TestDotNetCliRunner();
options.ProjectUpdaterFactory = _ => new TestProjectUpdater
{
UpdateProjectAsyncCallback = (_, _) => Task.FromResult(new ProjectUpdateResult { UpdatedApplied = false })
};
options.PackagingServiceFactory = _ => new TestPackagingService();
});
var detector = new TestConfigSourceDetector { IsInternal = true };
services.AddSingleton<IInternalMicrosoftDetector>(detector);
using var provider = services.BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse("update --yes --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(configuration, await File.ReadAllTextAsync(path));
Assert.Equal(0, detector.Calls);
Assert.Equal(0, Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>()).Calls);
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public async Task UpdateConfigSource_RefreshesNearestConfigurationForConfiguredProject(bool bound, bool childConfigExists)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var interaction = new TestInteractionService();
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var selected = workspace.CreateDirectory("selected");
var selectedFile = new FileInfo(Path.Combine(selected.FullName, "apphost.cs"));
var selectedSource = new ConfigSource { Repository = s_source.Repository, Path = "selected.json", AppliedVersion = s_source.AppliedVersion };
if (bound)
{
await TestConfigSourceServices.SaveBindingAsync(selectedSource, selected, CancellationToken.None);
}
else if (childConfigExists)
{
await File.WriteAllTextAsync(Path.Combine(selected.FullName, AspireConfigFile.FileName), "{}");
}
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
options.ProjectLocatorFactory = _ => new TestProjectLocator
{
GetAppHostFromSettingsAsyncCallback = _ => Task.FromResult<FileInfo?>(selectedFile)
};
});
using var provider = services.BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (source, _) =>
{
Assert.True(ConfigSource.HasSameIdentity(selectedSource, source) || ConfigSource.HasSameIdentity(s_source, source));
Assert.Null(source.AppliedVersion);
return Task.FromResult(("version-1", new JsonObject()));
};
var result = provider.GetRequiredService<RootCommand>().Parse("update --config-source --yes --non-interactive");
var hasBinding = bound || !childConfigExists;
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Empty(interaction.DisplayedErrors);
if (!hasBinding)
{
Assert.Equal(ConfigSourceStrings.NoBinding, Assert.Single(interaction.DisplayedMessages).Message);
}
Assert.Equal(hasBinding ? 1 : 0, git.Calls);
Assert.Equal(bound || childConfigExists ? s_source.AppliedVersion : "version-1", AspireConfigFile.Load(workspace.Path)!.ConfigSource!.AppliedVersion);
Assert.Equal(bound, AspireConfigFile.Load(selected.FullName)?.ConfigSource is not null);
}
[Fact]
public async Task ProjectSelection_ChecksAncestorSourceWithoutCopyingItsBinding()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var inheritedRepository = "example/parent";
var initial = TestConfigSourceServices.Create(workspace.CreateExecutionContext(), git: new TestConfigSourceRepository
{
ReadConfiguration = (_, _) => Task.FromResult(("version-1", new JsonObject
{
["skillSources"] = new JsonObject { ["team"] = new JsonObject { ["repository"] = inheritedRepository } }
}))
});
await initial.MaterializeAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var parentPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await ConfigurationService.SetConfigurationInFileAsync(parentPath, "appHost.path", "A/apphost.cs");
var parentConfiguration = await File.ReadAllTextAsync(parentPath);
var selected = workspace.CreateDirectory("B");
var projectFile = new FileInfo(Path.Combine(selected.FullName, "apphost.cs"));
await File.WriteAllTextAsync(projectFile.FullName, "#:sdk Aspire.AppHost.Sdk");
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
var project = await provider.GetRequiredService<IProjectLocator>().UseOrFindAppHostProjectFileAsync(
projectFile, createSettingsFile: false, CancellationToken.None);
var sources = provider.GetRequiredService<ConfigSourceService>();
await sources.WaitForChecksAsync().DefaultTimeout();
Assert.Equal(projectFile.FullName, project?.FullName);
var inherited = await provider.GetRequiredService<IConfigurationService>().GetConfigurationFromDirectoryAsync(
"skillSources.team.repository", selected, continueSearchWhenKeyMissing: true, cancellationToken: CancellationToken.None);
Assert.Equal(inheritedRepository, inherited);
await sources.CheckProjectAsync(selected, force: true, CancellationToken.None);
Assert.Equal(1, git.Calls);
Assert.Equal(0, git.CheckCalls);
Assert.Equal(parentConfiguration, await File.ReadAllTextAsync(parentPath));
Assert.False(File.Exists(Path.Combine(selected.FullName, AspireConfigFile.FileName)));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ProjectSelection_ChecksResolvedProjectSource(bool explicitProject)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var selected = workspace.CreateDirectory("selected");
var projectFile = new FileInfo(Path.Combine(selected.FullName, "apphost.cs"));
await File.WriteAllTextAsync(projectFile.FullName, "#:sdk Aspire.AppHost.Sdk");
var selectedSource = new ConfigSource { Repository = s_source.Repository, Path = "selected.json", AppliedVersion = s_source.AppliedVersion };
await TestConfigSourceServices.SaveBindingAsync(selectedSource, selected, CancellationToken.None);
await ConfigurationService.SetConfigurationInFileAsync(
Path.Combine(workspace.Path, AspireConfigFile.FileName), "appHost.path", "selected/apphost.cs");
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.InspectConfiguration = (source, _) =>
{
Assert.True(ConfigSource.HasSameIdentity(selectedSource, source));
Assert.Null(source.AppliedVersion);
return Task.FromResult("version-1");
};
var project = await provider.GetRequiredService<IProjectLocator>().UseOrFindAppHostProjectFileAsync(
explicitProject ? projectFile : null, createSettingsFile: false, CancellationToken.None);
await provider.GetRequiredService<ConfigSourceService>().WaitForChecksAsync().DefaultTimeout();
Assert.Equal(projectFile.FullName, project?.FullName);
Assert.Equal(1, git.CheckCalls);
Assert.Equal(0, git.Calls);
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task UpdateConfigSource_ExplicitDirectoryResolvesAppHostBeforeBindingFallback(bool hasAppHost, bool bound)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
var parentPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
var parentConfiguration = await File.ReadAllTextAsync(parentPath);
var requestedDirectory = workspace.CreateDirectory("selected");
var projectDirectory = hasAppHost ? requestedDirectory.CreateSubdirectory("AppHost") : requestedDirectory;
if (hasAppHost)
{
await File.WriteAllTextAsync(Path.Combine(projectDirectory.FullName, "apphost.cs"), "#:sdk Aspire.AppHost.Sdk");
await ConfigurationService.SetConfigurationInFileAsync(parentPath, "appHost.path", "selected/AppHost/apphost.cs");
parentConfiguration = await File.ReadAllTextAsync(parentPath);
}
var selectedSource = new ConfigSource
{
Repository = "https://selected.example/configuration",
Path = "selected.json",
AppliedVersion = "version-1"
};
var selectedPath = Path.Combine(projectDirectory.FullName, AspireConfigFile.FileName);
if (bound)
{
await TestConfigSourceServices.SaveBindingAsync(selectedSource, projectDirectory, CancellationToken.None);
}
else
{
await File.WriteAllTextAsync(selectedPath, "{}");
}
var originalConfiguration = await File.ReadAllTextAsync(selectedPath);
var interaction = new TestInteractionService();
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.InteractionServiceFactory = _ => interaction;
}).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (source, _) =>
{
Assert.True(ConfigSource.HasSameIdentity(selectedSource, source));
return Task.FromResult(("version-2", new JsonObject()));
};
var result = provider.GetRequiredService<RootCommand>().Parse(
$"update --config-source --apphost \"{requestedDirectory.FullName}\" --yes --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Empty(interaction.DisplayedErrors);
Assert.Equal(bound ? 1 : 0, git.Calls);
Assert.Equal(0, git.CheckCalls);
Assert.Equal(0, Assert.IsType<TestConfigSourceDetector>(provider.GetRequiredService<IInternalMicrosoftDetector>()).Calls);
Assert.Equal(parentConfiguration, await File.ReadAllTextAsync(parentPath));
if (bound)
{
Assert.Equal("version-2", AspireConfigFile.Load(projectDirectory.FullName)!.ConfigSource!.AppliedVersion);
}
else
{
var notice = Assert.Single(interaction.DisplayedMessages);
Assert.Equal(ConfigSourceStrings.NoBinding, notice.Message);
Assert.Equal(ConsoleOutput.Error, notice.ConsoleOverride);
Assert.Equal(originalConfiguration, await File.ReadAllTextAsync(selectedPath));
}
}
[Theory]
[InlineData("run")]
[InlineData("start")]
[InlineData("restore")]
public async Task ProjectCommands_DoNotCheckSourceWhenProjectResolutionFails(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var missingProject = Path.Combine(workspace.Path, "missing.csproj");
var result = provider.GetRequiredService<RootCommand>().Parse($"{commandLine} --apphost \"{missingProject}\"");
Assert.Empty(result.Errors);
Assert.NotEqual(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
Assert.Equal(0, git.CheckCalls);
Assert.Equal(0, git.Calls);
}
[Theory]
[InlineData("config get features.shared")]
[InlineData("config list --all")]
[InlineData("config set --global features.shared true")]
public async Task CommandsWithoutProjectResolution_DoNotCheckSavedSource(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse(commandLine);
Assert.Empty(result.Errors);
await result.InvokeAsync().DefaultTimeout();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
Assert.Equal(0, git.Calls);
Assert.Equal(0, git.CheckCalls);
}
[Theory]
[InlineData("update --help")]
[InlineData("new --help")]
[InlineData("init --help")]
public async Task Help_DoesNotAcquireSavedSource(string commandLine)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, CancellationToken.None);
using var provider = CliTestHelper.CreateServiceCollection(workspace, outputHelper).BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse(commandLine);
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equal(0, Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>()).Calls);
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(true, true)]
public async Task New_PersistsSourceOnlyInCreatedProjectWhenAccepted(bool accepted, bool localTemplate)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var output = Path.Combine(workspace.Path, "created-project");
if (localTemplate)
{
var config = workspace.CreateDirectory("template/.template.config");
await File.WriteAllTextAsync(Path.Combine(config.FullName, "template.json"), """
{ "identity": "ConfigSource.Local", "name": "Local template", "shortName": "local" }
""");
await File.WriteAllTextAsync(Path.Combine(workspace.Path, "template", AspireConfigFile.FileName), "{}");
}
var templateOptions = localTemplate
? "--template-path template"
: "aspire-empty --language csharp --version 17.0.0";
var services = CreateCreationServices(workspace);
using var provider = services.BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse(
$"new {templateOptions} --name CreatedProject --output \"{output}\" --suppress-agent-init --use-config-source{(accepted ? "" : " false")} --non-interactive");
var exitCode = await result.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.Success, exitCode);
Assert.Equivalent(accepted ? s_source : new ConfigSource { OptOut = true }, AspireConfigFile.Load(output)?.ConfigSource, strict: true);
var configuration = JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(output, AspireConfigFile.FileName)))!;
Assert.Equal(accepted ? "example/team" : null, configuration["skillSources"]?["team"]?["repository"]?.GetValue<string>());
Assert.Equal(accepted ? 1 : 0, Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>()).Calls);
Assert.False(File.Exists(Path.Combine(workspace.Path, AspireConfigFile.FileName)));
var interaction = Assert.IsType<TestInteractionService>(provider.GetRequiredService<IInteractionService>());
Assert.Single(interaction.DisplayedMessages,
message => message.Message == $"[yellow]{SharedCommandStrings.SourceTrustWarning}[/]");
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Init_PersistsSourceChoiceAlongsideSkeleton(bool accepted)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
using var provider = CreateCreationServices(workspace).BuildServiceProvider();
var result = provider.GetRequiredService<RootCommand>().Parse(
$"init --file-based --language csharp --suppress-agent-init --use-config-source{(accepted ? "" : " false")} --non-interactive");
Assert.Equal(CliExitCodes.Success, await result.InvokeAsync().DefaultTimeout());
Assert.Equivalent(accepted ? s_source : new ConfigSource { OptOut = true }, AspireConfigFile.Load(workspace.Path)!.ConfigSource, strict: true);
var configuration = JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(workspace.Path, AspireConfigFile.FileName)))!;
Assert.Equal(accepted ? "example/team" : null, configuration["skillSources"]?["team"]?["repository"]?.GetValue<string>());
Assert.True(File.Exists(Path.Combine(workspace.Path, "apphost.cs")));
Assert.Equal(accepted ? 1 : 0, Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>()).Calls);
}
[Fact]
public async Task Init_ExistingBindingChecksWithoutReapplyingOrRetargeting()
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
const string command = "init --file-based --language csharp --suppress-agent-init --use-config-source true --non-interactive";
using (var original = CreateCreationServices(workspace).BuildServiceProvider())
{
Assert.Equal(CliExitCodes.Success, await original.GetRequiredService<RootCommand>().Parse(command).InvokeAsync().DefaultTimeout());
}
var path = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await ConfigurationService.SetConfigurationInFileAsync(path, "skillSources.team.repository", "example/local");
var services = CreateCreationServices(workspace);
services.AddSingleton<IEnvironment>(new TestEnvironment(new Dictionary<string, string?>
{
[CliConfigNames.InitSourceUrl] = "https://other.example/configuration"
}));
using var provider = services.BuildServiceProvider();
Assert.Equal(CliExitCodes.Success, await provider.GetRequiredService<RootCommand>().Parse(
"init --file-based --language csharp --suppress-agent-init --non-interactive").InvokeAsync().DefaultTimeout());
var configuration = JsonNode.Parse(await File.ReadAllTextAsync(path))!;
Assert.Equal("example/local", configuration["skillSources"]!["team"]!["repository"]!.GetValue<string>());
Assert.Equivalent(s_source, configuration["configSource"]!.Deserialize(JsonSourceGenerationContext.Default.ConfigSource), strict: true);
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
Assert.Equal(0, git.Calls);
Assert.Equal(0, git.CheckCalls);
}
[Theory]
[InlineData(false, true, false)]
[InlineData(true, true, false)]
[InlineData(true, true, true)]
[InlineData(true, false, false)]
[InlineData(true, false, true)]
public async Task Init_SolutionModeUsesAppHostConfigurationAndRefreshesIt(bool existingAppHost, bool appHostConfig, bool existingBinding)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await File.WriteAllTextAsync(Path.Combine(workspace.Path, "Test.sln"), "Fake solution file");
var childPath = Path.Combine(workspace.Path, "Test.AppHost");
var projectPath = Path.Combine(childPath, "Test.AppHost.csproj");
var rootConfigPath = Path.Combine(workspace.Path, AspireConfigFile.FileName);
await File.WriteAllTextAsync(rootConfigPath, """
{"appHost":{"path":"Test.AppHost/Test.AppHost.csproj"},"custom":"solution","skillSources":{"team":{"repository":"example/solution"}}}
""");
if (appHostConfig)
{
await TestConfigSourceServices.SaveBindingAsync(new ConfigSource
{
Repository = "https://solution.example/configuration",
Path = "solution.json",
AppliedVersion = "solution-version"
}, workspace.WorkspaceRoot, CancellationToken.None);
}
const string templateConfig = """
{"appHost":{"path":"Test.AppHost.csproj"},"profiles":{"custom":{"applicationUrl":"https://localhost:1234"}},"custom":"template"}
""";
if (existingAppHost)
{
Directory.CreateDirectory(childPath);
await File.WriteAllTextAsync(projectPath, "<Project />");
if (appHostConfig)
{
await File.WriteAllTextAsync(Path.Combine(childPath, AspireConfigFile.FileName), templateConfig);
}
}
var configDirectory = appHostConfig ? new DirectoryInfo(childPath) : workspace.WorkspaceRoot;
var configPath = Path.Combine(configDirectory.FullName, AspireConfigFile.FileName);
if (existingBinding)
{
await TestConfigSourceServices.SaveBindingAsync(s_source, configDirectory, CancellationToken.None);
await ConfigurationService.SetConfigurationInFileAsync(configPath, "skillSources.team.repository", "example/local");
}
var originalRootConfiguration = await File.ReadAllTextAsync(rootConfigPath);
var originalConfiguration = existingBinding ? await File.ReadAllTextAsync(configPath) : null;
var services = CreateCreationServices(workspace);
services.AddSingleton(workspace.CreateExecutionContext(identityChannel: "default"));
var cache = new FakeNuGetPackageCache
{
GetTemplatePackagesAsyncCallback = (_, _, _, _) =>
Task.FromResult<IEnumerable<Aspire.Shared.NuGetPackageCli>>(
[new() { Id = "Aspire.ProjectTemplates", Source = "nuget.org", Version = "17.0.0" }])
};
services.AddSingleton<Aspire.Cli.Packaging.IPackagingService>(new TestPackagingService
{
GetChannelsAsyncCallback = _ => Task.FromResult<IEnumerable<Aspire.Cli.Packaging.PackageChannel>>(
[Aspire.Cli.Packaging.PackageChannel.CreateImplicitChannel(cache, new TestFeatures(), NullLogger.Instance)])
});
services.AddSingleton<Aspire.Cli.DotNet.IDotNetCliRunner>(new TestDotNetCliRunner
{
NewProjectAsyncCallback = (_, name, outputPath, _, _) =>
{
Directory.CreateDirectory(outputPath);
File.WriteAllText(Path.Combine(outputPath, $"{name}.csproj"), "<Project />");
File.WriteAllText(Path.Combine(outputPath, AspireConfigFile.FileName), templateConfig);
return 0;
}
});
services.AddSingleton<Aspire.Cli.Certificates.ICertificateService>(provider => new TestCertificateService
{
EnsureCertificatesTrustedAsyncCallback = async cancellationToken =>
{
// Keep init alive until its advisory check finishes instead of racing shutdown.
await provider.GetRequiredService<ConfigSourceService>().WaitForChecksAsync().DefaultTimeout();
return await new TestCertificateService().EnsureCertificatesTrustedAsync(cancellationToken);
}
});
if (existingBinding)
{
services.AddSingleton<IEnvironment>(new TestEnvironment(new Dictionary<string, string?>
{
[CliConfigNames.InitSourceUrl] = "https://other.example/configuration"
}));
}
using var provider = services.BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
ConfigSource? checkedSource = null;
git.InspectConfiguration = (source, _) =>
{
checkedSource = source;
return Task.FromResult("version-2");
};
var command = existingBinding
? "init --language csharp --suppress-agent-init --non-interactive"
: "init --language csharp --suppress-agent-init --use-config-source true --non-interactive";
var exitCode = await provider.GetRequiredService<RootCommand>().Parse(command).InvokeAsync().DefaultTimeout();
Assert.True(exitCode == CliExitCodes.Success, string.Join(Environment.NewLine,
Assert.IsType<TestInteractionService>(provider.GetRequiredService<IInteractionService>()).DisplayedErrors));
var sources = provider.GetRequiredService<ConfigSourceService>();
await sources.WaitForChecksAsync().DefaultTimeout();
var configuration = AspireConfigFile.Load(configDirectory.FullName)!;
Assert.Equivalent(s_source, configuration.ConfigSource, strict: true);
Assert.Equal(existingBinding ? "example/local" : "example/team", configuration.SkillSources!["team"].Repository);
Assert.True(Directory.Exists(childPath));
Assert.Equal(appHostConfig, File.Exists(Path.Combine(childPath, AspireConfigFile.FileName)));
Assert.Equal(appHostConfig ? "Test.AppHost.csproj" : "Test.AppHost/Test.AppHost.csproj", configuration.AppHost!.Path);
if (appHostConfig)
{
Assert.Equal("https://localhost:1234", configuration.Profiles!["custom"].ApplicationUrl);
Assert.Equal(originalRootConfiguration, await File.ReadAllTextAsync(rootConfigPath));
}
Assert.Equal(existingBinding ? 0 : 1, git.Calls);
Assert.Equal(existingBinding ? 1 : 0, git.CheckCalls);
if (existingBinding)
{
Assert.NotNull(checkedSource);
Assert.True(ConfigSource.HasSameIdentity(s_source, checkedSource));
Assert.Equal(originalConfiguration, await File.ReadAllTextAsync(configPath));
}
else
{
Assert.Null(checkedSource);
}
using var refreshProvider = CreateCreationServices(workspace).BuildServiceProvider();
var refreshGit = Assert.IsType<TestConfigSourceRepository>(refreshProvider.GetRequiredService<IGitClient>());
refreshGit.ReadConfiguration = (source, _) =>
{
Assert.True(ConfigSource.HasSameIdentity(s_source, source));
return Task.FromResult(("version-2", new JsonObject
{
["skillSources"] = new JsonObject { ["team"] = new JsonObject { ["repository"] = "example/updated" } }
}));
};
var refresh = refreshProvider.GetRequiredService<RootCommand>().Parse(
"update --config-source --yes --non-interactive");
Assert.Equal(CliExitCodes.Success, await refresh.InvokeAsync().DefaultTimeout());
var refreshed = AspireConfigFile.Load(configDirectory.FullName)!;
Assert.Equal("version-2", refreshed.ConfigSource!.AppliedVersion);
Assert.Equal("example/updated", refreshed.SkillSources!["team"].Repository);
Assert.Equal(configuration.AppHost.Path, refreshed.AppHost!.Path);
Assert.Equal(appHostConfig, File.Exists(Path.Combine(childPath, AspireConfigFile.FileName)));
if (appHostConfig)
{
Assert.Equal("https://localhost:1234", refreshed.Profiles!["custom"].ApplicationUrl);
Assert.Equal(originalRootConfiguration, await File.ReadAllTextAsync(rootConfigPath));
}
Assert.Equal(1, refreshGit.Calls);
Assert.Equal(0, refreshGit.CheckCalls);
}
[Theory]
[InlineData("aspire-empty --language csharp")]
[InlineData("--template-path template")]
public async Task New_AcquisitionFailureDoesNotCreateProjectOrFallBack(string templateOptions)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
var output = Path.Combine(workspace.Path, "created-project");
using var provider = CreateCreationServices(workspace).BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) => throw new ConfigSourceException(ConfigSourceStrings.AuthenticationFailed);
var result = provider.GetRequiredService<RootCommand>().Parse(
$"new {templateOptions} --output \"{output}\" --use-config-source true --non-interactive");
Assert.Equal(CliExitCodes.InvalidCommand, await result.InvokeAsync().DefaultTimeout());
Assert.False(Directory.Exists(output));
Assert.Equal(1, git.Calls);
Assert.Equal(ConfigSourceStrings.AuthenticationFailed,
Assert.Single(Assert.IsType<TestInteractionService>(provider.GetRequiredService<Aspire.Cli.Interaction.IInteractionService>()).DisplayedErrors));
}
[Theory]
[InlineData("new aspire-empty --language csharp", false, false)]
[InlineData("new aspire-empty --language csharp", false, true)]
[InlineData("new aspire-empty --language csharp", true, false)]
[InlineData("new aspire-empty --language csharp", true, true)]
[InlineData("init --language csharp", false, false)]
[InlineData("init --language csharp", false, true)]
[InlineData("init --language csharp", true, false)]
[InlineData("init --language csharp", true, true)]
[InlineData("update --config-source --yes", false, false)]
[InlineData("update --config-source --yes", false, true)]
[InlineData("update --config-source --yes", true, false)]
[InlineData("update --config-source --yes", true, true)]
public async Task ConfigSource_AcquisitionFailureIncludesReadmeHelpInSingleError(
string commandLine, bool microsoftDefault, bool supportsLinks)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
const string customReadmeUrl = "https://docs.example/config-source?team=[platform]";
var readmeUrl = microsoftDefault ? ConfigSourceService.MicrosoftReadmeUrl : customReadmeUrl;
var errorMessage = microsoftDefault ? ConfigSourceStrings.GitTimeout : $"{ConfigSourceStrings.AuthenticationFailed} [credential-helper]";
var interaction = new TestInteractionService { SupportsLinks = supportsLinks };
var services = CreateCreationServices(workspace);
services.AddSingleton<IInteractionService>(interaction);
services.AddSingleton<IEnvironment>(new TestEnvironment(new Dictionary<string, string?>
{
[CliConfigNames.InitSourceUrl] = microsoftDefault ? null : s_source.Repository,
[CliConfigNames.InitSourceReadmeUrl] = microsoftDefault ? null : customReadmeUrl
}));
services.AddSingleton<IInternalMicrosoftDetector>(new TestConfigSourceDetector { IsInternal = microsoftDefault });
if (commandLine.StartsWith("update", StringComparison.Ordinal))
{
await TestConfigSourceServices.SaveBindingAsync(microsoftDefault
? new ConfigSource
{
Repository = ConfigSourceService.MicrosoftRepository,
Path = AspireConfigFile.FileName,
AppliedVersion = "version-1"
}
: s_source, workspace.WorkspaceRoot, TestContext.Current.CancellationToken);
}
using var provider = services.BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) => throw new ConfigSourceException(errorMessage);
var result = provider.GetRequiredService<RootCommand>().Parse(
$"{commandLine} --use-config-source true --non-interactive");
Assert.Equal(CliExitCodes.InvalidCommand, await result.InvokeAsync().DefaultTimeout());
var expectedLink = supportsLinks ? $"[link]{readmeUrl.EscapeMarkup()}[/]" : readmeUrl.EscapeMarkup();
Assert.Equal(errorMessage.EscapeMarkup() + Environment.NewLine
+ string.Format(System.Globalization.CultureInfo.CurrentCulture, ConfigSourceStrings.AccessHelp, expectedLink),
Assert.Single(interaction.DisplayedErrors));
Assert.Equal(1, git.Calls);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ConfigSource_AcquisitionFailureIncludesReadmeHelpInSingleExtensionError(bool messageActions)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
const string readmeUrl = "https://docs.example/config-source?team=[platform]";
var errorMessage = $"{ConfigSourceStrings.GitTimeout} [credential-helper]";
var expectedError = errorMessage + Environment.NewLine + string.Format(System.Globalization.CultureInfo.CurrentCulture,
ConfigSourceStrings.AccessHelp, readmeUrl);
var capturedErrors = new List<(string? Message, bool AllowMarkup)>();
var services = CreateCreationServices(workspace);
services.AddSingleton<IExtensionBackchannel>(new TestExtensionBackchannel());
services.AddSingleton<IInteractionService>(serviceProvider => new TestExtensionInteractionService(serviceProvider)
{
TryDisplayCommandFailureAsyncCallback = (message, _, _, allowMarkup, _) =>
{
if (messageActions)
{
capturedErrors.Add((message, allowMarkup));
}
return Task.FromResult(messageActions);
}
});
services.AddSingleton<IEnvironment>(new TestEnvironment(new Dictionary<string, string?>
{
[CliConfigNames.InitSourceUrl] = s_source.Repository,
[CliConfigNames.InitSourceReadmeUrl] = readmeUrl
}));
using var provider = services.BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) => throw new ConfigSourceException(errorMessage);
var exitCode = await provider.GetRequiredService<RootCommand>()
.Parse("new aspire-empty --language csharp --use-config-source true --non-interactive")
.InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.InvalidCommand, exitCode);
var interaction = Assert.IsType<TestExtensionInteractionService>(provider.GetRequiredService<IInteractionService>());
if (messageActions)
{
Assert.Equal((expectedError.EscapeMarkup(), true), Assert.Single(capturedErrors));
Assert.Empty(interaction.DisplayedErrors);
}
else
{
Assert.Empty(capturedErrors);
Assert.Equal(expectedError.EscapeMarkup(), Assert.Single(interaction.DisplayedErrors));
}
}
[Theory]
[InlineData("")]
[InlineData("README.md")]
[InlineData("https://docs.example/README.md\n")]
public async Task UpdateConfigSource_InvalidReadmeDoesNotReplaceAcquisitionFailure(string readmeUrl)
{
using var workspace = TemporaryWorkspace.CreateForCli(outputHelper);
await TestConfigSourceServices.SaveBindingAsync(s_source, workspace.WorkspaceRoot, TestContext.Current.CancellationToken);
var services = CreateCreationServices(workspace);
services.AddSingleton<IEnvironment>(new TestEnvironment(new Dictionary<string, string?>
{
[CliConfigNames.InitSourceReadmeUrl] = readmeUrl
}));
using var provider = services.BuildServiceProvider();
var git = Assert.IsType<TestConfigSourceRepository>(provider.GetRequiredService<IGitClient>());
git.ReadConfiguration = (_, _) => throw new ConfigSourceException(ConfigSourceStrings.GitTimeout);
var exitCode = await provider.GetRequiredService<RootCommand>()
.Parse("update --config-source --yes --non-interactive").InvokeAsync().DefaultTimeout();
Assert.Equal(CliExitCodes.InvalidCommand, exitCode);
var interaction = Assert.IsType<TestInteractionService>(provider.GetRequiredService<IInteractionService>());
Assert.Equal(ConfigSourceStrings.GitTimeout, Assert.Single(interaction.DisplayedErrors));
}
private IServiceCollection CreateCreationServices(TemporaryWorkspace workspace)
{
var services = CliTestHelper.CreateServiceCollection(workspace, outputHelper, options =>
{
options.CliExecutionContextFactory = _ => workspace.CreateExecutionContext(identityChannel: "stable");
options.InteractionServiceFactory = _ => new TestInteractionService();
});
services.AddSingleton<IEnvironment>(new TestEnvironment(new Dictionary<string, string?>
{
[CliConfigNames.InitSourceUrl] = s_source.Repository
}));
services.AddSingleton<IGitClient>(new TestConfigSourceRepository
{
ReadConfiguration = (_, _) => Task.FromResult(("version-1", new JsonObject
{
["skillSources"] = new JsonObject { ["team"] = new JsonObject { ["repository"] = "example/team" } },
["sdk"] = new JsonObject { ["version"] = "99.0.0" }
}))
});
return services;
}
}