repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.IO; using System.Linq; namespace AWS.Deploy.ServerMode.Client.Utilities { public class PathUtilities { public static bool IsDeployToolPathValid(string deployToolPath) { deployToolPath = deployToolPath.Trim(); if (string.IsNullOrEmpty(deployToolPath)) return false; if (deployToolPath.StartsWith(@"\\")) return false; if (deployToolPath.Contains("&")) return false; if (Path.GetInvalidPathChars().Any(x => deployToolPath.Contains(x))) return false; if (!File.Exists(deployToolPath)) return false; return true; } } }
34
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using Amazon.Runtime; using System.Threading.Tasks; using System.Threading; namespace AWS.Deploy.ServerMode.Client.Utilities { public static class ServerModeUtilities { /// <summary> /// Checks server mode health API and waits until the API returns a `Ready` status. /// This is useful when initializing a server mode connection to make sure server mode is ready to accept requests. /// </summary> public static async Task WaitUntilServerModeReady(this RestAPIClient restApiClient, CancellationToken cancellationToken = default(CancellationToken)) { await WaitUntilHelper.WaitUntil(async () => { var status = SystemStatus.Error; try { status = (await restApiClient.HealthAsync()).Status; } catch (Exception) { } return status == SystemStatus.Ready; }, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10), cancellationToken); } /// <summary> /// Uses AWS .NET SDK <see cref="FallbackCredentialsFactory"/> to resolve the default credentials from multiple fallback sources. /// This includes AWS credentials file stored on the local machine, environment variables , etc... /// This method does not take into account the AWS Profile and Region defined on the CLI level for AWS Deploy Tool for .NET. /// </summary> public static Task<AWSCredentials> ResolveDefaultCredentials() { var testCredentials = FallbackCredentialsFactory.GetCredentials(); return Task.FromResult(testCredentials); } } }
46
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace AWS.Deploy.ServerMode.Client.Utilities { internal static class WaitUntilHelper { public static async Task WaitUntil(Func<Task<bool>> predicate, TimeSpan frequency, TimeSpan timeout, CancellationToken cancellationToken) { var waitTask = Task.Run(async () => { while (!await predicate()) { await Task.Delay(frequency, cancellationToken); } }); if (waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout))) { throw new TimeoutException(); } } public static async Task<bool> WaitUntilSuccessStatusCode(string url, HttpClientHandler httpClientHandler, TimeSpan frequency, TimeSpan timeout, CancellationToken cancellationToken) { var client = new HttpClient(httpClientHandler); try { await WaitUntil(async () => { try { var httpResponseMessage = await client.GetAsync(url, cancellationToken); return httpResponseMessage.IsSuccessStatusCode; } catch (Exception) { return false; } }, frequency, timeout, cancellationToken); } catch (TimeoutException) { return false; } return true; } } }
57
aws-dotnet-deploy
aws
C#
using AWS.Deploy.CLI; using AWS.Deploy.CLI.Commands; using NSwag; using NSwag.CodeGeneration.CSharp; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace AWS.Deploy.ServerMode.ClientGenerator { class Program { static async Task Main(string[] args) { // Start up the server mode to make the swagger.json file available. var portNumber = 5678; var serverCommand = new ServerModeCommand(new ConsoleInteractiveServiceImpl(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); _ = serverCommand.ExecuteAsync(cancelSource.Token); try { // Wait till server mode is started. await Task.Delay(3000); // Grab the swagger.json from the running instances of server mode var document = await OpenApiDocument.FromUrlAsync($"http://localhost:{portNumber}/swagger/v1/swagger.json"); var settings = new CSharpClientGeneratorSettings { ClassName = "RestAPIClient", GenerateClientInterfaces = true, CSharpGeneratorSettings = { Namespace = "AWS.Deploy.ServerMode.Client", }, HttpClientType = "ServerModeHttpClient" }; var generator = new CSharpClientGenerator(document, settings); var code = generator.GenerateFile(); // Save the generated client to the AWS.Deploy.ServerMode.Client project var fullPath = DetermineFullFilePath("RestAPI.cs"); File.WriteAllText(fullPath, code); } finally { // terminate running server mode. cancelSource.Cancel(); } } static string DetermineFullFilePath(string codeFile) { var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); while (!string.Equals(dir?.Name, "src")) { if (dir == null) break; dir = dir.Parent; } if (dir == null) throw new Exception("Could not determine file path of current directory."); return Path.Combine(dir.FullName, "AWS.Deploy.ServerMode.Client", codeFile); } } }
73
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.Common.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using Moq; using Xunit; namespace AWS.Deploy.CLI.Common.UnitTests.ConfigFileDeployment { public class DeploymentSettingsHandlerTests { private readonly string _projectPath; private readonly IOptionSettingHandler _optionSettingHandler; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IRecipeHandler _recipeHandler; private readonly IDeploymentSettingsHandler _deploymentSettingsHandler; private readonly RecommendationEngine _recommendationEngine; private readonly OrchestratorSession _orchestratorSession; private const string BEANSTALK_PLATFORM_ARN_TOKEN = "{LatestDotnetBeanstalkPlatformArn}"; private const string STACK_NAME_TOKEN = "{StackName}"; private const string DEFAULT_VPC_ID_TOKEN = "{DefaultVpcId}"; public DeploymentSettingsHandlerTests() { _projectPath = SystemIOUtilities.ResolvePath("WebAppWithDockerFile"); _directoryManager = new DirectoryManager(); _fileManager = new FileManager(); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new Mock<IOrchestratorInteractiveService>().Object; var parser = new ProjectDefinitionParser(_fileManager, _directoryManager); var awsCredentials = new Mock<AWSCredentials>(); _orchestratorSession = new OrchestratorSession( parser.Parse(_projectPath).Result, awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; var validatorFactory = new TestValidatorFactory(); _optionSettingHandler = new OptionSettingHandler(validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService, _directoryManager, _fileManager, _optionSettingHandler, validatorFactory); _deploymentSettingsHandler = new DeploymentSettingsHandler(_fileManager, _directoryManager, _optionSettingHandler, _recipeHandler); _recommendationEngine = new RecommendationEngine(_orchestratorSession, _recipeHandler); } [Fact] public async Task ApplySettings_AppRunner() { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppAppRunner")); var filePath = Path.Combine("ConfigFileDeployment", "TestFiles", "AppRunnerConfigFile.json"); // ACT var deploymentSettings = await _deploymentSettingsHandler.ReadSettings(filePath); await _deploymentSettingsHandler.ApplySettings(deploymentSettings, selectedRecommendation, new Mock<IDeployToolValidationContext>().Object); // ASSERT Assert.Equal("default", deploymentSettings.AWSProfile); Assert.Equal("us-west-2", deploymentSettings.AWSRegion); Assert.Equal("MyAppStack", deploymentSettings.ApplicationName); Assert.Equal("AspNetAppAppRunner", deploymentSettings.RecipeId); Assert.Equal(true, GetOptionSettingValue(selectedRecommendation, "VPCConnector.CreateNew")); Assert.Contains("subnet-1234abcd", GetOptionSettingValue<SortedSet<string>>(selectedRecommendation, "VPCConnector.Subnets")); Assert.Contains("sg-1234abcd", GetOptionSettingValue<SortedSet<string>>(selectedRecommendation, "VPCConnector.SecurityGroups")); } [Fact] public async Task ApplySettings_ECSFargate() { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppEcsFargate")); var filePath = Path.Combine("ConfigFileDeployment", "TestFiles", "ECSFargateConfigFile.json"); // ACT var deploymentSettings = await _deploymentSettingsHandler.ReadSettings(filePath); await _deploymentSettingsHandler.ApplySettings(deploymentSettings, selectedRecommendation, new Mock<IDeployToolValidationContext>().Object); // ASSERT Assert.Equal("default", deploymentSettings.AWSProfile); Assert.Equal("us-west-2", deploymentSettings.AWSRegion); Assert.Equal("MyAppStack", deploymentSettings.ApplicationName); Assert.Equal("AspNetAppEcsFargate", deploymentSettings.RecipeId); Assert.Equal(true, GetOptionSettingValue(selectedRecommendation, "ECSCluster.CreateNew")); Assert.Equal("MyNewCluster", GetOptionSettingValue(selectedRecommendation, "ECSCluster.NewClusterName")); Assert.Equal("MyNewService", GetOptionSettingValue(selectedRecommendation, "ECSServiceName")); Assert.Equal(3, GetOptionSettingValue<int>(selectedRecommendation, "DesiredCount")); Assert.Equal(true, GetOptionSettingValue(selectedRecommendation, "ApplicationIAMRole.CreateNew")); Assert.Equal(true, GetOptionSettingValue(selectedRecommendation, "Vpc.IsDefault")); Assert.Equal(256, GetOptionSettingValue<int>(selectedRecommendation, "TaskCpu")); Assert.Equal(512, GetOptionSettingValue<int>(selectedRecommendation, "TaskMemory")); Assert.Equal("C:\\codebase", GetOptionSettingValue(selectedRecommendation, "DockerExecutionDirectory")); } [Fact] public async Task ApplySettings_ElasticBeanStalk() { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppElasticBeanstalkLinux")); var filePath = Path.Combine("ConfigFileDeployment", "TestFiles", "ElasticBeanStalkConfigFile.json"); // ACT var deploymentSettings = await _deploymentSettingsHandler.ReadSettings(filePath); await _deploymentSettingsHandler.ApplySettings(deploymentSettings, selectedRecommendation, new Mock<IDeployToolValidationContext>().Object); // ASSERT Assert.Equal("default", deploymentSettings.AWSProfile); Assert.Equal("us-west-2", deploymentSettings.AWSRegion); Assert.Equal("MyAppStack", deploymentSettings.ApplicationName); Assert.Equal("AspNetAppElasticBeanstalkLinux", deploymentSettings.RecipeId); Assert.Equal(true, GetOptionSettingValue(selectedRecommendation, "BeanstalkApplication.CreateNew")); Assert.Equal("MyApplication", GetOptionSettingValue(selectedRecommendation, "BeanstalkApplication.ApplicationName")); Assert.Equal("MyEnvironment", GetOptionSettingValue(selectedRecommendation, "BeanstalkEnvironment.EnvironmentName")); Assert.Equal("MyInstance", GetOptionSettingValue(selectedRecommendation, "InstanceType")); Assert.Equal("SingleInstance", GetOptionSettingValue(selectedRecommendation, "EnvironmentType")); Assert.Equal("application", GetOptionSettingValue(selectedRecommendation, "LoadBalancerType")); Assert.Equal(true, GetOptionSettingValue(selectedRecommendation, "ApplicationIAMRole.CreateNew")); Assert.Equal("MyPlatformArn", GetOptionSettingValue(selectedRecommendation, "ElasticBeanstalkPlatformArn")); Assert.Equal(true, GetOptionSettingValue(selectedRecommendation, "ElasticBeanstalkManagedPlatformUpdates.ManagedActionsEnabled")); Assert.Equal("Mon:12:00", GetOptionSettingValue(selectedRecommendation, "ElasticBeanstalkManagedPlatformUpdates.PreferredStartTime")); Assert.Equal("minor", GetOptionSettingValue(selectedRecommendation, "ElasticBeanstalkManagedPlatformUpdates.UpdateLevel")); var envVars = GetOptionSettingValue<Dictionary<string, string>>(selectedRecommendation, "ElasticBeanstalkEnvironmentVariables"); Assert.Equal("VarValue", envVars["VarName"]); } [Theory] [InlineData(SaveSettingsType.All, "ConfigFileDeployment", "TestFiles", "SettingsSnapshot_NonContainer.json")] [InlineData(SaveSettingsType.Modified, "ConfigFileDeployment", "TestFiles", "SettingsSnapshot_NonContainer_ModifiedOnly.json")] public async Task SaveSettings_NonContainerBased(SaveSettingsType saveSettingsType, string path1, string path2, string path3) { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppElasticBeanstalkLinux")); var expectedSnapshotfilePath = Path.Combine(path1, path2, path3); var actualSnapshotFilePath = Path.Combine(Path.GetTempPath(), $"DeploymentSettings-{Guid.NewGuid().ToString().Split('-').Last()}.json"); var cloudApplication = new CloudApplication("MyAppStack", "", CloudApplicationResourceType.CloudFormationStack, "AspNetAppElasticBeanstalkLinux"); // ARRANGE - add replacement tokens selectedRecommendation.AddReplacementToken(BEANSTALK_PLATFORM_ARN_TOKEN, "Latest-ARN"); selectedRecommendation.AddReplacementToken(STACK_NAME_TOKEN, "MyAppStack"); selectedRecommendation.AddReplacementToken(DEFAULT_VPC_ID_TOKEN, "vpc-12345678"); // ARRANGE - Modify option setting items await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "BeanstalkApplication", "MyBeanstalkApplication"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "BeanstalkEnvironment.EnvironmentName", "MyBeanstalkEnvironment"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "EnvironmentType", "LoadBalanced"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "XRayTracingSupportEnabled", true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ElasticBeanstalkEnvironmentVariables", new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }); // ACT await _deploymentSettingsHandler.SaveSettings(new SaveSettingsConfiguration(saveSettingsType, actualSnapshotFilePath), selectedRecommendation, cloudApplication, _orchestratorSession); // ASSERT var actualSnapshot = await _fileManager.ReadAllTextAsync(actualSnapshotFilePath); var expectedSnapshot = await _fileManager.ReadAllTextAsync(expectedSnapshotfilePath); actualSnapshot = SanitizeFileContents(actualSnapshot); expectedSnapshot = SanitizeFileContents(expectedSnapshot); Assert.Equal(expectedSnapshot, actualSnapshot); } [Theory] [InlineData(SaveSettingsType.All, "ConfigFileDeployment", "TestFiles", "SettingsSnapshot_Container.json")] [InlineData(SaveSettingsType.Modified, "ConfigFileDeployment", "TestFiles", "SettingsSnapshot_Container_ModifiedOnly.json")] public async Task SaveSettings_ContainerBased(SaveSettingsType saveSettingsType, string path1, string path2, string path3) { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppAppRunner")); var expectedSnapshotfilePath = Path.Combine(path1, path2, path3); var actualSnapshotFilePath = Path.Combine(Path.GetTempPath(), $"DeploymentSettings-{Guid.NewGuid().ToString().Split('-').Last()}.json"); var cloudApplication = new CloudApplication("MyAppStack", "", CloudApplicationResourceType.CloudFormationStack, "AspNetAppAppRunner"); // ARRANGE - add replacement tokens selectedRecommendation.AddReplacementToken(STACK_NAME_TOKEN, "MyAppStack"); selectedRecommendation.AddReplacementToken(DEFAULT_VPC_ID_TOKEN, "vpc-12345678"); // ARRANGE - Modify option setting items await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ServiceName", "MyAppRunnerService"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "Port", "100"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ECRRepositoryName", "my-ecr-repository"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerfilePath", Path.Combine("DockerAssets", "Dockerfile")); // relative path await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerExecutionDirectory", Path.Combine(_projectPath, "DockerAssets")); // absolute path // ACT await _deploymentSettingsHandler.SaveSettings(new SaveSettingsConfiguration(saveSettingsType, actualSnapshotFilePath), selectedRecommendation, cloudApplication, _orchestratorSession); // ASSERT var actualSnapshot = await _fileManager.ReadAllTextAsync(actualSnapshotFilePath); var expectedSnapshot = await _fileManager.ReadAllTextAsync(expectedSnapshotfilePath); actualSnapshot = SanitizeFileContents(actualSnapshot); expectedSnapshot = SanitizeFileContents(expectedSnapshot); Assert.Equal(expectedSnapshot, actualSnapshot); } [Fact] public async Task SaveSettings_PushImageToECR() { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "PushContainerImageEcr")); var expectedSnapshotfilePath = Path.Combine("ConfigFileDeployment", "TestFiles", "SettingsSnapshot_PushImageECR.json"); var actualSnapshotFilePath = Path.Combine(Path.GetTempPath(), $"DeploymentSettings-{Guid.NewGuid().ToString().Split('-').Last()}.json"); var cloudApplication = new CloudApplication("my-ecr-repository", "", CloudApplicationResourceType.ElasticContainerRegistryImage, "PushContainerImageEcr"); // ARRANGE - Modify option setting items await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ImageTag", "123456789"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ECRRepositoryName", "my-ecr-repository"); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerfilePath", Path.Combine("DockerAssets", "Dockerfile")); // relative path await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerExecutionDirectory", Path.Combine(_projectPath, "DockerAssets")); // absolute path // ACT await _deploymentSettingsHandler.SaveSettings(new SaveSettingsConfiguration(SaveSettingsType.All, actualSnapshotFilePath), selectedRecommendation, cloudApplication, _orchestratorSession); // ASSERT var actualSnapshot = await _fileManager.ReadAllTextAsync(actualSnapshotFilePath); var expectedSnapshot = await _fileManager.ReadAllTextAsync(expectedSnapshotfilePath); actualSnapshot = SanitizeFileContents(actualSnapshot); expectedSnapshot = SanitizeFileContents(expectedSnapshot); Assert.Equal(expectedSnapshot, actualSnapshot); } [Fact] public async Task ReadSettings_InvalidJson() { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppAppRunner")); var filePath = Path.Combine("ConfigFileDeployment", "TestFiles", "InvalidConfigFile.json"); // ACT var readAction = async () => await _deploymentSettingsHandler.ReadSettings(filePath); // ASSERT var ex = await Assert.ThrowsAsync<InvalidDeploymentSettingsException>(readAction); Assert.Equal(DeployToolErrorCode.FailedToDeserializeUserDeploymentFile, ex.ErrorCode); } [Fact] public async Task ReadSettings_FileNotFound() { // ARRANGE var recommendations = await _recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppAppRunner")); var filePath = Path.Combine("ConfigFileDeployment", "TestFiles", "AppRunnerConfigFile"); // ACT var readAction = async () => await _deploymentSettingsHandler.ReadSettings(filePath); // ASSERT var ex = await Assert.ThrowsAsync<InvalidDeploymentSettingsException>(readAction); Assert.Equal(DeployToolErrorCode.UserDeploymentFileNotFound, ex.ErrorCode); } private object GetOptionSettingValue(Recommendation recommendation, string fullyQualifiedId) { var optionSetting = _optionSettingHandler.GetOptionSetting(recommendation, fullyQualifiedId); return _optionSettingHandler.GetOptionSettingValue(recommendation, optionSetting); } private T GetOptionSettingValue<T>(Recommendation recommendation, string fullyQualifiedId) { var optionSetting = _optionSettingHandler.GetOptionSetting(recommendation, fullyQualifiedId); return _optionSettingHandler.GetOptionSettingValue<T>(recommendation, optionSetting); } private string SanitizeFileContents(string content) { return content.Replace("\r\n", Environment.NewLine) .Replace("\n", Environment.NewLine) .Replace("\r\r\n", Environment.NewLine) .Trim(); } } public class TestValidatorFactory : IValidatorFactory { public IOptionSettingItemValidator[] BuildValidators(OptionSettingItem optionSettingItem, Func<OptionSettingItemValidatorConfig, bool> filter = null) => new IOptionSettingItemValidator[0]; public IRecipeValidator[] BuildValidators(RecipeDefinition recipeDefinition) => new IRecipeValidator[0]; } }
308
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using Newtonsoft.Json; using Xunit; using Should; namespace AWS.Deploy.CLI.Common.UnitTests.DeploymentManifestFile { public class DeploymentManifestFileTests : IDisposable { private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; private readonly IDirectoryManager _testDirectoryManager; private readonly string _targetApplicationFullPath; private readonly string _targetApplicationDirectoryFullPath; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly TestAppManager _testAppManager; private bool _isDisposed; public DeploymentManifestFileTests() { _fileManager = new FileManager(); _directoryManager = new DirectoryManager(); _testDirectoryManager = new TestDirectoryManager(); _testAppManager = new TestAppManager(); var targetApplicationPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj"));; _targetApplicationFullPath = _directoryManager.GetDirectoryInfo(targetApplicationPath).FullName; _targetApplicationDirectoryFullPath = _directoryManager.GetDirectoryInfo(targetApplicationPath).Parent.FullName; _deploymentManifestEngine = new DeploymentManifestEngine(_testDirectoryManager, _fileManager); } [Fact] public async Task UpdateDeploymentManifestFile() { // Arrange var saveCdkDirectoryFullPath = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp"); var saveCdkDirectoryFullPath2 = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp2"); var saveCdkDirectoryFullPath3 = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp3"); _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath); _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath2); _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath3); var saveCdkDirectoryRelativePath = Path.GetRelativePath(_targetApplicationDirectoryFullPath, saveCdkDirectoryFullPath); var saveCdkDirectoryRelativePath2 = Path.GetRelativePath(_targetApplicationDirectoryFullPath, saveCdkDirectoryFullPath2); var saveCdkDirectoryRelativePath3 = Path.GetRelativePath(_targetApplicationDirectoryFullPath, saveCdkDirectoryFullPath3); var deploymentManifestFilePath = Path.Combine(_targetApplicationDirectoryFullPath, "aws-deployments.json"); // Act await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath, _targetApplicationFullPath); // Assert Assert.True(_fileManager.Exists(deploymentManifestFilePath)); var deploymentProjectPaths = await GetDeploymentManifestEntries(deploymentManifestFilePath); Assert.Single(deploymentProjectPaths); deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath); // Update deployment-manifest file await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath2, _targetApplicationFullPath); await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath3, _targetApplicationFullPath); // Assert Assert.True(_fileManager.Exists(deploymentManifestFilePath)); deploymentProjectPaths = await GetDeploymentManifestEntries(deploymentManifestFilePath); Assert.Equal(3, deploymentProjectPaths.Count); deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath); deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath2); deploymentProjectPaths.ShouldContain(saveCdkDirectoryRelativePath3); // cleanup File.Delete(deploymentManifestFilePath); Assert.False(_fileManager.Exists(deploymentManifestFilePath)); } [Fact] public async Task GetRecipeDefinitionPaths() { // Arrange var saveCdkDirectoryFullPath = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp"); var saveCdkDirectoryFullPath2 = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp2"); var saveCdkDirectoryFullPath3 = Path.Combine(_targetApplicationDirectoryFullPath, "DeploymentProjects", "MyCdkApp3"); _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath); _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath2); _testDirectoryManager.CreateDirectory(saveCdkDirectoryFullPath3); await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath, _targetApplicationFullPath); await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath2, _targetApplicationFullPath); await _deploymentManifestEngine.UpdateDeploymentManifestFile(saveCdkDirectoryFullPath3, _targetApplicationFullPath); var deploymentManifestFilePath = Path.Combine(_targetApplicationDirectoryFullPath, "aws-deployments.json"); // Act var recipeDefinitionPaths = await _deploymentManifestEngine.GetRecipeDefinitionPaths(_targetApplicationFullPath); // Assert Assert.True(_fileManager.Exists(deploymentManifestFilePath)); recipeDefinitionPaths.Count.ShouldEqual(3, $"Custom recipes found: {Environment.NewLine} {string.Join(Environment.NewLine, recipeDefinitionPaths)}"); recipeDefinitionPaths.ShouldContain(saveCdkDirectoryFullPath); recipeDefinitionPaths.ShouldContain(saveCdkDirectoryFullPath2); recipeDefinitionPaths.ShouldContain(saveCdkDirectoryFullPath3); // cleanup File.Delete(deploymentManifestFilePath); Assert.False(_fileManager.Exists(deploymentManifestFilePath)); } private async Task<List<string>> GetDeploymentManifestEntries(string deploymentManifestFilePath) { var deploymentProjectPaths = new List<string>(); var manifestFilejsonString = await _fileManager.ReadAllTextAsync(deploymentManifestFilePath); var deploymentManifestModel = JsonConvert.DeserializeObject<DeploymentManifestModel>(manifestFilejsonString); foreach (var entry in deploymentManifestModel.DeploymentProjects) { deploymentProjectPaths.Add(entry.SaveCdkDirectoryRelativePath); } return deploymentProjectPaths; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var deploymentManifestFilePath = Path.Combine(_targetApplicationDirectoryFullPath, "aws-deployments.json"); if (_fileManager.Exists(deploymentManifestFilePath)) { File.Delete(deploymentManifestFilePath); } } _isDisposed = true; } ~DeploymentManifestFileTests() { Dispose(false); } } }
160
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.IO; namespace AWS.Deploy.CLI.Common.UnitTests.Extensions { public static class DirectoryCopyExtension { /// <summary> /// <see cref="https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories"/> /// </summary> public static void CopyTo(this DirectoryInfo dir, string destDirName, bool copySubDirs) { if (!dir.Exists) { throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: {dir.FullName}"); } var dirs = dir.GetDirectories(); Directory.CreateDirectory(destDirName); var files = dir.GetFiles(); foreach (var file in files) { var tempPath = Path.Combine(destDirName, file.Name); file.CopyTo(tempPath, false); } if (copySubDirs) { foreach (var subdir in dirs) { var tempPath = Path.Combine(destDirName, subdir.Name); var subDir = new DirectoryInfo(subdir.FullName); subDir.CopyTo(tempPath, copySubDirs); } } } } }
43
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using AWS.Deploy.CLI.Common.UnitTests.Extensions; namespace AWS.Deploy.CLI.Common.UnitTests.IO { public class TestAppManager { public string GetProjectPath(string path) { var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var sourceTestAppsDir = new DirectoryInfo("testapps"); var tempTestAppsPath = Path.Combine(tempDir, "testapps"); Directory.CreateDirectory(tempTestAppsPath); sourceTestAppsDir.CopyTo(tempTestAppsPath, true); return Path.Combine(tempDir, path); } } }
25
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using AWS.Deploy.Common.IO; using System.Linq; namespace AWS.Deploy.CLI.Common.UnitTests.IO { public class TestDirectoryManager : IDirectoryManager { public readonly HashSet<string> CreatedDirectories = new(); public readonly Dictionary<string, HashSet<string>> AddedFiles = new(); public DirectoryInfo CreateDirectory(string path) { CreatedDirectories.Add(path); return new DirectoryInfo(path); } public DirectoryInfo GetDirectoryInfo(string path) => new DirectoryInfo(path); public string GetRelativePath(string referenceFullPath, string targetFullPath) => Path.GetRelativePath(referenceFullPath, targetFullPath); public string GetAbsolutePath(string referenceFullPath, string targetRelativePath) => Path.GetFullPath(targetRelativePath, referenceFullPath); public string[] GetProjFiles(string path) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public void Delete(string path, bool recursive = false) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public bool ExistsInsideDirectory(string parentDirectoryPath, string childPath) => childPath.Contains(parentDirectoryPath + Path.DirectorySeparatorChar, StringComparison.InvariantCulture); public bool Exists(string path) { return CreatedDirectories.Contains(path); } public bool Exists(string path, string relativeTo) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public string[] GetDirectories(string path, string searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly) => CreatedDirectories.ToArray(); public string[] GetFiles(string path, string searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly) => AddedFiles.ContainsKey(path) ? AddedFiles[path].ToArray() : new string[0]; public bool IsEmpty(string path) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); } }
54
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using AWS.Deploy.Common.IO; namespace AWS.Deploy.CLI.Common.UnitTests.IO { public class TestFileManager : IFileManager { public readonly Dictionary<string, string> InMemoryStore = new Dictionary<string, string>(); public bool Exists(string path) { return InMemoryStore.ContainsKey(path); } public Task<string> ReadAllTextAsync(string path) { var text = InMemoryStore[path]; return Task.FromResult(text); } public async Task<string[]> ReadAllLinesAsync(string path) { return (await ReadAllTextAsync(path)).Split(Environment.NewLine); } public Task WriteAllTextAsync(string filePath, string contents, CancellationToken cancellationToken = default) { InMemoryStore[filePath] = contents; return Task.CompletedTask; } public FileStream OpenRead(string filePath) => throw new NotImplementedException(); public string GetExtension(string filePath) => throw new NotImplementedException(); public long GetSizeInBytes(string filePath) => throw new NotImplementedException(); public bool Exists(string path, string directory) { if (Path.IsPathRooted(path)) { return Exists(path); } else { return Exists(Path.Combine(directory, path)); } } public bool IsFileValidPath(string filePath) => throw new NotImplementedException(); } public static class TestFileManagerExtensions { /// <summary> /// Adds a virtual csproj file with valid xml contents /// </summary> /// <returns> /// Returns the correct full path for <paramref name="relativePath"/> /// </returns> public static string AddEmptyProjectFile(this TestFileManager fileManager, string relativePath) { relativePath = relativePath.Replace('\\', Path.DirectorySeparatorChar); var fullPath = Path.Join(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "c:\\" : "/", relativePath); fileManager.InMemoryStore.Add(fullPath, "<Project Sdk=\"Microsoft.NET.Sdk\"></Project>"); return fullPath; } } }
76
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.Orchestration.Utilities; using Moq; using Xunit; namespace AWS.Deploy.CLI.Common.UnitTests.LocalUserSettings { public class LocalUserSettingsTests { private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; private readonly ILocalUserSettingsEngine _localUserSettingsEngine; private readonly Mock<IEnvironmentVariableManager> _environmentVariableManager; private readonly IDeployToolWorkspaceMetadata _deployToolWorkspaceMetadata; public LocalUserSettingsTests() { _fileManager = new TestFileManager(); _directoryManager = new DirectoryManager(); var targetApplicationPath = Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj"); _environmentVariableManager = new Mock<IEnvironmentVariableManager>(); _environmentVariableManager .Setup(x => x.GetEnvironmentVariable(It.IsAny<string>())) .Returns(() => null); _deployToolWorkspaceMetadata = new DeployToolWorkspaceMetadata(_directoryManager, _environmentVariableManager.Object, _fileManager); _localUserSettingsEngine = new LocalUserSettingsEngine(_fileManager, _directoryManager, _deployToolWorkspaceMetadata); } [Fact] public async Task UpdateLastDeployedStackTest() { var stackName = "WebAppWithDockerFile"; var awsAccountId = "1234567890"; var awsRegion = "us-west-2"; var settingsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".aws-dotnet-deploy", "local-user-settings.json"); await _localUserSettingsEngine.UpdateLastDeployedStack(stackName, stackName, awsAccountId, awsRegion); var userSettings = await _localUserSettingsEngine.GetLocalUserSettings(); Assert.True(_fileManager.Exists(settingsFilePath)); Assert.NotNull(userSettings); Assert.NotNull(userSettings.LastDeployedStacks); Assert.Single(userSettings.LastDeployedStacks); Assert.Equal(awsAccountId, userSettings.LastDeployedStacks[0].AWSAccountId); Assert.Equal(awsRegion, userSettings.LastDeployedStacks[0].AWSRegion); Assert.Single(userSettings.LastDeployedStacks[0].Stacks); Assert.Equal(stackName, userSettings.LastDeployedStacks[0].Stacks[0]); } [Fact] public async Task UpdateLastDeployedStackTest_ExistingStacks() { var stackName = "WebAppWithDockerFile"; var awsAccountId = "1234567890"; var awsRegion = "us-west-2"; var settingsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".aws-dotnet-deploy", "local-user-settings.json"); await _fileManager.WriteAllTextAsync(settingsFilePath, "{\"LastDeployedStacks\": [{\"AWSAccountId\": \"1234567890\",\"AWSRegion\": \"us-west-2\",\"ProjectName\": \"WebApp1\",\"Stacks\": [\"WebApp1\"]}]}"); await _localUserSettingsEngine.UpdateLastDeployedStack(stackName, stackName, awsAccountId, awsRegion); var userSettings = await _localUserSettingsEngine.GetLocalUserSettings(); Assert.True(_fileManager.Exists(settingsFilePath)); Assert.NotNull(userSettings); Assert.NotNull(userSettings.LastDeployedStacks); Assert.Equal(2, userSettings.LastDeployedStacks.Count); Assert.Equal(awsAccountId, userSettings.LastDeployedStacks[1].AWSAccountId); Assert.Equal(awsRegion, userSettings.LastDeployedStacks[1].AWSRegion); Assert.Single(userSettings.LastDeployedStacks[1].Stacks); Assert.Equal(stackName, userSettings.LastDeployedStacks[1].Stacks[0]); } [Fact] public async Task DeleteLastDeployedStackTest() { var stackName = "WebAppWithDockerFile"; var awsAccountId = "1234567890"; var awsRegion = "us-west-2"; var settingsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".aws-dotnet-deploy", "local-user-settings.json"); await _localUserSettingsEngine.UpdateLastDeployedStack(stackName, stackName, awsAccountId, awsRegion); await _localUserSettingsEngine.DeleteLastDeployedStack(stackName, stackName, awsAccountId, awsRegion); var userSettings = await _localUserSettingsEngine.GetLocalUserSettings(); Assert.True(_fileManager.Exists(settingsFilePath)); Assert.NotNull(userSettings); Assert.NotNull(userSettings.LastDeployedStacks); Assert.Single(userSettings.LastDeployedStacks); Assert.Equal(awsAccountId, userSettings.LastDeployedStacks[0].AWSAccountId); Assert.Equal(awsRegion, userSettings.LastDeployedStacks[0].AWSRegion); } [Fact] public async Task CleanOrphanStacksTest() { var stackName = "WebAppWithDockerFile"; var awsAccountId = "1234567890"; var awsRegion = "us-west-2"; var settingsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".aws-dotnet-deploy", "local-user-settings.json"); await _localUserSettingsEngine.UpdateLastDeployedStack(stackName, stackName, awsAccountId, awsRegion); await _localUserSettingsEngine.CleanOrphanStacks(new List<string> { "WebAppWithDockerFile1" }, stackName, awsAccountId, awsRegion); var userSettings = await _localUserSettingsEngine.GetLocalUserSettings(); Assert.True(_fileManager.Exists(settingsFilePath)); Assert.NotNull(userSettings); Assert.NotNull(userSettings.LastDeployedStacks); Assert.Single(userSettings.LastDeployedStacks); Assert.Equal(awsAccountId, userSettings.LastDeployedStacks[0].AWSAccountId); Assert.Equal(awsRegion, userSettings.LastDeployedStacks[0].AWSRegion); // Attempt to clean orphans again. This is to make sure if the underlying stacks array collection is null we don't throw an exception. await _localUserSettingsEngine.CleanOrphanStacks(new List<string> { "WebAppWithDockerFile1" }, stackName, awsAccountId, awsRegion); userSettings = await _localUserSettingsEngine.GetLocalUserSettings(); Assert.True(_fileManager.Exists(settingsFilePath)); Assert.NotNull(userSettings); Assert.NotNull(userSettings.LastDeployedStacks); Assert.Single(userSettings.LastDeployedStacks); Assert.Equal(awsAccountId, userSettings.LastDeployedStacks[0].AWSAccountId); Assert.Equal(awsRegion, userSettings.LastDeployedStacks[0].AWSRegion); } } }
137
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Data; using Moq; using Should; using Xunit; namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { public class AppRunnerOptionSettingItemValidationTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public AppRunnerOptionSettingItemValidationTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Theory] [InlineData("abcdef1234", true)] [InlineData("abc123def45", true)] [InlineData("abc12-34-56_XZ", true)] [InlineData("abc_@1323", false)] //invalid character "@" [InlineData("123*&$_abc_", false)] //invalid characters [InlineData("-abc123def45", false)] // does not start with a letter or a number public async Task AppRunnerServiceNameValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); // 4 to 40 letters (uppercase and lowercase), numbers, hyphens, and underscores are allowed. optionSettingItem.Validators.Add(GetRegexValidatorConfig("^([A-Za-z0-9][A-Za-z0-9_-]{3,39})$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("arn:aws:iam::123456789012:role/S3Access", true)] [InlineData("arn:aws-cn:iam::123456789012:role/service-role/MyServiceRole", true)] [InlineData("arn:aws:IAM::123456789012:role/S3Access", false)] //invalid uppercase IAM [InlineData("arn:aws:iam::1234567890124354:role/S3Access", false)] //invalid account ID [InlineData("arn:aws-new:iam::123456789012:role/S3Access", false)] // invalid aws partition [InlineData("arn:aws:iam::123456789012:role", false)] // missing resorce path public async Task RoleArnValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("arn:(aws|aws-us-gov|aws-cn|aws-iso|aws-iso-b):iam::[0-9]{12}:(role|role/service-role)/[\\w+=,.@\\-/]{1,1000}")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", true)] [InlineData("arn:aws-us-gov:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", true)] [InlineData("arn:aws:kms:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", false)] // missing region [InlineData("arn:aws:kms:us-east-1:11112222:key/1234abcd-12ab-34cd-56ef-1234567890ab", false)] // invalid account ID [InlineData("arn:aws:kms:us-west-2:111122223333:key", false)] // missing resource path [InlineData("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab", false)] // invalid key-id structure public async Task KmsKeyArnValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("arn:aws(-[\\w]+)*:kms:[a-z\\-]+-[0-9]{1}:[0-9]{12}:key/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")); await Validate(optionSettingItem, value, isValid); } private async Task Validate<T>(OptionSettingItem optionSettingItem, T value, bool isValid) { ValidationFailedException exception = null; try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, value); } catch (ValidationFailedException e) { exception = e; } if (isValid) exception.ShouldBeNull(); else exception.ShouldNotBeNull(); } private OptionSettingItemValidatorConfig GetRegexValidatorConfig(string regex) { var regexValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, Configuration = new RegexValidator { Regex = regex } }; return regexValidatorConfig; } } }
109
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Should; using Xunit; namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { public class BlazorWasmOptionSettingItemValidationTest { private readonly IOptionSettingHandler _optionSettingHandler; private readonly IServiceProvider _serviceProvider; public BlazorWasmOptionSettingItemValidationTest() { var mockServiceProvider = new Mock<IServiceProvider>(); _serviceProvider = mockServiceProvider.Object; _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider)); } [Theory] [InlineData("https://www.abc.com/")] [InlineData("http://www.abc.com/")] [InlineData("http://abc.com")] [InlineData("http://abc.com.xyz")] [InlineData("http://abc.com/def")] [InlineData("http://abc.com//def")] [InlineData("http://api-uri")] [InlineData("customScheme://www.abc.com")] [InlineData("")] // Special case - It is possible that a URI specific option setting item is optional and can be null or empty. public async Task BackendApiUriValidationTests_ValidUri(string uri) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetUriValidatorConfig()); await Validate(optionSettingItem, uri, true); } [Theory] [InlineData("//")] [InlineData("/")] [InlineData("abc.com")] [InlineData("abc")] [InlineData("http:www.abc.com")] [InlineData("http:/www.abc.com")] [InlineData("http//:www.abc.com")] [InlineData("://www.abc.com")] [InlineData("www.abc.com")] public async Task BackendApiUriValidationTests_InvalidUri(string uri) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetUriValidatorConfig()); await Validate(optionSettingItem, uri, false); } [Theory] [InlineData("/*", true)] [InlineData("/api/*", true)] [InlineData("/api/myResource", true)] [InlineData("/", false)] [InlineData("", false)] [InlineData("abc", false)] public async Task BackendApiResourcePathValidationTests_InvalidUri(string resourcePath, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("^/\\S+$")); await Validate(optionSettingItem, resourcePath, isValid); } private OptionSettingItemValidatorConfig GetUriValidatorConfig() { var rangeValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Uri, }; return rangeValidatorConfig; } private OptionSettingItemValidatorConfig GetRegexValidatorConfig(string regex) { var regexValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, Configuration = new RegexValidator { Regex = regex } }; return regexValidatorConfig; } private async Task Validate<T>(OptionSettingItem optionSettingItem, T value, bool isValid) { ValidationFailedException exception = null; try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, value); } catch (ValidationFailedException e) { exception = e; } if (isValid) exception.ShouldBeNull(); else exception.ShouldNotBeNull(); } } }
119
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Xunit; namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { /// <summary> /// Tests for the recipe-level validation between the Dockerfile path and /// docker execution recipe options, <see cref="DockerfilePathValidator"/> /// </summary> public class DockerfilePathValidationTests { private readonly IServiceProvider _serviceProvider; private readonly RecipeDefinition _recipeDefinition; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; public DockerfilePathValidationTests() { _serviceProvider = new Mock<IServiceProvider>().Object; _directoryManager = new TestDirectoryManager(); _fileManager = new TestFileManager(); _recipeDefinition = new Mock<RecipeDefinition>( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<DeploymentTypes>(), It.IsAny<DeploymentBundleTypes>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()).Object; } public static IEnumerable<object[]> DockerfilePathTestData => new List<object[]>() { // Dockerfile path | Docker execution directory | expected to be valid? // We generate a Dockerfile later if one isn't specified, so not invalid at this point new object[] { "", Path.Combine("C:", "project"), true }, // We compute the execution directory later if one isn't specified, so not invalid at this point new object[] { Path.Combine("C:", "project", "Dockerfile"), "", true }, // Dockerfile is in the execution directory, with absolute paths new object[] { Path.Combine("C:", "project", "Dockerfile"), Path.Combine("C:", "project"), true }, // Dockerfile is in the execution directory, with relative paths new object[] { Path.Combine(".", "Dockerfile"), Path.Combine("."), true }, // Dockerfile is further down in execution directory, with absolute paths new object[] { Path.Combine("C:", "project", "child", "Dockerfile"), Path.Combine("C:", "project"), true }, // Dockerfile is further down in execution directory, with relative paths new object[] { Path.Combine(".", "child", "Dockerfile"), Path.Combine("."), true }, // Dockerfile is outside of the execution directory, which is invalid new object[] { Path.Combine("C:", "project", "Dockerfile"), Path.Combine("C:", "foo"), false } }; /// <summary> /// Tests for <see cref="DockerfilePathValidator"/>, which validates the relationship /// between a Dockerfile path and the Docker execution directory /// </summary> [Theory] [MemberData(nameof(DockerfilePathTestData))] public async Task DockerfilePathValidationHelperAsync(string dockerfilePath, string dockerExecutionDirectory, bool expectedToBeValid) { var projectPath = Path.Combine("C:", "project", "test.csproj"); var options = new List<OptionSettingItem>() { new OptionSettingItem("DockerfilePath", "", "", "") }; var projectDefintion = new ProjectDefinition(null, projectPath, "", ""); var recommendation = new Recommendation(_recipeDefinition, projectDefintion, 100, new Dictionary<string, object>()); var validator = new DockerfilePathValidator(_directoryManager, _fileManager); recommendation.DeploymentBundle.DockerExecutionDirectory = dockerExecutionDirectory; recommendation.DeploymentBundle.DockerfilePath = dockerfilePath; // "Write" to the TestFileManager so that "Exists" returns true if (Path.IsPathRooted(dockerfilePath)) await _fileManager.WriteAllTextAsync(dockerfilePath, ""); else await _fileManager.WriteAllTextAsync(Path.Combine(recommendation.GetProjectDirectory(), dockerfilePath), ""); var validationResult = await validator.Validate(recommendation, null); Assert.Equal(expectedToBeValid, validationResult.IsValid); } } }
107
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using Amazon.CloudControlApi.Model; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Should; using Xunit; using ResourceNotFoundException = Amazon.CloudControlApi.Model.ResourceNotFoundException; using Task = System.Threading.Tasks.Task; using System.Collections.Generic; using Amazon.EC2.Model; namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { public class ECSFargateOptionSettingItemValidationTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly IServiceProvider _serviceProvider; private readonly IDirectoryManager _directoryManager; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly RecipeDefinition _recipe; private readonly Recommendation _recommendation; public ECSFargateOptionSettingItemValidationTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _directoryManager = new TestDirectoryManager(); var mockServiceProvider = new Mock<IServiceProvider>(); mockServiceProvider.Setup(x => x.GetService(typeof(IDirectoryManager))).Returns(_directoryManager); mockServiceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _serviceProvider = mockServiceProvider.Object; _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider)); _recipe = new RecipeDefinition("Fargate", "0.1", "Fargate", DeploymentTypes.CdkProject, DeploymentBundleTypes.Container, "", "", "", "", ""); _recommendation = new Recommendation(_recipe, null, 100, new Dictionary<string, object>()); } [Theory] [InlineData("arn:aws:ecs:us-east-1:012345678910:cluster/test", true)] [InlineData("arn:aws-cn:ecs:us-east-1:012345678910:cluster/test", true)] [InlineData("arb:aws:ecs:us-east-1:012345678910:cluster/test", false)] //typo arb instean of arn [InlineData("arn:aws:ecs:us-east-1:01234567891:cluster/test", false)] //invalid account ID [InlineData("arn:aws:ecs:us-east-1:012345678910:cluster", false)] //no cluster name [InlineData("arn:aws:ecs:us-east-1:012345678910:fluster/test", false)] //fluster instead of cluster public async Task ClusterArnValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("arn:[^:]+:ecs:[^:]*:[0-9]{12}:cluster/.+")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("abcdef1234", true)] [InlineData("abc123def45", true)] [InlineData("abc12-34-56-XZ", true)] [InlineData("abc_@1323", false)] //invalid characters [InlineData("123*&$abc", false)] //invalid characters public async Task NewClusterNameValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); //up to 255 letters(uppercase and lowercase), numbers, underscores, and hyphens are allowed. optionSettingItem.Validators.Add(GetRegexValidatorConfig("^([A-Za-z0-9-]{1,255})$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("abcdef1234", true)] [InlineData("abc123def45", true)] [InlineData("abc12-34-56_XZ", true)] [InlineData("abc_@1323", false)] //invalid character "@" [InlineData("123*&$_abc_", false)] //invalid characters public async Task ECSServiceNameValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); // Up to 255 letters (uppercase and lowercase), numbers, hyphens, and underscores are allowed. optionSettingItem.Validators.Add(GetRegexValidatorConfig("^([A-Za-z0-9_-]{1,255})$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData(5, true)] [InlineData(10, true)] [InlineData(-1, false)] [InlineData(6000, false)] [InlineData(1000, true)] public async Task DesiredCountValidationTests(int value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRangeValidatorConfig(1, 5000)); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData(5, false)] [InlineData(6, true)] public async Task HealthCheckInterval(int value, bool isValid) { var healthCheckInterval = new OptionSettingItem("healthCheckInterval", "fullyQualifiedId", "name", "description"); var healthCheckTimeout = new OptionSettingItem("healthCheckTimeout", "fullyQualifiedId", "name", "description"); _recipe.OptionSettings.Add(healthCheckInterval); _recipe.OptionSettings.Add(healthCheckTimeout); await _optionSettingHandler.SetOptionSettingValue(_recommendation, healthCheckTimeout, 5, true); healthCheckInterval.Validators.Add(GetComparisonValidatorConfig(ComparisonValidatorOperation.GreaterThan, "healthCheckTimeout")); await Validate(healthCheckInterval, value, isValid); } [Theory] [InlineData("arn:aws:iam::123456789012:user/JohnDoe", true)] [InlineData("arn:aws:iam::123456789012:user/division_abc/subdivision_xyz/JaneDoe", true)] [InlineData("arn:aws:iam::123456789012:group/Developers", true)] [InlineData("arn:aws:iam::123456789012:role/S3Access", true)] [InlineData("arn:aws:IAM::123456789012:role/S3Access", false)] //invalid uppercase IAM [InlineData("arn:aws:iam::1234567890124354:role/S3Access", false)] //invalid account ID public async Task RoleArnValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("arn:.+:iam::[0-9]{12}:.+")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("vpc-0123abcd", true)] [InlineData("vpc-ab12bf49", true)] [InlineData("vpc-ffffffffaaaabbbb1", true)] [InlineData("vpc-12345678", true)] [InlineData("ipc-456678", false)] //invalid prefix [InlineData("vpc-zzzzzzzz", false)] //invalid character z [InlineData("vpc-ffffffffaaaabbbb12", false)] //suffix length greater than 17 public async Task VpcIdValidationTests(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); //must start with the \"vpc-\" prefix, //followed by either 8 or 17 characters consisting of digits and letters(lower-case) from a to f. optionSettingItem.Validators.Add(GetRegexValidatorConfig("^vpc-([0-9a-f]{8}|[0-9a-f]{17})$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("arn:aws:elasticloadbalancing:us-east-1:012345678910:loadbalancer/my-load-balancer", true)] [InlineData("arn:aws:elasticloadbalancing:us-east-1:012345678910:loadbalancer/app/my-load-balancer", true)] [InlineData("arn:aws:elasticloadbalancing:012345678910:elasticloadbalancing:loadbalancer/my-load-balancer", false)] //missing region [InlineData("arn:aws:elasticloadbalancing:012345678910:elasticloadbalancing:loadbalancer", false)] //missing resource path [InlineData("arn:aws:elasticloadbalancing:01234567891:elasticloadbalancing:loadbalancer", false)] //11 digit account ID public async Task LoadBalancerArnValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("arn:[^:]+:elasticloadbalancing:[^:]*:[0-9]{12}:loadbalancer/.+")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("/", true)] [InlineData("/Api/*", true)] [InlineData("/Api/Path/&*$-/@", true)] [InlineData("Api/Path", false)] // does not start with '/' [InlineData("/Api/Path/<dsd<>", false)] // contains invalid character '<' and '>' public async Task ListenerConditionPathPatternValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("^/[a-zA-Z0-9*?&_\\-.$/~\"'@:+]{0,127}$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("myrepo123", true)] [InlineData("myrepo123.a/b", true)] [InlineData("MyRepo", false)] // cannot contain uppercase letters [InlineData("myrepo123@", false)] // cannot contain @ [InlineData("myrepo123.a//b", false)] // cannot contain consecutive slashes. [InlineData("aa", true)] [InlineData("a", false)] //length cannot be less than 2 [InlineData("", false)] // length cannot be less than 2 [InlineData("reporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporeporepo", false)] // cannot be greater than 256 characters public async Task ECRRepositoryNameValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("^(?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*$")); optionSettingItem.Validators.Add(GetStringLengthValidatorConfig(2, 256)); await Validate(optionSettingItem, value, isValid); } [Fact] public async Task ECSClusterNameValidationTest_Valid() { _awsResourceQueryer.Setup(x => x.GetCloudControlApiResource(It.IsAny<string>(), It.IsAny<string>())).Throws(new ResourceQueryException(DeployToolErrorCode.ResourceQuery, "", new ResourceNotFoundException(""))); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetExistingResourceValidatorConfig("AWS::ECS::Cluster")); await Validate(optionSettingItem, "WebApp1", true); } [Fact] public async Task VpcIdHasSubnetsInDifferentAZs_DifferentZones_Valid() { _awsResourceQueryer.Setup(x => x.DescribeSubnets(It.IsAny<string>())).ReturnsAsync( new List<Amazon.EC2.Model.Subnet> { new Amazon.EC2.Model.Subnet { AvailabilityZoneId = "AZ1"}, new Amazon.EC2.Model.Subnet { AvailabilityZoneId = "AZ2"} }); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetVPCSubnetsInDifferentAZsValidatorConfig()); await Validate(optionSettingItem, "vpc-1234abcd", true); } [Fact] public async Task VpcIdHasSubnetsInDifferentAZs_SingleSubnet_Invalid() { _awsResourceQueryer.Setup(x => x.DescribeSubnets(It.IsAny<string>())).ReturnsAsync( new List<Amazon.EC2.Model.Subnet> { new Amazon.EC2.Model.Subnet { AvailabilityZoneId = "AZ1"} }); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetVPCSubnetsInDifferentAZsValidatorConfig()); await Validate(optionSettingItem, "vpc-1234abcd", false); } [Fact] public async Task VpcIdHasSubnetsInDifferentAZs_SingleZone_Invalid() { _awsResourceQueryer.Setup(x => x.DescribeSubnets(It.IsAny<string>())).ReturnsAsync( new List<Amazon.EC2.Model.Subnet> { new Amazon.EC2.Model.Subnet { AvailabilityZoneId = "AZ1"}, new Amazon.EC2.Model.Subnet { AvailabilityZoneId = "AZ1"} }); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetVPCSubnetsInDifferentAZsValidatorConfig()); await Validate(optionSettingItem, "vpc-1234abcd", false); } [Fact] public async Task ECSClusterNameValidationTest_Invalid() { var resource = new ResourceDescription { Identifier = "WebApp1" }; _awsResourceQueryer.Setup(x => x.GetCloudControlApiResource(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(resource); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetExistingResourceValidatorConfig("AWS::ECS::Cluster")); await Validate(optionSettingItem, "WebApp1", false); } [Theory] [InlineData("", true)] [InlineData("--build-arg arg=val --no-cache", true)] [InlineData("-t name:tag", false)] [InlineData("--tag name:tag", false)] [InlineData("-f file", false)] [InlineData("--file file", false)] public async Task DockerBuildArgsValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.DockerBuildArgs }); await Validate(optionSettingItem, value, isValid); } [Fact] public async Task DockerExecutionDirectory_AbsoluteExists() { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.DirectoryExists, }); _directoryManager.CreateDirectory(Path.Join("C:", "project")); await Validate(optionSettingItem, Path.Join("C:", "project"), true); } [Fact] public async Task DockerExecutionDirectory_AbsoluteDoesNotExist() { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.DirectoryExists, }); await Validate(optionSettingItem, Path.Join("C:", "other_project"), false); } /// <summary> /// Tests the relationship between an explicit VPC ID, whether "Default VPC" is checked, /// and any security groups that are specified. /// </summary> /// <param name="vpcId">selected VPC Id</param> /// <param name="isDefaultVpcSelected">whether the "Default VPC" radio is selected</param> /// <param name="selectedSecurityGroups">selected security groups</param> /// <param name="isValid">Whether or not the test case is expected to be valid</param> [Theory] // The Console Service recipe uses a comma-seperated string of security groups [InlineData("vpc1", true, "", true)] // Valid because the security groups are optional [InlineData("vpc1", true, "sg-1a,sg-1b", true)] // Valid because the security group does belong to the default VPC [InlineData("vpc1", true, "sg-1a,sg-2a", false)] // Invalid because the security group does not belong to the default VPC [InlineData("vpc2", false, "sg-2a", true)] // Valid because the security group does belong to the non-default VPC [InlineData("vpc2", false, "sg-1a", false)] // Invalid because the security group does not belong to the non-default VPC [InlineData("vpc2", true, "sg-1a", true)] // Valid because "true" for IsDefaultVPC overrides the "vpc2", so the security group matches [InlineData("vpc2", true, "sg-2a", false)] // Invalid because "true" for IsDefaultVPC overrides the "vpc2", so the security group does not match // // The ASP.NET on Fargate recipe uses a JSON list of security groups (these are same cases from above) // [InlineData("vpc1", true, "[]", true)] [InlineData("vpc1", true, "[\"sg-1a\",\"sg-1b\"]", true)] [InlineData("vpc1", true, "[\"sg-1a\",\"sg-2a\"]", false)] [InlineData("vpc2", false, "[\"sg-2a\"]", true)] [InlineData("vpc2", false, "[\"sg-1a\"]", false)] [InlineData("vpc2", true, "[\"sg-1a\"]", true)] [InlineData("vpc2", true, "[\"sg-2a\"]", false)] public async Task VpcId_DefaultVpc_SecurityGroups_Relationship(string vpcId, bool isDefaultVpcSelected, object selectedSecurityGroups, bool isValid) { PrepareMockVPCsAndSecurityGroups(_awsResourceQueryer); var (vpcIdOption, vpcDefaultOption, securityGroupsOption) = PrepareECSVpcOptions(); securityGroupsOption.Validators.Add(GetSecurityGroupsInVpcValidatorConfig(_awsResourceQueryer, _optionSettingHandler)); await _optionSettingHandler.SetOptionSettingValue(_recommendation, vpcIdOption, vpcId); await _optionSettingHandler.SetOptionSettingValue(_recommendation, vpcDefaultOption, isDefaultVpcSelected); await Validate(securityGroupsOption, selectedSecurityGroups, isValid); } private OptionSettingItemValidatorConfig GetRegexValidatorConfig(string regex) { var regexValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, Configuration = new RegexValidator { Regex = regex } }; return regexValidatorConfig; } private OptionSettingItemValidatorConfig GetExistingResourceValidatorConfig(string type) { var existingResourceValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.ExistingResource, Configuration = new ExistingResourceValidator(_awsResourceQueryer.Object) { ResourceType = type } }; return existingResourceValidatorConfig; } private OptionSettingItemValidatorConfig GetVPCSubnetsInDifferentAZsValidatorConfig() { var vpcSubnetsInDifferentAZsValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.VPCSubnetsInDifferentAZs, Configuration = new VPCSubnetsInDifferentAZsValidator(_awsResourceQueryer.Object) }; return vpcSubnetsInDifferentAZsValidatorConfig; } private OptionSettingItemValidatorConfig GetRangeValidatorConfig(int min, int max) { var rangeValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = min, Max = max } }; return rangeValidatorConfig; } private OptionSettingItemValidatorConfig GetComparisonValidatorConfig(ComparisonValidatorOperation operation, string settingId) { var comparisonValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Comparison, Configuration = new ComparisonValidator(_optionSettingHandler) { Operation = operation, SettingId = settingId } }; return comparisonValidatorConfig; } private OptionSettingItemValidatorConfig GetStringLengthValidatorConfig(int minLength, int maxLength) { var stringLengthValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.StringLength, Configuration = new StringLengthValidator { MinLength = minLength, MaxLength = maxLength } }; return stringLengthValidatorConfig; } private async Task Validate<T>(OptionSettingItem optionSettingItem, T value, bool isValid) { ValidationFailedException exception = null; try { await _optionSettingHandler.SetOptionSettingValue(_recommendation, optionSettingItem, value); } catch (ValidationFailedException e) { exception = e; } if (isValid) exception.ShouldBeNull(); else exception.ShouldNotBeNull(); } /// <summary> /// Prepares a <see cref="SecurityGroupsInVpcValidator"/> for testing /// </summary> private OptionSettingItemValidatorConfig GetSecurityGroupsInVpcValidatorConfig(Mock<IAWSResourceQueryer> awsResourceQueryer, IOptionSettingHandler optionSettingHandler) { var validator = new SecurityGroupsInVpcValidator(awsResourceQueryer.Object, optionSettingHandler); validator.VpcId = "Vpc.VpcId"; validator.IsDefaultVpcOptionSettingId = "Vpc.IsDefault"; return new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.SecurityGroupsInVpc, Configuration = validator }; } /// <summary> /// Mocks the provided <see cref="IAWSResourceQueryer"> to return the following /// 1. Default vpc1 with security groups sg-1a and sg-1b /// 2. Non-default vpc2 with security groups sg-2a and sg-2b /// </summary> /// <param name="awsResourceQueryer">Mocked AWS Resource Queryer</param> private void PrepareMockVPCsAndSecurityGroups(Mock<IAWSResourceQueryer> awsResourceQueryer) { awsResourceQueryer.Setup(x => x.GetListOfVpcs()).ReturnsAsync( new List<Vpc> { new Vpc { VpcId = "vpc1", IsDefault = true }, new Vpc { VpcId = "vpc2"} }); awsResourceQueryer.Setup(x => x.DescribeSecurityGroups("vpc1")).ReturnsAsync( new List<SecurityGroup> { new SecurityGroup { GroupId = "sg-1a", VpcId = "vpc1" }, new SecurityGroup { GroupId = "sg-1b", VpcId = "vpc1" } }); awsResourceQueryer.Setup(x => x.DescribeSecurityGroups("vpc2")).ReturnsAsync( new List<SecurityGroup> { new SecurityGroup { GroupId = "sg-2a", VpcId = "vpc2" }, new SecurityGroup { GroupId = "sg-2a", VpcId = "vpc2" } }); awsResourceQueryer.Setup(x => x.GetDefaultVpc()).ReturnsAsync(new Vpc { VpcId = "vpc1", IsDefault = true }); } /// <summary> /// Prepares VPC-related options that match the ECS Fargate recipes for testing /// </summary> /// <returns>The "Vpc.VpcId" option, the "Vpc.IsDefault" option, and the "ECSServiceSecurityGroups" option</returns> private (OptionSettingItem, OptionSettingItem, OptionSettingItem) PrepareECSVpcOptions() { var vpcIdOption = new OptionSettingItem("VpcId", "Vpc.VpcId", "name", "description"); var vpcDefaultOption = new OptionSettingItem("IsDefault", "Vpc.IsDefault", "name", "description"); var ecsServiceSecurityGroupsOption = new OptionSettingItem("ECSServiceSecurityGroups", "ECSServiceSecurityGroups", "name", ""); var vpc = new OptionSettingItem("Vpc", "Vpc", "", ""); vpc.ChildOptionSettings.Add(vpcIdOption); vpc.ChildOptionSettings.Add(vpcDefaultOption); _recipe.OptionSettings.Add(vpc); return (vpcIdOption, vpcDefaultOption, ecsServiceSecurityGroupsOption); } } }
499
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.EC2; using Amazon.EC2.Model; using Amazon.ElasticBeanstalk.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Should; using Xunit; namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { public class ElasticBeanStalkOptionSettingItemValidationTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public ElasticBeanStalkOptionSettingItemValidationTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Theory] [InlineData("12345sas", true)] [InlineData("435&*abc@3123", true)] [InlineData("abc/123/#", false)] // invalid character forward slash(/) public async Task ApplicationNameValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); //can contain up to 100 Unicode characters, not including forward slash (/). optionSettingItem.Validators.Add(GetRegexValidatorConfig("^[^/]{1,100}$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("Sun:00:00", true)] [InlineData("sun:00:00", false)] [InlineData("Suns:00:00", false)] [InlineData("Mon:23:59", true)] [InlineData("Mon:24:00", false)] [InlineData("Mon:00:60", false)] [InlineData("", false)] [InlineData("test", false)] public async Task PreferredStartTimeValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); // valid examples are in the 'day:hour:minute' pattern such as 'Sun:00:00' optionSettingItem.Validators.Add(GetRegexValidatorConfig("^(Mon|Tue|Wed|Thu|Fri|Sat|Sun):(0[0-9]|1\\d|2[0-3]):(0[0-9]|1\\d|2\\d|3\\d|4\\d|5\\d)$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("abc-123", true)] [InlineData("abc-ABC-123-xyz", true)] [InlineData("abc", false)] // invalid length less than 4 characters. [InlineData("-12-abc", false)] // invalid character leading hyphen (-) public async Task EnvironmentNameValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); // Must be from 4 to 40 characters in length. The name can contain only letters, numbers, and hyphens. // It can't start or end with a hyphen. optionSettingItem.Validators.Add(GetRegexValidatorConfig("^[a-zA-Z0-9][a-zA-Z0-9-]{2,38}[a-zA-Z0-9]$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("arn:aws:iam::123456789012:user/JohnDoe", true)] [InlineData("arn:aws:iam::123456789012:user/division_abc/subdivision_xyz/JaneDoe", true)] [InlineData("arn:aws:iam::123456789012:group/Developers", true)] [InlineData("arn:aws:iam::123456789012:role/S3Access", true)] [InlineData("arn:aws:IAM::123456789012:role/S3Access", false)] //invalid uppercase IAM [InlineData("arn:aws:iam::1234567890124354:role/S3Access", false)] //invalid account ID public async Task IAMRoleArnValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("arn:.+:iam::[0-9]{12}:.+")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("abcd1234", true)] [InlineData("abc 1234 xyz", true)] [InlineData(" abc 123-xyz", false)] //leading space [InlineData(" 123 abc-456 ", false)] //leading and trailing space public async Task EC2KeyPairValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); // It allows all ASCII characters but without leading and trailing spaces optionSettingItem.Validators.Add(GetRegexValidatorConfig("^(?! ).+(?<! )$")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("arn:aws:elasticbeanstalk:us-east-1:123456789012:platform/MyPlatform", true)] [InlineData("arn:aws-cn:elasticbeanstalk:us-west-1:123456789012:platform/MyPlatform", true)] [InlineData("arn:aws:elasticbeanstalk:eu-west-1:123456789012:platform/MyPlatform/v1.0", true)] [InlineData("arn:aws:elasticbeanstalk:us-west-2::platform/MyPlatform/v1.0", true)] [InlineData("arn:aws:elasticbeanstalk:us-east-1:123456789012:platform/", false)] //no resource path [InlineData("arn:aws:elasticbeanstack:eu-west-1:123456789012:platform/MyPlatform", false)] //Typo elasticbeanstack instead of elasticbeanstalk public async Task ElasticBeanstalkPlatformArnValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("arn:[^:]+:elasticbeanstalk:[^:]+:[^:]*:platform/.+")); await Validate(optionSettingItem, value, isValid); } [Theory] [InlineData("PT10M", true)] [InlineData("PT1H", true)] [InlineData("PT25S", true)] [InlineData("PT1H20M30S", true)] [InlineData("invalid", false)] [InlineData("PTB1H20M30S", false)] public async Task ElasticBeanstalkRollingUpdatesPauseTime(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("^P([0-9]+(?:[,\\.][0-9]+)?Y)?([0-9]+(?:[,\\.][0-9]+)?M)?([0-9]+(?:[,\\.][0-9]+)?D)?(?:T([0-9]+(?:[,\\.][0-9]+)?H)?([0-9]+(?:[,\\.][0-9]+)?M)?([0-9]+(?:[,\\.][0-9]+)?S)?)?$")); await Validate(optionSettingItem, value, isValid); } [Fact] public async Task ExistingApplicationNameValidationTest_Valid() { _awsResourceQueryer.Setup(x => x.ListOfElasticBeanstalkApplications(It.IsAny<string>())).ReturnsAsync(new List<ApplicationDescription> { }); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetExistingResourceValidatorConfig("AWS::ElasticBeanstalk::Application")); await Validate(optionSettingItem, "WebApp1", true); } [Fact] public async Task ExistingApplicationNameValidationTest_Invalid() { _awsResourceQueryer.Setup(x => x.ListOfElasticBeanstalkApplications(It.IsAny<string>())).ReturnsAsync(new List<ApplicationDescription> { new ApplicationDescription { ApplicationName = "WebApp1" } }); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetExistingResourceValidatorConfig("AWS::ElasticBeanstalk::Application")); await Validate(optionSettingItem, "WebApp1", false); } [Fact] public async Task ExistingEnvironmentNameValidationTest_Valid() { _awsResourceQueryer.Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<EnvironmentDescription> { }); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetExistingResourceValidatorConfig("AWS::ElasticBeanstalk::Environment")); await Validate(optionSettingItem, "WebApp1", true); } [Fact] public async Task ExistingEnvironmentNameValidationTest_Invalid() { _awsResourceQueryer.Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<EnvironmentDescription> { new EnvironmentDescription { EnvironmentName = "WebApp1" } }); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetExistingResourceValidatorConfig("AWS::ElasticBeanstalk::Environment")); await Validate(optionSettingItem, "WebApp1", false); } /// <summary> /// Validates that <see cref="InstanceTypeValidator"/> treats an instance type as /// invalid when DescribeInstanceType is mocked to return an InstanceTypeInfo instance /// </summary> [Fact] public async Task EC2InstanceType_Valid() { var validInstanceType = "m5.large"; _awsResourceQueryer.Setup(x => x.DescribeInstanceType( It.Is<string>(rawInstanceType => rawInstanceType.Equals(validInstanceType)))) .ReturnsAsync(new InstanceTypeInfo()); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.InstanceType }); await Validate(optionSettingItem, validInstanceType, true); } /// <summary> /// Validates that <see cref="InstanceTypeValidator"/> treats an instance type as /// invalid when DescribeInstanceType is mocked to return null /// </summary> [Fact] public async Task EC2InstanceType_Invalid() { var invalidInstanceType = "m5.superlarge"; _awsResourceQueryer.Setup(x => x.DescribeInstanceType( It.Is<string>(rawInstanceType => rawInstanceType.Equals(invalidInstanceType)))) .ReturnsAsync(() => null); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.InstanceType }); await Validate(optionSettingItem, invalidInstanceType, false); } private OptionSettingItemValidatorConfig GetExistingResourceValidatorConfig(string type) { var existingResourceValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.ExistingResource, Configuration = new ExistingResourceValidator(_awsResourceQueryer.Object) { ResourceType = type } }; return existingResourceValidatorConfig; } [Theory] [InlineData("", true)] [InlineData("--no-restore --nologo --framework net6.0", true)] [InlineData("-o dir", false)] // -o or --output is reserved by the deploy tool [InlineData("--output dir", false)] [InlineData("-c Release", false)] // -c or --configuration is controlled by DotnetPublishBuildConfiguration instead [InlineData("--configuration Release", false)] [InlineData("--self-contained true", false)] // --self-contained is controlled by SelfContainedBuild instead [InlineData("--no-self-contained", false)] public async Task DotnetPublishArgsValidationTest(string value, bool isValid) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.DotnetPublishArgs }); await Validate(optionSettingItem, value, isValid); } private OptionSettingItemValidatorConfig GetRegexValidatorConfig(string regex) { var regexValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, Configuration = new RegexValidator { Regex = regex } }; return regexValidatorConfig; } private OptionSettingItemValidatorConfig GetRangeValidatorConfig(int min, int max) { var rangeValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = min, Max = max } }; return rangeValidatorConfig; } private async Task Validate<T>(OptionSettingItem optionSettingItem, T value, bool isValid) { ValidationFailedException exception = null; try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, value); } catch (ValidationFailedException e) { exception = e; } if (isValid) exception.ShouldBeNull(); else exception.ShouldNotBeNull(); } } }
294
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Should; using Xunit; using Xunit.Abstractions; // Justification: False Positives with assertions, also test class // ReSharper disable PossibleNullReferenceException namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { /// <summary> /// Tests for the interaction between <see cref="OptionSettingItem.SetValueOverride"/> /// and <see cref="IOptionSettingItemValidator"/> /// </summary> public class OptionSettingsItemValidationTests { private readonly ITestOutputHelper _output; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public OptionSettingsItemValidationTests(ITestOutputHelper output) { _output = output; _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Theory] [InlineData("")] [InlineData("-10")] [InlineData("100")] public async Task InvalidInputInMultipleValidatorsThrowsException(string invalidValue) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Required }, new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = 7, Max = 10 } } } }; ValidationFailedException exception = null; // ACT try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, invalidValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldNotBeNull(); _output.WriteLine(exception.Message); } [Fact] public async Task InvalidInputInSingleValidatorThrowsException() { var invalidValue = "lowercase_only"; var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, Configuration = new RegexValidator { Regex = "^[A-Z]*$" } } } }; ValidationFailedException exception = null; // ACT try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, invalidValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldNotBeNull(); exception.Message.ShouldContain("[A-Z]*"); } [Fact] public async Task ValidInputDoesNotThrowException() { var validValue = 8; var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = 7, Max = 10 } }, new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Required } } }; ValidationFailedException exception = null; // ACT try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, validValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldBeNull(); } /// <remarks> /// This tests a decent amount of plumbing for a unit test, but /// helps tests several important concepts. /// </remarks> [Fact] public async Task CustomValidatorMessagePropagatesToValidationException() { // ARRANGE var customValidationMessage = "Custom Validation Message: Testing!"; var invalidValue = 100; var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description") { Validators = new() { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Range, Configuration = new RangeValidator { Min = 7, Max = 10, ValidationFailedMessage = customValidationMessage } } } }; ValidationFailedException exception = null; // ACT try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, invalidValue); } catch (ValidationFailedException e) { exception = e; } exception.ShouldNotBeNull(); exception.Message.ShouldEqual(customValidationMessage); } } }
208
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Should; using Xunit; namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { public class PushToECROptionSettingItemValidationTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly IServiceProvider _serviceProvider; public PushToECROptionSettingItemValidationTests() { var mockServiceProvider = new Mock<IServiceProvider>(); _serviceProvider = mockServiceProvider.Object; _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider)); } [Theory] [InlineData("abc123")] [InlineData("abc.123")] [InlineData("abc-123")] [InlineData("123abc")] [InlineData("1abc234")] [InlineData("1-234_abc")] [InlineData("1.234-abc")] [InlineData("267-234.abc_.-")] public async Task ImageTagValidationTests_ValidTags(string imageTag) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("^[a-zA-Z0-9][a-zA-Z0-9.\\-_]{0,127}$")); await Validate(optionSettingItem, imageTag, true); } [Theory] [InlineData("-abc123")] // cannot start with a special character [InlineData("abc.$123")] // can only contain dot(.), hyphen(-), and underscore(_) as special characters [InlineData("abc@123")]// can only contain dot(.), hyphen(-), and underscore(_) as special characters [InlineData("")] // cannot be empty [InlineData("imagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetagimagetag")] // cannot be greater than 128 characters public async Task ImageTagValidationTests_InValidTags(string imageTag) { var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description"); optionSettingItem.Validators.Add(GetRegexValidatorConfig("^[a-zA-Z0-9][a-zA-Z0-9.\\-_]{0,127}$")); await Validate(optionSettingItem, imageTag, false); } private OptionSettingItemValidatorConfig GetRegexValidatorConfig(string regex) { var regexValidatorConfig = new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, Configuration = new RegexValidator { Regex = regex } }; return regexValidatorConfig; } private async Task Validate<T>(OptionSettingItem optionSettingItem, T value, bool isValid) { ValidationFailedException exception = null; try { await _optionSettingHandler.SetOptionSettingValue(null, optionSettingItem, value); } catch (ValidationFailedException e) { exception = e; } if (isValid) exception.ShouldBeNull(); else exception.ShouldNotBeNull(); } } }
93
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using Amazon.Runtime.Internal; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using Moq; using Newtonsoft.Json; using Should; using Xunit; // Justification: False Positives with assertions, also test class // ReSharper disable PossibleNullReferenceException namespace AWS.Deploy.CLI.Common.UnitTests.Recipes.Validation { /// <summary> /// Tests for <see cref="ValidatorFactory"/> /// </summary> public class ValidatorFactoryTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly IServiceProvider _serviceProvider; private readonly IValidatorFactory _validatorFactory; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; public ValidatorFactoryTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _optionSettingHandler = new Mock<IOptionSettingHandler>().Object; var mockServiceProvider = new Mock<IServiceProvider>(); mockServiceProvider.Setup(x => x.GetService(typeof(IOptionSettingHandler))).Returns(_optionSettingHandler); mockServiceProvider.Setup(x => x.GetService(typeof(IDirectoryManager))).Returns(new TestDirectoryManager()); mockServiceProvider.Setup(x => x.GetService(typeof(IFileManager))).Returns(new TestFileManager()); _serviceProvider = mockServiceProvider.Object; mockServiceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _validatorFactory = new ValidatorFactory(_serviceProvider); mockServiceProvider .Setup(x => x.GetService(typeof(IValidatorFactory))) .Returns(_validatorFactory); } [Fact] public void HasABindingForAllOptionSettingItemValidators() { // ARRANGE var allValidators = Enum.GetValues(typeof(OptionSettingItemValidatorList)); var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description") { Validators = allValidators .Cast<OptionSettingItemValidatorList>() .Select(validatorType => new OptionSettingItemValidatorConfig { ValidatorType = validatorType } ) .ToList() }; // ACT var validators = _validatorFactory.BuildValidators(optionSettingItem); // ASSERT validators.Length.ShouldEqual(allValidators.Length); } [Fact] public void HasABindingForAllRecipeValidators() { // ARRANGE var allValidators = Enum.GetValues(typeof(RecipeValidatorList)); var recipeDefinition = new RecipeDefinition("id", "version", "name", DeploymentTypes.CdkProject, DeploymentBundleTypes.Container, "template", "templateId", "description", "shortDescription", "targetService") { Validators = allValidators .Cast<RecipeValidatorList>() .Select(validatorType => new RecipeValidatorConfig { ValidatorType = validatorType } ) .ToList() }; // ACT var validators = _validatorFactory.BuildValidators(recipeDefinition); // ASSERT validators.Length.ShouldEqual(allValidators.Length); } /// <summary> /// Make sure we build correctly when coming from json /// </summary> [Fact] public void CanBuildRehydratedOptionSettingsItem() { // ARRANGE var expectedValidator = new RequiredValidator { ValidationFailedMessage = "Custom Test Message" }; var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description") { Name = "Test Item", Validators = new List<OptionSettingItemValidatorConfig> { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Required, Configuration = expectedValidator } } }; var json = JsonConvert.SerializeObject(optionSettingItem, Formatting.Indented); var deserialized = JsonConvert.DeserializeObject<OptionSettingItem>(json); // ACT var validators = _validatorFactory.BuildValidators(deserialized); // ASSERT validators.Length.ShouldEqual(1); validators.First().ShouldBeType(expectedValidator.GetType()); validators.OfType<RequiredValidator>().First().ValidationFailedMessage.ShouldEqual(expectedValidator.ValidationFailedMessage); } /// <summary> /// This tests captures the behavior of the system. Requirements for this area are a little unclear /// and can be adjusted as needed. This test is not meant to show 'ideal' behavior; only 'current' /// behavior. /// <para /> /// This test behavior is dependent on using intermediary json. If you just /// used a fully populated <see cref="OptionSettingItem"/>, this test would behave differently. /// Coming from json, <see cref="OptionSettingItemValidatorConfig.ValidatorType"/> wins, /// coming from object model <see cref="OptionSettingItemValidatorConfig.Configuration"/> wins. /// </summary> [Fact] public void WhenValidatorTypeAndConfigurationHaveAMismatchThenValidatorTypeWins() { // ARRANGE var optionSettingItem = new OptionSettingItem("id", "fullyQualifiedId", "name", "description") { Name = "Test Item", Validators = new List<OptionSettingItemValidatorConfig> { new OptionSettingItemValidatorConfig { ValidatorType = OptionSettingItemValidatorList.Regex, // Required can only map to RequiredValidator, this setup doesn't make sense: Configuration = new RangeValidator { Min = 1 } } } }; var json = JsonConvert.SerializeObject(optionSettingItem, Formatting.Indented); var deserialized = JsonConvert.DeserializeObject<OptionSettingItem>(json); Exception exception = null; IOptionSettingItemValidator[] validators = null; // ACT try { validators = _validatorFactory.BuildValidators(deserialized); } catch (Exception e) { exception = e; } // ASSERT exception.ShouldBeNull(); // we have our built validator validators.ShouldNotBeNull(); validators.Length.ShouldEqual(1); // things get a little odd, the type is correct, // but the output messages is going to be from the RangeValidator. validators.First().ShouldBeType<RegexValidator>(); validators.OfType<RegexValidator>().First().ValidationFailedMessage.ShouldEqual( new RangeValidator().ValidationFailedMessage); } } }
208
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Diagnostics; using System.IO; using AWS.Deploy.Orchestration; namespace AWS.Deploy.CLI.IntegrationTests.Services { public class InMemoryInteractiveService : IToolInteractiveService, IOrchestratorInteractiveService { private static readonly object s_readToEndLocker = new object(); private readonly object _writeLocker = new object(); private readonly object _readLocker = new object(); private long _stdOutWriterPosition; private long _stdInReaderPosition; private readonly StreamWriter _stdOutWriter; private readonly StreamReader _stdInReader; /// <summary> /// Allows consumers to write string to the BaseStream /// which will be returned on <see cref="ReadLine"/> method call. /// </summary> public StreamWriter StdInWriter { get; } /// <summary> /// Allows consumers to read string which is written via <see cref="WriteLine"/> /// </summary> public StreamReader StdOutReader { get; } public InMemoryInteractiveService() { var stdOut = new MemoryStream(); _stdOutWriter = new StreamWriter(stdOut); StdOutReader = new StreamReader(stdOut); var stdIn = new MemoryStream(); _stdInReader = new StreamReader(stdIn); StdInWriter = new StreamWriter(stdIn); } public void Write(string message) { lock (_writeLocker) { Debug.Write(message); // Save BaseStream position, it must be only modified by the consumer of StdOutReader // After writing to the BaseStream, we will reset it to the original position. var stdOutReaderPosition = StdOutReader.BaseStream.Position; // Reset the BaseStream to the last save position to continue writing from where we left. _stdOutWriter.BaseStream.Position = _stdOutWriterPosition; _stdOutWriter.Write(message); _stdOutWriter.Flush(); // Save the BaseStream position for future writes. _stdOutWriterPosition = _stdOutWriter.BaseStream.Position; // Reset the BaseStream position to the original position StdOutReader.BaseStream.Position = stdOutReaderPosition; } } public void WriteLine(string message) { lock (_writeLocker) { Debug.WriteLine(message); // Save BaseStream position, it must be only modified by the consumer of StdOutReader // After writing to the BaseStream, we will reset it to the original position. var stdOutReaderPosition = StdOutReader.BaseStream.Position; // Reset the BaseStream to the last save position to continue writing from where we left. _stdOutWriter.BaseStream.Position = _stdOutWriterPosition; _stdOutWriter.WriteLine(message); _stdOutWriter.Flush(); // Save the BaseStream position for future writes. _stdOutWriterPosition = _stdOutWriter.BaseStream.Position; // Reset the BaseStream position to the original position StdOutReader.BaseStream.Position = stdOutReaderPosition; } } public void WriteDebugLine(string message) { WriteLine(message); } public void WriteErrorLine(string message) { WriteLine(message); } public string ReadLine() { lock (_readLocker) { var stdInWriterPosition = StdInWriter.BaseStream.Position; // Reset the BaseStream to the last save position to continue writing from where we left. _stdInReader.BaseStream.Position = _stdInReaderPosition; var readLine = _stdInReader.ReadLine(); if (readLine == null) { throw new InvalidOperationException(); } // Save the BaseStream position for future reads. _stdInReaderPosition = _stdInReader.BaseStream.Position; // Reset the BaseStream position to the original position StdInWriter.BaseStream.Position = stdInWriterPosition; WriteLine(readLine); return readLine; } } public bool Diagnostics { get; set; } public bool DisableInteractive { get; set; } public ConsoleKeyInfo ReadKey(bool intercept) { var stdInWriterPosition = StdInWriter.BaseStream.Position; // Reset the BaseStream to the last save position to continue writing from where we left. _stdInReader.BaseStream.Position = _stdInReaderPosition; var keyChar = _stdInReader.Read(); var key = new ConsoleKeyInfo((char)keyChar, (ConsoleKey)keyChar, false, false, false); // Save the BaseStream position for future reads. _stdInReaderPosition = _stdInReader.BaseStream.Position; // Reset the BaseStream position to the original position StdInWriter.BaseStream.Position = stdInWriterPosition; WriteLine(key.ToString()); return key; } public void ReadStdOutStartToEnd() { lock (s_readToEndLocker) { // Save BaseStream position, it must be only modified by the consumer of StdOutReader // After writing to the BaseStream, we will reset it to the original position. var stdOutReaderPosition = StdOutReader.BaseStream.Position; StdOutReader.BaseStream.Position = 0; var output = StdOutReader.ReadToEnd(); Console.WriteLine(output); Debug.WriteLine(output); // Reset the BaseStream position to the original position StdOutReader.BaseStream.Position = stdOutReaderPosition; } } public void LogSectionStart(string message, string description) { WriteLine(message); } public void LogErrorMessage(string message) { WriteLine(message); } public void LogInfoMessage(string message) { WriteLine(message); } public void LogDebugMessage(string message) { WriteLine(message); } } }
193
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace AWS.Deploy.CLI.Common.UnitTests.Utilities { internal static class SystemIOUtilities { public static string ResolvePath(string projectName) { var testsPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); while (testsPath != null && !string.Equals(new DirectoryInfo(testsPath).Name, "test", StringComparison.OrdinalIgnoreCase)) { testsPath = Directory.GetParent(testsPath).FullName; } return Path.Combine(testsPath, "..", "testapps", projectName); } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using Microsoft.Extensions.DependencyInjection; using Xunit; using static System.Net.WebRequestMethods; namespace AWS.Deploy.CLI.IntegrationTests { public class BlazorWasmTests : IDisposable { private readonly HttpHelper _httpHelper; private readonly CloudFormationHelper _cloudFormationHelper; private readonly CloudFrontHelper _cloudFrontHelper; private readonly InMemoryInteractiveService _interactiveService; private readonly App _app; private string _stackName; private bool _isDisposed; private readonly TestAppManager _testAppManager; public BlazorWasmTests() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); _app = serviceProvider.GetService<App>(); Assert.NotNull(_app); _interactiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(_interactiveService); _httpHelper = new HttpHelper(_interactiveService); var cloudFormationClient = new AmazonCloudFormationClient(); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); _cloudFrontHelper = new CloudFrontHelper(new Amazon.CloudFront.AmazonCloudFrontClient()); _testAppManager = new TestAppManager(); } [Theory] [InlineData("testapps", "BlazorWasm60", "BlazorWasm60.csproj")] public async Task DefaultConfigurations(params string[] components) { _stackName = $"{components[1]}{Guid.NewGuid().ToString().Split('-').Last()}"; // Arrange input for deploy await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default recommendation await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); // Deploy var deployArgs = new[] { "deploy", "--project-path", _testAppManager.GetProjectPath(Path.Combine(components)), "--application-name", _stackName, "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); var tempCdkProjectLine = deployStdOut.First(line => line.StartsWith("Saving AWS CDK deployment project to: ")); var tempCdkProject = tempCdkProjectLine.Split(": ")[1].Trim(); Assert.False(Directory.Exists(tempCdkProject), $"{tempCdkProject} must not exist."); // Example URL string: BlazorWasm6068e7a879d5ee.EndpointURL = http://blazorwasm6068e7a879d5ee-blazorhostc7106839-a2585dcq9xve.s3-website-us-west-2.amazonaws.com/ var applicationUrl = deployStdOut.First(line => line.Contains("https://") && line.Contains("cloudfront.net/")) .Split("=")[1] .Trim(); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); // The initial state of logging should be false, the test will test enabling logging during redeployment. var distributionId = await _cloudFormationHelper.GetResourceId(_stackName, "RecipeCloudFrontDistribution2BE25932"); var distribution = await _cloudFrontHelper.GetDistribution(distributionId); Assert.Equal(Amazon.CloudFront.PriceClass.PriceClass_All, distribution.DistributionConfig.PriceClass); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(listArgs));; // Verify stack exists in list of deployments var listDeployStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listDeployStdOut, (deployment) => _stackName.Equals(deployment)); // Setup for redeployment turning on access logging via settings file. await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); var applyLoggingSettingsFile = Path.Combine(Directory.GetParent(_testAppManager.GetProjectPath(Path.Combine(components))).FullName, "apply-settings.json"); deployArgs = new[] { "deploy", "--project-path", _testAppManager.GetProjectPath(Path.Combine(components)), "--application-name", _stackName, "--diagnostics", "--apply", applyLoggingSettingsFile }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); distribution = await _cloudFrontHelper.GetDistribution(distributionId); Assert.Equal(Amazon.CloudFront.PriceClass.PriceClass_100, distribution.DistributionConfig.PriceClass); // Arrange input for delete await _interactiveService.StdInWriter.WriteAsync("y"); // Confirm delete await _interactiveService.StdInWriter.FlushAsync(); var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics" }; // Delete Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deleteArgs));; // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName), $"{_stackName} still exists."); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } _isDisposed = true; } ~BlazorWasmTests() { Dispose(false); } } }
156
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudWatchLogs; using Amazon.ECS; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests { public class ConsoleAppTests : IDisposable { private readonly CloudFormationHelper _cloudFormationHelper; private readonly ECSHelper _ecsHelper; private readonly CloudWatchLogsHelper _cloudWatchLogsHelper; private readonly App _app; private readonly InMemoryInteractiveService _interactiveService; private bool _isDisposed; private string _stackName; private readonly TestAppManager _testAppManager; public ConsoleAppTests() { var ecsClient = new AmazonECSClient(); _ecsHelper = new ECSHelper(ecsClient); var cloudWatchLogsClient = new AmazonCloudWatchLogsClient(); _cloudWatchLogsHelper = new CloudWatchLogsHelper(cloudWatchLogsClient); var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); _app = serviceProvider.GetService<App>(); Assert.NotNull(_app); _interactiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(_interactiveService); var cloudFormationClient = new AmazonCloudFormationClient(); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); _testAppManager = new TestAppManager(); } [Theory] [InlineData("testapps", "ConsoleAppService", "ConsoleAppService.csproj")] [InlineData("testapps", "ConsoleAppTask", "ConsoleAppTask.csproj")] public async Task DefaultConfigurations(params string[] components) { _stackName = $"{components[1]}{Guid.NewGuid().ToString().Split('-').Last()}"; // Arrange input for deploy await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default recommendation await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); // Deploy var deployArgs = new[] { "deploy", "--project-path", _testAppManager.GetProjectPath(Path.Combine(components)), "--application-name", _stackName, "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var cluster = await _ecsHelper.GetCluster(_stackName); Assert.Equal("ACTIVE", cluster.Status); // Verify CloudWatch logs var logGroup = await _ecsHelper.GetLogGroup(_stackName); var logMessages = await _cloudWatchLogsHelper.GetLogMessages(logGroup); Assert.Contains("Hello World!", logMessages); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); var tempCdkProjectLine = deployStdOut.First(line => line.StartsWith("Saving AWS CDK deployment project to: ")); var tempCdkProject = tempCdkProjectLine.Split(": ")[1].Trim(); Assert.False(Directory.Exists(tempCdkProject), $"{tempCdkProject} must not exist."); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(listArgs));; // Verify stack exists in list of deployments var listStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listStdOut, (deployment) => _stackName.Equals(deployment)); // Arrange input for re-deployment await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); // Perform re-deployment deployArgs = new[] { "deploy", "--project-path", _testAppManager.GetProjectPath(Path.Combine(components)), "--application-name", _stackName, "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); Assert.Equal(StackStatus.UPDATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); // Arrange input for delete await _interactiveService.StdInWriter.WriteAsync("y"); // Confirm delete await _interactiveService.StdInWriter.FlushAsync(); var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics" }; // Delete Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deleteArgs));; // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName), $"{_stackName} still exists."); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } _isDisposed = true; } ~ConsoleAppTests() { Dispose(false); } } }
151
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.ECS; using Amazon.Runtime; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.CLI.IntegrationTests.Utilities; using AWS.Deploy.CLI.ServerMode; using AWS.Deploy.Orchestration.Utilities; using AWS.Deploy.ServerMode.Client; using AWS.Deploy.ServerMode.Client.Utilities; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests { public class ServerModeTests : IDisposable { private bool _isDisposed; private string _stackName; private readonly IServiceProvider _serviceProvider; private readonly CloudFormationHelper _cloudFormationHelper; private readonly string _awsRegion; private readonly TestAppManager _testAppManager; private readonly InMemoryInteractiveService _interactiveService; public ServerModeTests() { _interactiveService = new InMemoryInteractiveService(); var cloudFormationClient = new AmazonCloudFormationClient(Amazon.RegionEndpoint.USWest2); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); _awsRegion = "us-west-2"; _testAppManager = new TestAppManager(); } /// <summary> /// ServerMode must only be connectable from 127.0.0.1 or localhost. This test confirms that connect attempts using /// the host name fail. /// </summary> /// <returns></returns> [Fact] public async Task ConfirmLocalhostOnly() { var portNumber = 4900; var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); _ = serverCommand.ExecuteAsync(cancelSource.Token); try { var restClient = new RestAPIClient($"http://localhost:{portNumber}/", ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials)); await restClient.WaitUntilServerModeReady(); using var client = new HttpClient(); var localhostUrl = $"http://localhost:{portNumber}/api/v1/Health"; await client.GetStringAsync(localhostUrl); var host = Dns.GetHostName(); var hostnameUrl = $"http://{host}:{portNumber}/api/v1/Health"; await Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetStringAsync(hostnameUrl)); } finally { cancelSource.Cancel(); } } [Fact] public async Task GetRecommendations() { var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4000; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var restClient = new RestAPIClient($"http://localhost:{portNumber}/", httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); Assert.NotEmpty(getRecommendationOutput.Recommendations); var beanstalkRecommendation = getRecommendationOutput.Recommendations.FirstOrDefault(); Assert.Equal("AspNetAppElasticBeanstalkLinux", beanstalkRecommendation.RecipeId); Assert.Null(beanstalkRecommendation.BaseRecipeId); Assert.False(beanstalkRecommendation.IsPersistedDeploymentProject); Assert.NotNull(beanstalkRecommendation.ShortDescription); Assert.NotNull(beanstalkRecommendation.Description); Assert.True(beanstalkRecommendation.ShortDescription.Length < beanstalkRecommendation.Description.Length); Assert.Equal("AWS Elastic Beanstalk", beanstalkRecommendation.TargetService); } finally { cancelSource.Cancel(); } } [Fact] public async Task GetRecommendationsWithEncryptedCredentials() { var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4000; var aes = Aes.Create(); aes.GenerateKey(); aes.GenerateIV(); using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials, aes); var keyInfo = new EncryptionKeyInfo { Version = EncryptionKeyInfo.VERSION_1_0, Key = Convert.ToBase64String(aes.Key), IV = Convert.ToBase64String(aes.IV) }; var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo))); await _interactiveService.StdInWriter.WriteAsync(keyInfoStdin); await _interactiveService.StdInWriter.FlushAsync(); var serverCommand = new ServerModeCommand(_interactiveService, portNumber, null, false); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var restClient = new RestAPIClient($"http://localhost:{portNumber}/", httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); Assert.NotEmpty(getRecommendationOutput.Recommendations); Assert.Equal("AspNetAppElasticBeanstalkLinux", getRecommendationOutput.Recommendations.FirstOrDefault().RecipeId); var listDeployStdOut = _interactiveService.StdOutReader.ReadAllLines(); Assert.Contains("Waiting on symmetric key from stdin", listDeployStdOut); Assert.Contains("Encryption provider enabled", listDeployStdOut); } finally { cancelSource.Cancel(); } } [Fact] public async Task WebFargateDeploymentNoConfigChanges() { _stackName = $"ServerModeWebFargate{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4011; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var signalRClient = new DeploymentCommunicationClient(baseUrl); await signalRClient.JoinSession(sessionId); var logOutput = new StringBuilder(); RegisterSignalRMessageCallbacks(signalRClient, logOutput); var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); Assert.NotEmpty(getRecommendationOutput.Recommendations); var fargateRecommendation = getRecommendationOutput.Recommendations.FirstOrDefault(x => string.Equals(x.RecipeId, "AspNetAppEcsFargate")); Assert.NotNull(fargateRecommendation); await restClient.SetDeploymentTargetAsync(sessionId, new SetDeploymentTargetInput { NewDeploymentName = _stackName, NewDeploymentRecipeId = fargateRecommendation.RecipeId }); await restClient.StartDeploymentAsync(sessionId); await restClient.WaitForDeployment(sessionId); var stackStatus = await _cloudFormationHelper.GetStackStatus(_stackName); Assert.Equal(StackStatus.CREATE_COMPLETE, stackStatus); Assert.True(logOutput.Length > 0); // Check to make sure the task memory setting was copied to the container defintion memory limit; var taskDefinitionId = await _cloudFormationHelper.GetResourceId(_stackName, "RecipeAppTaskDefinitionAC7F53DB"); using var ecsClient = new AmazonECSClient(Amazon.RegionEndpoint.GetBySystemName(_awsRegion)); var taskDefinition = (await ecsClient.DescribeTaskDefinitionAsync(new Amazon.ECS.Model.DescribeTaskDefinitionRequest { TaskDefinition = taskDefinitionId })).TaskDefinition; var containerDefinition = taskDefinition.ContainerDefinitions[0]; Assert.Equal(int.Parse(taskDefinition.Memory), containerDefinition.Memory); // Make sure section header is return to output log Assert.Contains("Creating deployment image", logOutput.ToString()); // Make sure normal log messages are returned to output log Assert.Contains("Pushing container image", logOutput.ToString()); var redeploymentSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var redeploymentSessionId = redeploymentSessionOutput.SessionId; var existingDeployments = await restClient.GetExistingDeploymentsAsync(redeploymentSessionId); var existingDeployment = existingDeployments.ExistingDeployments.First(x => string.Equals(_stackName, x.Name)); Assert.Equal(_stackName, existingDeployment.Name); Assert.Equal(fargateRecommendation.RecipeId, existingDeployment.RecipeId); Assert.Null(fargateRecommendation.BaseRecipeId); Assert.False(fargateRecommendation.IsPersistedDeploymentProject); Assert.Equal(fargateRecommendation.Name, existingDeployment.RecipeName); Assert.Equal(fargateRecommendation.ShortDescription, existingDeployment.ShortDescription); Assert.Equal(fargateRecommendation.Description, existingDeployment.Description); Assert.Equal(fargateRecommendation.TargetService, existingDeployment.TargetService); Assert.Equal(DeploymentTypes.CloudFormationStack, existingDeployment.DeploymentType); Assert.NotEmpty(existingDeployment.SettingsCategories); Assert.Contains(existingDeployment.SettingsCategories, x => string.Equals(x.Id, AWS.Deploy.Common.Recipes.Category.DeploymentBundle.Id)); Assert.DoesNotContain(existingDeployment.SettingsCategories, x => string.IsNullOrEmpty(x.Id)); Assert.DoesNotContain(existingDeployment.SettingsCategories, x => string.IsNullOrEmpty(x.DisplayName)); // The below tests will check if updating readonly settings will properly get rejected. // These tests need to be performed on a redeployment await restClient.SetDeploymentTargetAsync(redeploymentSessionId, new SetDeploymentTargetInput { ExistingDeploymentId = await _cloudFormationHelper.GetStackArn(_stackName) }); var settings = await restClient.GetConfigSettingsAsync(sessionId); // Try to update a list of settings containing readonly settings which we expect to fail var updatedSettings = (IDictionary<string, string>)settings.OptionSettings.Where(x => !string.IsNullOrEmpty(x.FullyQualifiedId)).ToDictionary(k => k.FullyQualifiedId, v => "test"); var exceptionThrown = await Assert.ThrowsAsync<ApiException>(async () => await restClient.ApplyConfigSettingsAsync(redeploymentSessionId, new ApplyConfigSettingsInput() { UpdatedSettings = updatedSettings })); Assert.Equal(400, exceptionThrown.StatusCode); // Try to update an updatable setting which should be successful var applyConfigResponse = await restClient.ApplyConfigSettingsAsync(redeploymentSessionId, new ApplyConfigSettingsInput { UpdatedSettings = new Dictionary<string, string> { { "DesiredCount", "4" } } }); Assert.Empty(applyConfigResponse.FailedConfigUpdates); } finally { cancelSource.Cancel(); await _cloudFormationHelper.DeleteStack(_stackName); _stackName = null; } } [Fact] public async Task RecommendationsForNewDeployments_DoesNotIncludeExistingBeanstalkEnvironmentRecipe() { var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4002; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); Assert.NotEmpty(getRecommendationOutput.Recommendations); var recommendations = getRecommendationOutput.Recommendations; Assert.DoesNotContain(recommendations, x => x.DeploymentType == DeploymentTypes.BeanstalkEnvironment); } finally { cancelSource.Cancel(); } } [Fact] public async Task ShutdownViaRestClient() { var portNumber = 4003; var cancelSource = new CancellationTokenSource(); using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); await restClient.ShutdownAsync(); Thread.Sleep(100); // Expecting System.Net.Http.HttpRequestException : No connection could be made because the target machine actively refused it. await Assert.ThrowsAsync<System.Net.Http.HttpRequestException>(async () => await restClient.HealthAsync()); } finally { cancelSource.Cancel(); } } [Theory] [InlineData("1234MyAppStack")] // cannot start with a number [InlineData("MyApp@Stack/123")] // cannot contain special characters [InlineData("")] // cannot be empty [InlineData("stackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstackstack")] // cannot contain more than 128 characters public async Task InvalidStackName_ThrowsException(string invalidStackName) { var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4012; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); var fargateRecommendation = getRecommendationOutput.Recommendations.FirstOrDefault(x => string.Equals(x.RecipeId, "AspNetAppEcsFargate")); var exception = await Assert.ThrowsAsync<ApiException<ProblemDetails>>(() => restClient.SetDeploymentTargetAsync(sessionId, new SetDeploymentTargetInput { NewDeploymentName = invalidStackName, NewDeploymentRecipeId = fargateRecommendation.RecipeId })); Assert.Equal(400, exception.StatusCode); var errorMessage = $"Invalid cloud application name: {invalidStackName}"; Assert.Contains(errorMessage, exception.Result.Detail); } finally { cancelSource.Cancel(); } } [Fact] public async Task CheckCategories() { var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4200; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var restClient = new RestAPIClient($"http://localhost:{portNumber}/", httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = _awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); foreach(var recommendation in getRecommendationOutput.Recommendations) { Assert.NotEmpty(recommendation.SettingsCategories); Assert.Contains(recommendation.SettingsCategories, x => string.Equals(x.Id, AWS.Deploy.Common.Recipes.Category.DeploymentBundle.Id)); Assert.DoesNotContain(recommendation.SettingsCategories, x => string.IsNullOrEmpty(x.Id)); Assert.DoesNotContain(recommendation.SettingsCategories, x => string.IsNullOrEmpty(x.DisplayName)); } var selectedRecommendation = getRecommendationOutput.Recommendations.First(); await restClient.SetDeploymentTargetAsync(sessionId, new SetDeploymentTargetInput { NewDeploymentRecipeId = selectedRecommendation.RecipeId, NewDeploymentName = "TestStack-" + DateTime.UtcNow.Ticks }); var getConfigSettingsResponse = await restClient.GetConfigSettingsAsync(sessionId); // Make sure all top level settings have a category Assert.DoesNotContain(getConfigSettingsResponse.OptionSettings, x => string.IsNullOrEmpty(x.Category)); // Make sure build settings have been applied a category. var buildSetting = getConfigSettingsResponse.OptionSettings.FirstOrDefault(x => string.Equals(x.Id, "DotnetBuildConfiguration")); Assert.NotNull(buildSetting); Assert.Equal(AWS.Deploy.Common.Recipes.Category.DeploymentBundle.Id, buildSetting.Category); } finally { cancelSource.Cancel(); } } internal static void RegisterSignalRMessageCallbacks(IDeploymentCommunicationClient signalRClient, StringBuilder logOutput) { signalRClient.ReceiveLogSectionStart = (message, description) => { logOutput.AppendLine(new string('*', message.Length)); logOutput.AppendLine(message); logOutput.AppendLine(new string('*', message.Length)); }; signalRClient.ReceiveLogInfoMessage = (message) => { logOutput.AppendLine(message); }; signalRClient.ReceiveLogErrorMessage = (message) => { logOutput.AppendLine(message); }; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { if(!string.IsNullOrEmpty(_stackName)) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } } _isDisposed = true; } ~ServerModeTests() { Dispose(false); } } }
551
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.Orchestration.Utilities; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Xunit; using Environment = System.Environment; namespace AWS.Deploy.CLI.IntegrationTests { public class WebAppNoDockerFileTests : IDisposable { private readonly HttpHelper _httpHelper; private readonly CloudFormationHelper _cloudFormationHelper; private readonly App _app; private readonly InMemoryInteractiveService _interactiveService; private bool _isDisposed; private string _stackName; private readonly TestAppManager _testAppManager; private readonly string _customWorkspace; public WebAppNoDockerFileTests() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); foreach (var item in serviceCollection) { if (item.ServiceType == typeof(IEnvironmentVariableManager)) { serviceCollection.Remove(item); break; } } serviceCollection.TryAdd(new ServiceDescriptor(typeof(IEnvironmentVariableManager), typeof(TestEnvironmentVariableManager), ServiceLifetime.Singleton)); var serviceProvider = serviceCollection.BuildServiceProvider(); _customWorkspace = Path.Combine(Path.GetTempPath(), $"deploy-tool-workspace{Guid.NewGuid().ToString().Split('-').Last()}"); Helpers.Utilities.OverrideDefaultWorkspace(serviceProvider, _customWorkspace); _app = serviceProvider.GetService<App>(); Assert.NotNull(_app); _interactiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(_interactiveService); _httpHelper = new HttpHelper(_interactiveService); var cloudFormationClient = new AmazonCloudFormationClient(); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); _testAppManager = new TestAppManager(); } [Theory] [InlineData("ElasticBeanStalkConfigFile-Linux.json", true)] [InlineData("ElasticBeanStalkConfigFile-Linux-SelfContained.json", true)] [InlineData("ElasticBeanStalkConfigFile-Windows.json", false)] [InlineData("ElasticBeanStalkConfigFile-Windows-SelfContained.json", false)] public async Task EBDefaultConfigurations(string configFile, bool linux) { _stackName = $"BeanstalkTest-{Guid.NewGuid().ToString().Split('-').Last()}"; // Deploy var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _stackName, "--diagnostics", "--silent", "--apply", configFile }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); var tempCdkProjectLine = deployStdOut.First(line => line.StartsWith("Saving AWS CDK deployment project to: ")); var tempCdkProject = tempCdkProjectLine.Split(": ")[1].Trim(); Assert.False(Directory.Exists(tempCdkProject), $"{tempCdkProject} must not exist."); // Example: Endpoint: http://52.36.216.238/ var endpointLine = deployStdOut.First(line => line.Trim().StartsWith($"Endpoint")); var applicationUrl = endpointLine.Substring(endpointLine.IndexOf(":") + 1).Trim(); Assert.True(Uri.IsWellFormedUriString(applicationUrl, UriKind.Absolute)); if(!linux) { // "extra-path" is the IISAppPath set in the config file. applicationUrl = new Uri(new Uri(applicationUrl), "extra-path").AbsoluteUri; } // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(listArgs)); ; // Verify stack exists in list of deployments var listStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listStdOut, (deployment) => _stackName.Equals(deployment)); // Arrange input for delete // Use --silent flag to delete without user prompts var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics", "--silent" }; // Delete Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deleteArgs)); ; // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName), $"{_stackName} still exists."); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } _isDisposed = true; } ~WebAppNoDockerFileTests() { Dispose(false); } } }
157
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Net.Http; using System.Collections.Generic; using Amazon.CloudFormation; using Amazon.ECS; using Amazon.ECS.Model; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using Microsoft.Extensions.DependencyInjection; using Xunit; using Task = System.Threading.Tasks.Task; namespace AWS.Deploy.CLI.IntegrationTests { public class WebAppWithDockerFileTests : IDisposable { private readonly HttpHelper _httpHelper; private readonly CloudFormationHelper _cloudFormationHelper; private readonly ECSHelper _ecsHelper; private readonly App _app; private readonly InMemoryInteractiveService _interactiveService; private bool _isDisposed; private string _stackName; private readonly TestAppManager _testAppManager; public WebAppWithDockerFileTests() { var ecsClient = new AmazonECSClient(); _ecsHelper = new ECSHelper(ecsClient); var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); _app = serviceProvider.GetService<App>(); Assert.NotNull(_app); _interactiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(_interactiveService); _httpHelper = new HttpHelper(_interactiveService); var cloudFormationClient = new AmazonCloudFormationClient(); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); _testAppManager = new TestAppManager(); } [Fact] public async Task DefaultConfigurations() { _stackName = $"WebAppWithDockerFile{Guid.NewGuid().ToString().Split('-').Last()}"; // Arrange input for deploy await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default recommendation await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); // Deploy var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _stackName, "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var cluster = await _ecsHelper.GetCluster(_stackName); Assert.Equal("ACTIVE", cluster.Status); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); var tempCdkProjectLine = deployStdOut.First(line => line.StartsWith("Saving AWS CDK deployment project to: ")); var tempCdkProject = tempCdkProjectLine.Split(": ")[1].Trim(); Assert.False(Directory.Exists(tempCdkProject), $"{tempCdkProject} must not exist."); var applicationUrl = deployStdOut.First(line => line.Trim().StartsWith("Endpoint:")) .Split(" ")[1] .Trim(); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(listArgs));; // Verify stack exists in list of deployments var listDeployStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listDeployStdOut, (deployment) => _stackName.Equals(deployment)); // Arrange input for re-deployment await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); // Perform re-deployment deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _stackName, "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); Assert.Equal(StackStatus.UPDATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); Assert.Equal("ACTIVE", cluster.Status); // Arrange input for delete await _interactiveService.StdInWriter.WriteAsync("y"); // Confirm delete await _interactiveService.StdInWriter.FlushAsync(); var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics" }; // Delete Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deleteArgs));; // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName), $"{_stackName} still exists."); } [Fact] public async Task AppRunnerDeployment() { var stackNamePlaceholder = "{StackName}"; _stackName = $"WebAppWithDockerFile{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var configFilePath = Path.Combine(Directory.GetParent(projectPath).FullName, "AppRunnerConfigFile.json"); ConfigFileHelper.ApplyReplacementTokens(new Dictionary<string, string> { { stackNamePlaceholder, _stackName } }, configFilePath); // Deploy var deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _stackName, "--diagnostics", "--apply", configFilePath, "--silent" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); var applicationUrl = deployStdOut.First(line => line.StartsWith($"{_stackName}.RecipeEndpointURL")) .Split("=")[1] .Trim(); Assert.Contains("awsapprunner", applicationUrl); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); // Ensure environemnt variables specified in AppRunnerConfigFile.json are set for the service. var checkEnvironmentVariableUrl = applicationUrl + "envvar/TEST_Key1"; using var httpClient = new HttpClient(); var envVarValue = await httpClient.GetStringAsync(checkEnvironmentVariableUrl); Assert.Equal("Value1", envVarValue); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(listArgs));; // Verify stack exists in list of deployments var listDeployStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listDeployStdOut, (deployment) => _stackName.Equals(deployment)); // Arrange input for delete await _interactiveService.StdInWriter.WriteAsync("y"); // Confirm delete await _interactiveService.StdInWriter.FlushAsync(); var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics" }; // Delete Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deleteArgs));; // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName)); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } _isDisposed = true; } ~WebAppWithDockerFileTests() { Dispose(false); } } }
207
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.CLI.IntegrationTests.Extensions; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests { [Collection(nameof(TestContextFixture))] public class CLITests { private readonly TestContextFixture _fixture; public CLITests(TestContextFixture fixture) { _fixture = fixture; } [Fact] public async Task DeployToExistingBeanstalkEnvironment() { var projectPath = _fixture.TestAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _fixture.EnvironmentName, "--diagnostics", "--silent", "--region", "us-west-2" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _fixture.App.Run(deployArgs)); var environmentDescription = await _fixture.AWSResourceQueryer.DescribeElasticBeanstalkEnvironment(_fixture.EnvironmentName); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _fixture.HttpHelper.WaitUntilSuccessStatusCode(environmentDescription.CNAME, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); var successMessagePrefix = $"The Elastic Beanstalk Environment {_fixture.EnvironmentName} has been successfully updated"; var deployStdOutput = _fixture.InteractiveService.StdOutReader.ReadAllLines(); var successMessage = deployStdOutput.First(line => line.Trim().StartsWith(successMessagePrefix)); Assert.False(string.IsNullOrEmpty(successMessage)); var expectedVersionLabel = successMessage.Split(" ").Last(); Assert.True(await _fixture.EBHelper.VerifyEnvironmentVersionLabel(_fixture.EnvironmentName, expectedVersionLabel)); } [Fact] public async Task DeployToExistingBeanstalkEnvironmentSelfContained() { var projectPath = _fixture.TestAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _fixture.EnvironmentName, "--diagnostics", "--silent", "--region", "us-west-2", "--apply", "Existing-ElasticBeanStalkConfigFile-Linux-SelfContained.json" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _fixture.App.Run(deployArgs)); var environmentDescription = await _fixture.AWSResourceQueryer.DescribeElasticBeanstalkEnvironment(_fixture.EnvironmentName); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _fixture.HttpHelper.WaitUntilSuccessStatusCode(environmentDescription.CNAME, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); var successMessagePrefix = $"The Elastic Beanstalk Environment {_fixture.EnvironmentName} has been successfully updated"; var deployStdOutput = _fixture.InteractiveService.StdOutReader.ReadAllLines(); var successMessage = deployStdOutput.First(line => line.Trim().StartsWith(successMessagePrefix)); Assert.False(string.IsNullOrEmpty(successMessage)); var expectedVersionLabel = successMessage.Split(" ").Last(); Assert.True(await _fixture.EBHelper.VerifyEnvironmentVersionLabel(_fixture.EnvironmentName, expectedVersionLabel)); } } }
66
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.IntegrationTests.Utilities; using AWS.Deploy.Orchestration.Utilities; using AWS.Deploy.ServerMode.Client; using AWS.Deploy.ServerMode.Client.Utilities; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests { [Collection(nameof(TestContextFixture))] public class ServerModeTests { private readonly TestContextFixture _fixture; private const string BEANSTALK_ENVIRONMENT_RECIPE_ID = "AspNetAppExistingBeanstalkEnvironment"; public ServerModeTests(TestContextFixture fixture) { _fixture = fixture; } [Fact] public async Task DeployToExistingBeanstalkEnvironment() { var projectPath = _fixture.TestAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4031; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_fixture.ToolInteractiveService, portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = "us-west-2", ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var existingDeployments = await restClient.GetExistingDeploymentsAsync(sessionId); var existingDeployment = existingDeployments.ExistingDeployments.First(x => string.Equals(_fixture.EnvironmentName, x.Name)); Assert.Equal(_fixture.EnvironmentName, existingDeployment.Name); Assert.Equal(BEANSTALK_ENVIRONMENT_RECIPE_ID, existingDeployment.RecipeId); Assert.Null(existingDeployment.BaseRecipeId); Assert.False(existingDeployment.IsPersistedDeploymentProject); Assert.Equal(_fixture.EnvironmentId, existingDeployment.ExistingDeploymentId); Assert.Equal(DeploymentTypes.BeanstalkEnvironment, existingDeployment.DeploymentType); var signalRClient = new DeploymentCommunicationClient(baseUrl); await signalRClient.JoinSession(sessionId); var logOutput = new StringBuilder(); AWS.Deploy.CLI.IntegrationTests.ServerModeTests.RegisterSignalRMessageCallbacks(signalRClient, logOutput); await restClient.SetDeploymentTargetAsync(sessionId, new SetDeploymentTargetInput { ExistingDeploymentId = _fixture.EnvironmentId }); await restClient.StartDeploymentAsync(sessionId); await restClient.WaitForDeployment(sessionId); Assert.True(logOutput.Length > 0); var successMessagePrefix = $"The Elastic Beanstalk Environment {_fixture.EnvironmentName} has been successfully updated"; var deployStdOutput = logOutput.ToString().Split(Environment.NewLine); var successMessage = deployStdOutput.First(line => line.Trim().StartsWith(successMessagePrefix)); Assert.False(string.IsNullOrEmpty(successMessage)); var expectedVersionLabel = successMessage.Split(" ").Last(); Assert.True(await _fixture.EBHelper.VerifyEnvironmentVersionLabel(_fixture.EnvironmentName, expectedVersionLabel)); } finally { cancelSource.Cancel(); } } } }
99
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.ElasticBeanstalk; using Amazon.IdentityManagement; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.Utilities; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests { /// <summary> /// The goal of this class is to be used as shared context between a collection of tests. /// More info could be found here https://xunit.net/docs/shared-context /// </summary> public class TestContextFixture : IAsyncLifetime { public readonly App App; public readonly HttpHelper HttpHelper; public readonly IAWSResourceQueryer AWSResourceQueryer; public readonly TestAppManager TestAppManager; public readonly IDirectoryManager DirectoryManager; public readonly ICommandLineWrapper CommandLineWrapper; public readonly IZipFileManager ZipFileManager; public readonly IToolInteractiveService ToolInteractiveService; public readonly InMemoryInteractiveService InteractiveService; public readonly ElasticBeanstalkHelper EBHelper; public readonly IAMHelper IAMHelper; public readonly string ApplicationName; public readonly string EnvironmentName; public readonly string VersionLabel; public readonly string RoleName; public string EnvironmentId; public TestContextFixture() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); var awsClientFactory = serviceProvider.GetService<IAWSClientFactory>(); awsClientFactory.ConfigureAWSOptions((options) => { options.Region = Amazon.RegionEndpoint.USWest2; }); App = serviceProvider.GetService<App>(); Assert.NotNull(App); InteractiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(InteractiveService); ToolInteractiveService = serviceProvider.GetService<IToolInteractiveService>(); AWSResourceQueryer = serviceProvider.GetService<IAWSResourceQueryer>(); Assert.NotNull(AWSResourceQueryer); CommandLineWrapper = serviceProvider.GetService<ICommandLineWrapper>(); Assert.NotNull(CommandLineWrapper); ZipFileManager = serviceProvider.GetService<IZipFileManager>(); Assert.NotNull(ZipFileManager); DirectoryManager = serviceProvider.GetService<IDirectoryManager>(); Assert.NotNull(DirectoryManager); HttpHelper = new HttpHelper(InteractiveService); TestAppManager = new TestAppManager(); var suffix = Guid.NewGuid().ToString().Split('-').Last(); ApplicationName = $"application{suffix}"; EnvironmentName = $"environment{suffix}"; VersionLabel = $"v-{suffix}"; RoleName = $"aws-elasticbeanstalk-ec2-role{suffix}"; EBHelper = new ElasticBeanstalkHelper(new AmazonElasticBeanstalkClient(Amazon.RegionEndpoint.USWest2), AWSResourceQueryer, ToolInteractiveService); IAMHelper = new IAMHelper(new AmazonIdentityManagementServiceClient(), AWSResourceQueryer, ToolInteractiveService); } public async Task InitializeAsync() { await IAMHelper.CreateRoleForBeanstalkEnvionmentDeployment(RoleName); var projectPath = TestAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var publishDirectoryInfo = DirectoryManager.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())); var zipFilePath = $"{publishDirectoryInfo.FullName}.zip"; var publishCommand = $"dotnet publish \"{projectPath}\"" + $" -o \"{publishDirectoryInfo}\"" + $" -c release"; var result = await CommandLineWrapper.TryRunWithResult(publishCommand, streamOutputToInteractiveService: true); Assert.Equal(0, result.ExitCode); await ZipFileManager.CreateFromDirectory(publishDirectoryInfo.FullName, zipFilePath); await EBHelper.CreateApplicationAsync(ApplicationName); await EBHelper.CreateApplicationVersionAsync(ApplicationName, VersionLabel, zipFilePath); var success = await EBHelper.CreateEnvironmentAsync(ApplicationName, EnvironmentName, VersionLabel, BeanstalkPlatformType.Linux, RoleName); Assert.True(success); var environmentDescription = await AWSResourceQueryer.DescribeElasticBeanstalkEnvironment(EnvironmentName); EnvironmentId = environmentDescription.EnvironmentId; // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await HttpHelper.WaitUntilSuccessStatusCode(environmentDescription.CNAME, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); } public async Task DisposeAsync() { var success = await EBHelper.DeleteApplication(ApplicationName, EnvironmentName); await IAMHelper.DeleteRoleAndInstanceProfileAfterBeanstalkEnvionmentDeployment(RoleName); Assert.True(success); } } }
135
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests { /// <summary> /// The goal of this class is to create a Collection definition and use <see cref="TestContextFixture"/> as shared context. /// More info could be found here https://xunit.net/docs/shared-context /// </summary> [CollectionDefinition(nameof(TestContextFixture))] public class TestContextFixtureCollection : ICollectionFixture<TestContextFixture> { } }
17
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.ServiceHandlers; using Moq; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests.ExistingWindowsEnvironment { [Collection(nameof(WindowsTestContextFixture))] public class CLITests { private readonly WindowsTestContextFixture _fixture; private readonly AWSElasticBeanstalkHandler _awsElasticBeanstalkHandler; private readonly Mock<IOptionSettingHandler> _optionSettingHandler; private readonly ProjectDefinitionParser _projectDefinitionParser; private readonly RecipeDefinition _recipeDefinition; public CLITests(WindowsTestContextFixture fixture) { _projectDefinitionParser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); _fixture = fixture; _optionSettingHandler = new Mock<IOptionSettingHandler>(); _awsElasticBeanstalkHandler = new AWSElasticBeanstalkHandler(null, null, null, _optionSettingHandler.Object); _recipeDefinition = new Mock<RecipeDefinition>( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<DeploymentTypes>(), It.IsAny<DeploymentBundleTypes>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()).Object; } [Fact] public async Task DeployToExistingBeanstalkEnvironment() { var projectPath = _fixture.TestAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _fixture.EnvironmentName, "--diagnostics", "--silent", "--region", "us-west-2" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _fixture.App.Run(deployArgs)); var environmentDescription = await _fixture.AWSResourceQueryer.DescribeElasticBeanstalkEnvironment(_fixture.EnvironmentName); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _fixture.HttpHelper.WaitUntilSuccessStatusCode(environmentDescription.CNAME, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); var successMessagePrefix = $"The Elastic Beanstalk Environment {_fixture.EnvironmentName} has been successfully updated"; var deployStdOutput = _fixture.InteractiveService.StdOutReader.ReadAllLines(); var successMessage = deployStdOutput.First(line => line.Trim().StartsWith(successMessagePrefix)); Assert.False(string.IsNullOrEmpty(successMessage)); var expectedVersionLabel = successMessage.Split(" ").Last(); Assert.True(await _fixture.EBHelper.VerifyEnvironmentVersionLabel(_fixture.EnvironmentName, expectedVersionLabel)); } } }
68
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.IntegrationTests.Utilities; using AWS.Deploy.ServerMode.Client; using AWS.Deploy.ServerMode.Client.Utilities; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests.ExistingWindowsEnvironment { [Collection(nameof(WindowsTestContextFixture))] public class ServerModeTests { private readonly WindowsTestContextFixture _fixture; private const string BEANSTALK_ENVIRONMENT_RECIPE_ID = "AspNetAppExistingBeanstalkWindowsEnvironment"; public ServerModeTests(WindowsTestContextFixture fixture) { _fixture = fixture; } [Fact] public async Task DeployToExistingWindowsBeanstalkEnvironment() { var projectPath = _fixture.TestAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4031; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_fixture.ToolInteractiveService, portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = "us-west-2", ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); var existingDeployments = await restClient.GetExistingDeploymentsAsync(sessionId); var existingDeployment = existingDeployments.ExistingDeployments.First(x => string.Equals(_fixture.EnvironmentName, x.Name)); Assert.Equal(_fixture.EnvironmentName, existingDeployment.Name); Assert.Equal(BEANSTALK_ENVIRONMENT_RECIPE_ID, existingDeployment.RecipeId); Assert.Null(existingDeployment.BaseRecipeId); Assert.False(existingDeployment.IsPersistedDeploymentProject); Assert.Equal(_fixture.EnvironmentId, existingDeployment.ExistingDeploymentId); Assert.Equal(DeploymentTypes.BeanstalkEnvironment, existingDeployment.DeploymentType); var signalRClient = new DeploymentCommunicationClient(baseUrl); await signalRClient.JoinSession(sessionId); var logOutput = new StringBuilder(); AWS.Deploy.CLI.IntegrationTests.ServerModeTests.RegisterSignalRMessageCallbacks(signalRClient, logOutput); await restClient.SetDeploymentTargetAsync(sessionId, new SetDeploymentTargetInput { ExistingDeploymentId = _fixture.EnvironmentId }); await restClient.StartDeploymentAsync(sessionId); await restClient.WaitForDeployment(sessionId); Assert.True(logOutput.Length > 0); var successMessagePrefix = $"The Elastic Beanstalk Environment {_fixture.EnvironmentName} has been successfully updated"; var deployStdOutput = logOutput.ToString().Split(Environment.NewLine); var successMessage = deployStdOutput.First(line => line.Trim().StartsWith(successMessagePrefix)); Assert.False(string.IsNullOrEmpty(successMessage)); var expectedVersionLabel = successMessage.Split(" ").Last(); Assert.True(await _fixture.EBHelper.VerifyEnvironmentVersionLabel(_fixture.EnvironmentName, expectedVersionLabel)); } finally { cancelSource.Cancel(); } } } }
98
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using Amazon.ElasticBeanstalk; using Amazon.IdentityManagement; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.ServiceHandlers; using AWS.Deploy.Orchestration.Utilities; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests.ExistingWindowsEnvironment { /// <summary> /// The goal of this class is to be used as shared context between a collection of tests. /// More info could be found here https://xunit.net/docs/shared-context /// </summary> public class WindowsTestContextFixture : IAsyncLifetime { public readonly App App; public readonly HttpHelper HttpHelper; public readonly IAWSResourceQueryer AWSResourceQueryer; public readonly TestAppManager TestAppManager; public readonly IDirectoryManager DirectoryManager; public readonly ICommandLineWrapper CommandLineWrapper; public readonly IZipFileManager ZipFileManager; public readonly IToolInteractiveService ToolInteractiveService; public readonly IElasticBeanstalkHandler ElasticBeanstalkHandler; public readonly InMemoryInteractiveService InteractiveService; public readonly ElasticBeanstalkHelper EBHelper; public readonly IAMHelper IAMHelper; public readonly string ApplicationName; public readonly string EnvironmentName; public readonly string VersionLabel; public readonly string RoleName; public string EnvironmentId; public WindowsTestContextFixture() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); var awsClientFactory = serviceProvider.GetService<IAWSClientFactory>(); awsClientFactory.ConfigureAWSOptions((options) => { options.Region = Amazon.RegionEndpoint.USWest2; }); App = serviceProvider.GetService<App>(); Assert.NotNull(App); InteractiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(InteractiveService); ToolInteractiveService = serviceProvider.GetService<IToolInteractiveService>(); AWSResourceQueryer = serviceProvider.GetService<IAWSResourceQueryer>(); Assert.NotNull(AWSResourceQueryer); CommandLineWrapper = serviceProvider.GetService<ICommandLineWrapper>(); Assert.NotNull(CommandLineWrapper); ZipFileManager = serviceProvider.GetService<IZipFileManager>(); Assert.NotNull(ZipFileManager); DirectoryManager = serviceProvider.GetService<IDirectoryManager>(); Assert.NotNull(DirectoryManager); ElasticBeanstalkHandler = serviceProvider.GetService<IElasticBeanstalkHandler>(); Assert.NotNull(ElasticBeanstalkHandler); HttpHelper = new HttpHelper(InteractiveService); TestAppManager = new TestAppManager(); var suffix = Guid.NewGuid().ToString().Split('-').Last(); ApplicationName = $"application{suffix}"; EnvironmentName = $"environment{suffix}"; VersionLabel = $"v-{suffix}"; RoleName = $"aws-elasticbeanstalk-ec2-role{suffix}"; EBHelper = new ElasticBeanstalkHelper(new AmazonElasticBeanstalkClient(Amazon.RegionEndpoint.USWest2), AWSResourceQueryer, ToolInteractiveService); IAMHelper = new IAMHelper(new AmazonIdentityManagementServiceClient(), AWSResourceQueryer, ToolInteractiveService); } public async Task InitializeAsync() { await IAMHelper.CreateRoleForBeanstalkEnvionmentDeployment(RoleName); var projectPath = TestAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var publishDirectoryInfo = DirectoryManager.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())); var zipFilePath = $"{publishDirectoryInfo.FullName}.zip"; var publishCommand = $"dotnet publish \"{projectPath}\"" + $" -o \"{publishDirectoryInfo}\"" + $" -c release"; var result = await CommandLineWrapper.TryRunWithResult(publishCommand, streamOutputToInteractiveService: true); Assert.Equal(0, result.ExitCode); await ZipFileManager.CreateFromDirectory(publishDirectoryInfo.FullName, zipFilePath); SetupWindowsDeploymentManifest(zipFilePath); await EBHelper.CreateApplicationAsync(ApplicationName); await EBHelper.CreateApplicationVersionAsync(ApplicationName, VersionLabel, zipFilePath); var success = await EBHelper.CreateEnvironmentAsync(ApplicationName, EnvironmentName, VersionLabel, BeanstalkPlatformType.Windows, RoleName); Assert.True(success); var environmentDescription = await AWSResourceQueryer.DescribeElasticBeanstalkEnvironment(EnvironmentName); EnvironmentId = environmentDescription.EnvironmentId; // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await HttpHelper.WaitUntilSuccessStatusCode(environmentDescription.CNAME, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); } public void SetupWindowsDeploymentManifest(string dotnetZipFilePath) { const string MANIFEST_FILENAME = "aws-windows-deployment-manifest.json"; var jsonStream = new MemoryStream(); using (var jsonWriter = new Utf8JsonWriter(jsonStream)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("manifestVersion"); jsonWriter.WriteNumberValue(1); jsonWriter.WriteStartObject("deployments"); jsonWriter.WriteStartArray("aspNetCoreWeb"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("name"); jsonWriter.WriteStringValue("MainApp"); jsonWriter.WriteStartObject("parameters"); jsonWriter.WritePropertyName("appBundle"); jsonWriter.WriteStringValue("."); jsonWriter.WritePropertyName("iisWebSite"); jsonWriter.WriteStringValue("Default Web Site"); jsonWriter.WritePropertyName("iisPath"); jsonWriter.WriteStringValue("/"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); } using (var zipArchive = ZipFile.Open(dotnetZipFilePath, ZipArchiveMode.Update)) { var zipEntry = zipArchive.CreateEntry(MANIFEST_FILENAME); using var zipEntryStream = zipEntry.Open(); jsonStream.Position = 0; jsonStream.CopyTo(zipEntryStream); } } public async Task DisposeAsync() { var success = await EBHelper.DeleteApplication(ApplicationName, EnvironmentName); await IAMHelper.DeleteRoleAndInstanceProfileAfterBeanstalkEnvionmentDeployment(RoleName); Assert.True(success); } } }
187
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.BeanstalkBackwardsCompatibilityTests.ExistingWindowsEnvironment { /// <summary> /// The goal of this class is to create a Collection definition and use <see cref="WindowsTestContextFixture"/> as shared context. /// More info could be found here https://xunit.net/docs/shared-context /// </summary> [CollectionDefinition(nameof(WindowsTestContextFixture))] public class WindowsTestContextFixtureCollection : ICollectionFixture<WindowsTestContextFixture> { } }
17
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Collections.Generic; using Amazon.CloudFormation; using Amazon.ECS; using Amazon.ECS.Model; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using Microsoft.Extensions.DependencyInjection; using Xunit; using Task = System.Threading.Tasks.Task; namespace AWS.Deploy.CLI.IntegrationTests.ConfigFileDeployment { public class ECSFargateDeploymentTest : IDisposable { private readonly HttpHelper _httpHelper; private readonly CloudFormationHelper _cloudFormationHelper; private readonly ECSHelper _ecsHelper; private readonly App _app; private readonly InMemoryInteractiveService _interactiveService; private bool _isDisposed; private string _stackName; private string _clusterName; private readonly TestAppManager _testAppManager; public ECSFargateDeploymentTest() { var ecsClient = new AmazonECSClient(); _ecsHelper = new ECSHelper(ecsClient); var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); _app = serviceProvider.GetService<App>(); Assert.NotNull(_app); _interactiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(_interactiveService); var cloudFormationClient = new AmazonCloudFormationClient(); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); _httpHelper = new HttpHelper(_interactiveService); _testAppManager = new TestAppManager(); } [Fact] public async Task PerformDeployment() { var stackNamePlaceholder = "{StackName}"; _stackName = $"WebAppWithDockerFile{Guid.NewGuid().ToString().Split('-').Last()}"; _clusterName = $"{_stackName}-cluster"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var configFilePath = Path.Combine(Directory.GetParent(projectPath).FullName, "ECSFargateConfigFile.json"); ConfigFileHelper.ApplyReplacementTokens(new Dictionary<string, string> { { stackNamePlaceholder, _stackName } }, configFilePath); // Deploy var deployArgs = new[] { "deploy", "--project-path", projectPath, "--apply", configFilePath, "--silent", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var cluster = await _ecsHelper.GetCluster(_clusterName); Assert.Equal("ACTIVE", cluster.Status); Assert.Equal(cluster.ClusterName, _clusterName); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); var applicationUrl = deployStdOut.First(line => line.Trim().StartsWith("Endpoint:")) .Split(" ")[1] .Trim(); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(listArgs));; // Verify stack exists in list of deployments var listDeployStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listDeployStdOut, (deployment) => _stackName.Equals(deployment)); // Arrange input for delete await _interactiveService.StdInWriter.WriteAsync("y"); // Confirm delete await _interactiveService.StdInWriter.FlushAsync(); var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics" }; // Delete Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deleteArgs));; // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName), $"{_stackName} still exists."); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } _isDisposed = true; } ~ECSFargateDeploymentTest() { Dispose(false); } } }
140
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.Orchestration; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.ConfigFileDeployment { public class ElasticBeanStalkDeploymentTest : IDisposable { private readonly HttpHelper _httpHelper; private readonly CloudFormationHelper _cloudFormationHelper; private readonly App _app; private readonly InMemoryInteractiveService _interactiveService; private bool _isDisposed; private string _stackName; private readonly TestAppManager _testAppManager; private readonly IServiceProvider _serviceProvider; public ElasticBeanStalkDeploymentTest() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); _app = _serviceProvider.GetService<App>(); Assert.NotNull(_app); _interactiveService = _serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(_interactiveService); _httpHelper = new HttpHelper(_interactiveService); var cloudFormationClient = new AmazonCloudFormationClient(); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); _testAppManager = new TestAppManager(); } [Fact] public async Task PerformDeployment() { // Create the config file var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var stackNamePlaceholder = "{StackName}"; var configFilePath = Path.Combine(Path.GetTempPath(), $"DeploymentSettings-{Guid.NewGuid().ToString().Split('-').Last()}.json"); var expectedConfigFilePath = Path.Combine(Directory.GetParent(projectPath).FullName, "ElasticBeanStalkConfigFile.json"); var optionSettings = new Dictionary<string, object> { {"BeanstalkApplication.CreateNew", true }, {"BeanstalkApplication.ApplicationName", $"{stackNamePlaceholder}-app" }, {"BeanstalkEnvironment.EnvironmentName", $"{stackNamePlaceholder}-dev" }, {"EnvironmentType", "LoadBalanced" }, {"LoadBalancerType", "application" }, {"ApplicationIAMRole.CreateNew", true }, {"XRayTracingSupportEnabled", true } }; await ConfigFileHelper.CreateConfigFile(_serviceProvider, stackNamePlaceholder, "AspNetAppElasticBeanstalkLinux", optionSettings, projectPath, configFilePath, SaveSettingsType.Modified); Assert.True(await ConfigFileHelper.VerifyConfigFileContents(expectedConfigFilePath, configFilePath)); // Deploy _stackName = $"WebAppNoDockerFile{Guid.NewGuid().ToString().Split('-').Last()}"; ConfigFileHelper.ApplyReplacementTokens(new Dictionary<string, string> { {stackNamePlaceholder, _stackName } }, configFilePath); var deployArgs = new[] { "deploy", "--project-path", projectPath, "--apply", configFilePath, "--silent", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deployArgs)); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); // Example: Endpoint: http://52.36.216.238/ var applicationUrl = deployStdOut.First(line => line.Trim().StartsWith("Endpoint:")) .Split(" ")[1] .Trim(); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(listArgs));; // Verify stack exists in list of deployments var listDeployStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listDeployStdOut, (deployment) => _stackName.Equals(deployment)); // Arrange input for delete await _interactiveService.StdInWriter.WriteAsync("y"); // Confirm delete await _interactiveService.StdInWriter.FlushAsync(); var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics" }; // Delete Assert.Equal(CommandReturnCodes.SUCCESS, await _app.Run(deleteArgs));; // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName), $"{_stackName} still exists."); _interactiveService.ReadStdOutStartToEnd(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } _isDisposed = true; } ~ElasticBeanStalkDeploymentTest() { Dispose(false); } } }
148
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Text; namespace AWS.Deploy.CLI.IntegrationTests.Extensions { public static class ReadAllLinesStreamReaderExtension { /// <summary> /// Reads all lines of the stream into a string list /// </summary> /// <param name="reader">Reader that allows line by line reading</param> /// <returns>Read lines</returns> public static IList<string> ReadAllLines(this StreamReader reader) { var lines = new List<string>(); string line; while ((line = reader.ReadLine()) != null) { lines.Add(line); } return lines; } } }
32
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.CLI.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.Utilities; using Microsoft.Extensions.DependencyInjection; namespace AWS.Deploy.CLI.IntegrationTests.Extensions { public static class TestServiceCollectionExtension { /// <summary> /// Extension method for <see cref="IServiceCollection"/> that injects essential app dependencies for testing. /// </summary> /// <param name="serviceCollection"><see cref="IServiceCollection"/> instance that holds the app dependencies.</param> public static void AddTestServices(this IServiceCollection serviceCollection) { serviceCollection.AddSingleton<InMemoryInteractiveService>(); serviceCollection.AddSingleton<IToolInteractiveService>(serviceProvider => serviceProvider.GetService<InMemoryInteractiveService>()); serviceCollection.AddSingleton<IOrchestratorInteractiveService>(serviceProvider => serviceProvider.GetService<InMemoryInteractiveService>()); } } }
33
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using AWS.Deploy.Common; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class CloudFormationHelper { private readonly IAmazonCloudFormation _cloudFormationClient; public CloudFormationHelper(IAmazonCloudFormation cloudFormationClient) { _cloudFormationClient = cloudFormationClient; } public async Task<StackStatus> GetStackStatus(string stackName) { var stack = await GetStackAsync(stackName); return stack.StackStatus; } public async Task<StackStatus> GetStackArn(string stackName) { var stack = await GetStackAsync(stackName); return stack.StackId; } public async Task<bool> IsStackDeleted(string stackName) { try { await GetStackAsync(stackName); } catch (AmazonCloudFormationException cloudFormationException) when (cloudFormationException.Message.Equals($"Stack with id {stackName} does not exist")) { return true; } return false; } public async Task DeleteStack(string stackName) { var request = new DeleteStackRequest() { StackName = stackName }; await _cloudFormationClient.DeleteStackAsync(request); } public async Task<string> GetResourceId(string stackName, string logicalId) { var request = new DescribeStackResourceRequest { StackName = stackName, LogicalResourceId = logicalId }; var response = await _cloudFormationClient.DescribeStackResourceAsync(request); return response.StackResourceDetail.PhysicalResourceId; } private async Task<Stack> GetStackAsync(string stackName) { var response = await _cloudFormationClient.DescribeStacksAsync(new DescribeStacksRequest { StackName = stackName }); return response.Stacks.Count == 0 ? null : response.Stacks[0]; } } }
82
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Amazon.CloudFront; using Amazon.CloudFront.Model; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class CloudFrontHelper { readonly IAmazonCloudFront _cloudFrontClient; public CloudFrontHelper(IAmazonCloudFront cloudFrontClient) { _cloudFrontClient = cloudFrontClient; } public async Task<Distribution> GetDistribution(string id) { var response = await _cloudFrontClient.GetDistributionAsync(new GetDistributionRequest {Id = id }); return response.Distribution; } } }
29
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class CloudWatchLogsHelper { private readonly IAmazonCloudWatchLogs _client; public CloudWatchLogsHelper(IAmazonCloudWatchLogs client) { _client = client; } public async Task<IEnumerable<string>> GetLogMessages(string logGroup) { var logStream = await GetLatestLogStream(logGroup); return await GetLogMessages(logGroup, logStream); } private async Task<IEnumerable<string>> GetLogMessages(string logGroup, string logStreamName) { var request = new GetLogEventsRequest { LogGroupName = logGroup, LogStreamName = logStreamName }; ; var logMessages = new List<string>(); var listStacksPaginator = _client.Paginators.GetLogEvents(request); await foreach (var response in listStacksPaginator.Responses) { // When there are no new events, Events list is returned empty. // Therefore, we want to stop the paginator and return the response. // Otherwise, paginator will end up in an infinite loop. if (response.Events.Count == 0) { break; } var messages = response.Events.Select(e => e.Message); logMessages.AddRange(messages); } return logMessages; } private async Task<string> GetLatestLogStream(string logGroup) { var request = new DescribeLogStreamsRequest { LogGroupName = logGroup }; var response = await _client.DescribeLogStreamsAsync(request); return response.LogStreams.FirstOrDefault()?.LogStreamName; } } }
67
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class ConfigFileHelper { /// <summary> /// Applies replacement tokens to a file /// </summary> public static void ApplyReplacementTokens(Dictionary<string, string> replacements, string filePath) { var content = File.ReadAllText(filePath); foreach (var replacement in replacements) { content = content.Replace(replacement.Key, replacement.Value); } File.WriteAllText(filePath, content); } /// <summary> /// This method create a JSON config file from the specified recipeId and option setting values /// </summary> /// <param name="serviceProvider">The dependency injection container</param> /// <param name="applicationName">The cloud application name used to uniquely identify the app within AWS. Ex - CloudFormation stack name</param> /// <param name="recipeId">The recipeId for the deployment recommendation</param> /// <param name="optionSettings">This is a dictionary with FullyQualifiedId as key and their corresponsing option setting values</param> /// <param name="projectPath">The path to the .NET application that will be deployed</param> /// <param name="configFilePath">The absolute JSON file path where the deployment settings are persisted</param> public static async Task CreateConfigFile(IServiceProvider serviceProvider, string applicationName, string recipeId, Dictionary<string, object> optionSettings, string projectPath, string configFilePath, SaveSettingsType saveSettingsType) { var parser = serviceProvider.GetService<IProjectDefinitionParser>(); var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>(); var deploymentSettingHandler = serviceProvider.GetRequiredService<IDeploymentSettingsHandler>(); var orchestratorSession = new OrchestratorSession(parser.Parse(projectPath).Result); var cloudApplication = new CloudApplication(applicationName, "", CloudApplicationResourceType.CloudFormationStack, recipeId); var recommendationEngine = new RecommendationEngine(orchestratorSession, serviceProvider.GetService<IRecipeHandler>()); var recommendations = await recommendationEngine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, recipeId)); foreach (var item in optionSettings) { await optionSettingHandler.SetOptionSettingValue(selectedRecommendation, item.Key, item.Value, skipValidation: true); } await deploymentSettingHandler.SaveSettings(new SaveSettingsConfiguration(saveSettingsType, configFilePath), selectedRecommendation, cloudApplication, orchestratorSession); } /// <summary> /// Verifies that the file contents are the same by accounting for os-specific new line delimiters. /// </summary> /// <returns>true if the contents match, false otherwise</returns> public static async Task<bool> VerifyConfigFileContents(string expectedContentPath, string actualContentPath) { var expectContent = await File.ReadAllTextAsync(expectedContentPath); var actualContent = await File.ReadAllTextAsync(actualContentPath); actualContent = SanitizeFileContents(actualContent); expectContent = SanitizeFileContents(expectContent); return string.Equals(expectContent, actualContent); } private static string SanitizeFileContents(string content) { return content.Replace("\r\n", Environment.NewLine) .Replace("\n", Environment.NewLine) .Replace("\r\r\n", Environment.NewLine) .Trim(); } } }
85
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.ECS; using Amazon.ECS.Model; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class ECSHelper { private readonly IAmazonECS _client; public ECSHelper(IAmazonECS client) { _client = client; } public async Task<string> GetLogGroup(string clusterName) { var taskDefinition = await GetTaskDefinition(clusterName); return await GetAwsLogGroup(taskDefinition); } public async Task<Cluster> GetCluster(string clusterName) { var request = new DescribeClustersRequest { Clusters = new List<string> { clusterName } }; var response = await _client.DescribeClustersAsync(request); return response.Clusters.First(); } private async Task<string> GetTaskDefinition(string clusterName) { var request = new ListTaskDefinitionsRequest(); var response = await _client.ListTaskDefinitionsAsync(request); return response.TaskDefinitionArns.First(taskDefinitionArn => { // Example: arn:aws:ecs:us-west-2:727033484140:task-definition/ConsoleAppServiceTaskDefinition6663F6FD:1 var taskDefinitionName = taskDefinitionArn.Split('/')[1]; return taskDefinitionName.StartsWith(clusterName); }); } private async Task<string> GetAwsLogGroup(string taskDefinition) { var request = new DescribeTaskDefinitionRequest { TaskDefinition = taskDefinition }; var response = await _client.DescribeTaskDefinitionAsync(request); var containerDefinition = response.TaskDefinition.ContainerDefinitions.First(); return containerDefinition.LogConfiguration.Options["awslogs-group"]; } } }
66
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using Amazon.S3; using Amazon.S3.Transfer; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class ElasticBeanstalkHelper { private readonly IAmazonElasticBeanstalk _client; private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly IToolInteractiveService _interactiveService; public ElasticBeanstalkHelper(IAmazonElasticBeanstalk client, IAWSResourceQueryer awsResourceQueryer, IToolInteractiveService toolInteractiveService) { _client = client; _awsResourceQueryer = awsResourceQueryer; _interactiveService = toolInteractiveService; } public async Task CreateApplicationAsync(string applicationName) { _interactiveService.WriteLine($"Create Elastic Beanstalk application: {applicationName}"); await _client.CreateApplicationAsync(new CreateApplicationRequest { ApplicationName = applicationName, Description = "aws-dotnet-deploy-integ-test" }); } public async Task CreateApplicationVersionAsync(string applicationName, string versionLabel, string deploymentPackage) { _interactiveService.WriteLine($"Creating new application version for {applicationName}: {versionLabel}"); var bucketName = (await _client.CreateStorageLocationAsync()).S3Bucket; var key = string.Format("{0}/AWSDeploymentArchive_{0}_{1}{2}", applicationName.Replace(' ', '-'), versionLabel.Replace(' ', '-'), new FileManager().GetExtension(deploymentPackage)); await UploadToS3Async(bucketName, key, deploymentPackage); await _client.CreateApplicationVersionAsync(new CreateApplicationVersionRequest { ApplicationName = applicationName, VersionLabel = versionLabel, SourceBundle = new S3Location { S3Bucket = bucketName, S3Key = key } }); } public async Task<bool> CreateEnvironmentAsync(string applicationName, string environmentName, string versionLabel, BeanstalkPlatformType platformType, string ec2Role) { _interactiveService.WriteLine($"Creating new Elastic Beanstalk environment {environmentName} with versionLabel {versionLabel}"); var startingEventDate = DateTime.Now; await _client.CreateEnvironmentAsync(new CreateEnvironmentRequest { ApplicationName = applicationName, EnvironmentName = environmentName, VersionLabel = versionLabel, PlatformArn = (await _awsResourceQueryer.GetLatestElasticBeanstalkPlatformArn(platformType)).PlatformArn, OptionSettings = new List<ConfigurationOptionSetting> { new ConfigurationOptionSetting("aws:autoscaling:launchconfiguration", "IamInstanceProfile", ec2Role), new ConfigurationOptionSetting("aws:elasticbeanstalk:healthreporting:system", "SystemType", "basic") } }); return await WaitForEnvironmentCreateCompletion(applicationName, environmentName, startingEventDate); } public async Task<bool> DeleteApplication(string applicationName, string environmentName) { _interactiveService.WriteLine($"Deleting Elastic Beanstalk application: {applicationName}"); _interactiveService.WriteLine($"Deleting Elastic Beanstalk environment: {environmentName}"); await _client.DeleteApplicationAsync(new DeleteApplicationRequest { ApplicationName = applicationName, TerminateEnvByForce = true }); return await WaitForEnvironmentDeletion(environmentName); } public async Task<bool> VerifyEnvironmentVersionLabel(string environmentName, string expectedVersionLabel) { var envDescription = await _awsResourceQueryer.DescribeElasticBeanstalkEnvironment(environmentName); _interactiveService.WriteLine($"The Elastic Beanstalk environment is pointing to \"{envDescription.VersionLabel}\" version label"); return string.Equals(envDescription.VersionLabel, expectedVersionLabel); } private async Task<bool> WaitForEnvironmentCreateCompletion(string applicationName, string environmentName, DateTime startingEventDate) { _interactiveService.WriteLine("Waiting for environment update to complete"); var success = true; var environment = new EnvironmentDescription(); var lastEventDate = startingEventDate; var requestEvents = new DescribeEventsRequest { ApplicationName = applicationName, EnvironmentName = environmentName }; var requestEnvironment = new DescribeEnvironmentsRequest { ApplicationName = applicationName, EnvironmentNames = new List<string> { environmentName } }; do { Thread.Sleep(5000); var responseEnvironments = await _client.DescribeEnvironmentsAsync(requestEnvironment); environment = responseEnvironments.Environments[0]; requestEvents.StartTimeUtc = lastEventDate; var responseEvents = await _client.DescribeEventsAsync(requestEvents); if (responseEvents.Events.Any()) { for (var i = responseEvents.Events.Count - 1; i >= 0; i--) { var evnt = responseEvents.Events[i]; if (evnt.EventDate <= lastEventDate) continue; _interactiveService.WriteLine(evnt.EventDate.ToLocalTime() + " " + evnt.Severity + " " + evnt.Message); if (evnt.Severity == EventSeverity.ERROR || evnt.Severity == EventSeverity.FATAL) { success = false; } } lastEventDate = responseEvents.Events[0].EventDate; } } while (environment.Status == EnvironmentStatus.Launching || environment.Status == EnvironmentStatus.Updating); return success; } private async Task<bool> WaitForEnvironmentDeletion(string environmentName) { var attemptCount = 0; const int maxAttempts = 7; while (attemptCount < maxAttempts) { attemptCount += 1; var response = await _client.DescribeEnvironmentsAsync(new DescribeEnvironmentsRequest { EnvironmentNames = new List<string> { environmentName } }); if (!response.Environments.Any() || response.Environments.Single().Status == EnvironmentStatus.Terminated) return true; await Task.Delay(GetWaitTime(attemptCount)); } return false; } private TimeSpan GetWaitTime(int attemptCount) { var waitTime = Math.Pow(2, attemptCount) * 5; return TimeSpan.FromSeconds(waitTime); } private async Task UploadToS3Async(string bucketName, string key, string filePath) { _interactiveService.WriteLine("Uploading application deployment package to S3..."); using (var stream = File.OpenRead(filePath)) { var request = new TransferUtilityUploadRequest() { BucketName = bucketName, Key = key, InputStream = stream }; var s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USWest2); await new TransferUtility(s3Client).UploadAsync(request); } } } }
202
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Net.Http; using System.Threading.Tasks; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.Common; using AWS.Deploy.Orchestration.Utilities; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class HttpHelper { private readonly InMemoryInteractiveService _interactiveService; public HttpHelper(InMemoryInteractiveService interactiveService) { _interactiveService = interactiveService; } public async Task WaitUntilSuccessStatusCode(string url, TimeSpan frequency, TimeSpan timeout) { using var client = new HttpClient(); try { await Orchestration.Utilities.Helpers.WaitUntil(async () => { var httpResponseMessage = await client.GetAsync(url); return httpResponseMessage.IsSuccessStatusCode; }, frequency, timeout); } catch (TimeoutException ex) { _interactiveService.WriteErrorLine(ex.PrettyPrint()); Assert.True(false, $"{url} URL is not reachable."); } } } }
43
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Linq; using System.Threading.Tasks; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using AWS.Deploy.Common.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class IAMHelper { private readonly IAmazonIdentityManagementService _client; private readonly IToolInteractiveService _interactiveService; private readonly IAWSResourceQueryer _awsResourceQueryer; public IAMHelper(IAmazonIdentityManagementService client, IAWSResourceQueryer awsResourceQueryer, IToolInteractiveService toolInteractiveService) { _client = client; _awsResourceQueryer = awsResourceQueryer; _interactiveService = toolInteractiveService; } /// <summary> /// Delete an existing IAM Role by first removing the role from an existing instance profile and deleting that profile. /// </summary> public async Task DeleteRoleAndInstanceProfileAfterBeanstalkEnvionmentDeployment(string roleName) { var existingRoles = await _awsResourceQueryer.ListOfIAMRoles("ec2.amazonaws.com"); var role = existingRoles.FirstOrDefault(x => string.Equals(roleName, x.RoleName)); if (role != null) { await _client.RemoveRoleFromInstanceProfileAsync(new RemoveRoleFromInstanceProfileRequest { RoleName = roleName, InstanceProfileName = roleName }); await _client.DeleteInstanceProfileAsync(new DeleteInstanceProfileRequest() { InstanceProfileName = roleName }); await _client.DeleteRoleAsync(new DeleteRoleRequest { RoleName = role.RoleName }); } } public async Task CreateRoleForBeanstalkEnvionmentDeployment(string roleName) { _interactiveService.WriteLine($"Creating role {roleName} for deployment to Elastic Beanstalk environemnt"); var existingRoles = await _awsResourceQueryer.ListOfIAMRoles("ec2.amazonaws.com"); var role = existingRoles.FirstOrDefault(x => string.Equals(roleName, x.RoleName)); if (role != null) { _interactiveService.WriteLine($" The role {roleName} already exists"); } else { var assumeRolepolicyDocument = @"{ 'Version':'2008-10-17', 'Statement':[ { 'Effect':'Allow', 'Principal':{ 'Service':'ec2.amazonaws.com' }, 'Action':'sts:AssumeRole' } ] }"; await _client.CreateRoleAsync(new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = assumeRolepolicyDocument.Replace("'", "\""), MaxSessionDuration = 7200 }); } InstanceProfile instanceProfile = null; try { instanceProfile = (await _client.GetInstanceProfileAsync(new GetInstanceProfileRequest() { InstanceProfileName = roleName })).InstanceProfile; } catch (NoSuchEntityException) { } // Check to see if an instance profile exists for this role and if not create it. if (instanceProfile == null) { _interactiveService.WriteLine($"Creating new IAM Instance Profile {roleName}"); await _client.CreateInstanceProfileAsync(new CreateInstanceProfileRequest() { InstanceProfileName = roleName }); _interactiveService.WriteLine($"Attaching IAM role {roleName} to Instance Profile {roleName}"); await _client.AddRoleToInstanceProfileAsync(new AddRoleToInstanceProfileRequest() { RoleName = roleName, InstanceProfileName = roleName }); } // If it already exists see if this role is already assigned and if not assign it. else { _interactiveService.WriteLine($"IAM Instance Profile {roleName} already exists"); if (instanceProfile.Roles.FirstOrDefault(x => x.RoleName == roleName) == null) { _interactiveService.WriteLine($"Attaching IAM role {roleName} to Instance Profile {roleName}"); await _client.AddRoleToInstanceProfileAsync(new AddRoleToInstanceProfileRequest() { RoleName = roleName, InstanceProfileName = roleName }); } } } } }
126
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public class TestEnvironmentVariableManager : IEnvironmentVariableManager { public readonly Dictionary<string, string> store = new Dictionary<string, string>(); public string GetEnvironmentVariable(string variable) { return store.ContainsKey(variable) ? store[variable] : null; } public void SetEnvironmentVariable(string variable, string value) { if (string.Equals(variable, "AWS_DOTNET_DEPLOYTOOL_WORKSPACE")) store[variable] = value; else Environment.SetEnvironmentVariable(variable, value); } } }
29
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Text; using AWS.Deploy.Orchestration.Utilities; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace AWS.Deploy.CLI.IntegrationTests.Helpers { public static class Utilities { /// <summary> /// This method sets a custom workspace which will be used by the deploy tool to create and run the CDK project and any temporary files during the deployment. /// It also adds a nuget.config file that references a private nuget-cache. This cache holds the latest (in-development/unreleased) version of AWS.Deploy.Recipes.CDK.Common.nupkg file /// </summary> public static void OverrideDefaultWorkspace(ServiceProvider serviceProvider, string customWorkspace) { var environmentVariableManager = serviceProvider.GetRequiredService<IEnvironmentVariableManager>(); environmentVariableManager.SetEnvironmentVariable("AWS_DOTNET_DEPLOYTOOL_WORKSPACE", customWorkspace); Directory.CreateDirectory(customWorkspace); var nugetCachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".aws-dotnet-deploy", "Projects", "nuget-cache"); nugetCachePath = nugetCachePath.Replace(Path.DirectorySeparatorChar, '/'); var nugetConfigContent = $@" <?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <packageSources> <add key=""deploy-tool-cache"" value=""{nugetCachePath}"" /> </packageSources> </configuration> ".Trim(); File.WriteAllText(Path.Combine(customWorkspace, "nuget.config"), nugetConfigContent); } } }
42
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using AWS.Deploy.CLI.Utilities; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration; using Xunit; using Task = System.Threading.Tasks.Task; using Should; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.Common.Recipes; using Moq; using AWS.Deploy.Common.Recipes.Validation; namespace AWS.Deploy.CLI.IntegrationTests.SaveCdkDeploymentProject { public class CustomRecipeLocatorTests : IDisposable { private readonly CommandLineWrapper _commandLineWrapper; private readonly InMemoryInteractiveService _inMemoryInteractiveService; public CustomRecipeLocatorTests() { _inMemoryInteractiveService = new InMemoryInteractiveService(); _commandLineWrapper = new CommandLineWrapper(_inMemoryInteractiveService); } [Fact] public async Task LocateCustomRecipePathsWithManifestFile() { var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var webAppWithDockerCsproj = Path.Combine(webAppWithDockerFilePath, "WebAppWithDockerFile.csproj"); var solutionDirectoryPath = tempDirectoryPath; var recipeHandler = BuildRecipeHandler(); await _commandLineWrapper.Run("git init", tempDirectoryPath); // ARRANGE - Create 2 CDK deployment projects that contain the custom recipe snapshot await Utilities.CreateCDKDeploymentProject(webAppWithDockerFilePath, Path.Combine(tempDirectoryPath, "MyCdkApp1")); await Utilities.CreateCDKDeploymentProject(webAppWithDockerFilePath, Path.Combine(tempDirectoryPath, "MyCdkApp2")); // ACT - Fetch custom recipes corresponding to the same target application that has a deployment-manifest file. var customRecipePaths = await recipeHandler.LocateCustomRecipePaths(webAppWithDockerCsproj, solutionDirectoryPath); // ASSERT File.Exists(Path.Combine(webAppWithDockerFilePath, "aws-deployments.json")).ShouldBeTrue(); customRecipePaths.Count.ShouldEqual(2, $"Custom recipes found: {Environment.NewLine} {string.Join(Environment.NewLine, customRecipePaths)}"); customRecipePaths.ShouldContain(Path.Combine(tempDirectoryPath, "MyCdkApp1")); customRecipePaths.ShouldContain(Path.Combine(tempDirectoryPath, "MyCdkApp1")); } [Fact] public async Task LocateCustomRecipePathsWithoutManifestFile() { var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var webAppNoDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppNoDockerFile"); var webAppWithDockerCsproj = Path.Combine(webAppWithDockerFilePath, "WebAppWithDockerFile.csproj"); var webAppNoDockerCsproj = Path.Combine(webAppNoDockerFilePath, "WebAppNoDockerFile.csproj"); var solutionDirectoryPath = tempDirectoryPath; var recipeHandler = BuildRecipeHandler(); await _commandLineWrapper.Run("git init", tempDirectoryPath); // ARRANGE - Create 2 CDK deployment projects that contain the custom recipe snapshot await Utilities.CreateCDKDeploymentProject(webAppWithDockerFilePath, Path.Combine(tempDirectoryPath, "MyCdkApp1")); await Utilities.CreateCDKDeploymentProject(webAppWithDockerFilePath, Path.Combine(tempDirectoryPath, "MyCdkApp2")); // ACT - Fetch custom recipes corresponding to a different target application (under source control) without a deployment-manifest file. var customRecipePaths = await recipeHandler.LocateCustomRecipePaths(webAppNoDockerCsproj, solutionDirectoryPath); // ASSERT File.Exists(Path.Combine(webAppNoDockerFilePath, "aws-deployments.json")).ShouldBeFalse(); customRecipePaths.Count.ShouldEqual(2, $"Custom recipes found: {Environment.NewLine} {string.Join(Environment.NewLine, customRecipePaths)}"); customRecipePaths.ShouldContain(Path.Combine(tempDirectoryPath, "MyCdkApp1")); customRecipePaths.ShouldContain(Path.Combine(tempDirectoryPath, "MyCdkApp1")); } private IRecipeHandler BuildRecipeHandler() { var directoryManager = new DirectoryManager(); var fileManager = new FileManager(); var deploymentManifestEngine = new DeploymentManifestEngine(directoryManager, fileManager); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); return new RecipeHandler(deploymentManifestEngine, _inMemoryInteractiveService, directoryManager, fileManager, optionSettingHandler, validatorFactory); } protected virtual void Dispose(bool disposing) { if (disposing) { _inMemoryInteractiveService.ReadStdOutStartToEnd(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~CustomRecipeLocatorTests() => Dispose(false); } }
109
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AWS.Deploy.CLI.Utilities; using AWS.Deploy.CLI.IntegrationTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.DockerEngine; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Recipes; using Moq; using Xunit; using Should; using AWS.Deploy.Common.Recipes; using Newtonsoft.Json; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.Orchestration.Utilities; using AWS.Deploy.Orchestration.ServiceHandlers; using AWS.Deploy.Common.Recipes.Validation; namespace AWS.Deploy.CLI.IntegrationTests.SaveCdkDeploymentProject { public class RecommendationTests : IDisposable { private readonly CommandLineWrapper _commandLineWrapper; private readonly InMemoryInteractiveService _inMemoryInteractiveService; public RecommendationTests() { _inMemoryInteractiveService = new InMemoryInteractiveService(); _commandLineWrapper = new CommandLineWrapper(_inMemoryInteractiveService); } [Fact] public async Task GenerateRecommendationsForDeploymentProject() { // ARRANGE var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var orchestrator = await GetOrchestrator(webAppWithDockerFilePath); await _commandLineWrapper.Run("git init", tempDirectoryPath); // ACT var recommendations = await orchestrator.GenerateRecommendationsToSaveDeploymentProject(); // ASSERT var anyNonCdkRecommendations = recommendations.Where(x => x.Recipe.DeploymentType != DeploymentTypes.CdkProject); Assert.False(anyNonCdkRecommendations.Any()); Assert.NotNull(recommendations.FirstOrDefault(x => x.Recipe.Id == "AspNetAppEcsFargate")); Assert.NotNull(recommendations.FirstOrDefault(x => x.Recipe.Id == "AspNetAppElasticBeanstalkLinux")); } [Fact] public async Task GenerateRecommendationsWithoutCustomRecipes() { // ARRANGE var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var orchestrator = await GetOrchestrator(webAppWithDockerFilePath); await _commandLineWrapper.Run("git init", tempDirectoryPath); // ACT var recommendations = await orchestrator.GenerateDeploymentRecommendations(); // ASSERT recommendations.Count.ShouldEqual(7); recommendations[0].Name.ShouldEqual("ASP.NET Core App to Amazon ECS using AWS Fargate"); // default recipe recommendations[1].Name.ShouldEqual("ASP.NET Core App to AWS App Runner"); // default recipe recommendations[2].Name.ShouldEqual("ASP.NET Core App to AWS Elastic Beanstalk on Linux"); // default recipe recommendations[3].Name.ShouldEqual("ASP.NET Core App to AWS Elastic Beanstalk on Windows"); // default recipe recommendations[4].Name.ShouldEqual("ASP.NET Core App to Existing AWS Elastic Beanstalk Environment"); // default recipe recommendations[5].Name.ShouldEqual("ASP.NET Core App to Existing AWS Elastic Beanstalk Windows Environment"); // default recipe recommendations[6].Name.ShouldEqual("Container Image to Amazon Elastic Container Registry (ECR)"); // default recipe } [Fact] public async Task GenerateRecommendationsFromCustomRecipesWithManifestFile() { // ARRANGE var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var orchestrator = await GetOrchestrator(webAppWithDockerFilePath); await _commandLineWrapper.Run("git init", tempDirectoryPath); var saveDirectoryPathEcsProject = Path.Combine(tempDirectoryPath, "ECS-CDK"); var saveDirectoryPathEbsProject = Path.Combine(tempDirectoryPath, "EBS-CDK"); var customEcsRecipeName = "Custom ECS Fargate Recipe"; var customEbsRecipeName = "Custom Elastic Beanstalk Recipe"; // select ECS Fargate recipe await Utilities.CreateCDKDeploymentProjectWithRecipeName(webAppWithDockerFilePath, customEcsRecipeName, "1", saveDirectoryPathEcsProject); // select Elastic Beanstalk recipe await Utilities.CreateCDKDeploymentProjectWithRecipeName(webAppWithDockerFilePath, customEbsRecipeName, "3", saveDirectoryPathEbsProject); // Get custom recipe IDs var customEcsRecipeId = await GetCustomRecipeId(Path.Combine(saveDirectoryPathEcsProject, "ECS-CDK.recipe")); var customEbsRecipeId = await GetCustomRecipeId(Path.Combine(saveDirectoryPathEbsProject, "EBS-CDK.recipe")); // ACT var recommendations = await orchestrator.GenerateDeploymentRecommendations(); // ASSERT - Recipes are ordered by priority recommendations.Count.ShouldEqual(9); recommendations[0].Name.ShouldEqual(customEcsRecipeName); // custom recipe recommendations[1].Name.ShouldEqual(customEbsRecipeName); // custom recipe recommendations[2].Name.ShouldEqual("ASP.NET Core App to Amazon ECS using AWS Fargate"); // default recipe recommendations[3].Name.ShouldEqual("ASP.NET Core App to AWS App Runner"); // default recipe recommendations[4].Name.ShouldEqual("ASP.NET Core App to AWS Elastic Beanstalk on Linux"); // default recipe recommendations[5].Name.ShouldEqual("ASP.NET Core App to AWS Elastic Beanstalk on Windows"); // default recipe recommendations[6].Name.ShouldEqual("ASP.NET Core App to Existing AWS Elastic Beanstalk Environment"); // default recipe recommendations[7].Name.ShouldEqual("ASP.NET Core App to Existing AWS Elastic Beanstalk Windows Environment"); // default recipe recommendations[8].Name.ShouldEqual("Container Image to Amazon Elastic Container Registry (ECR)"); // default recipe // ASSERT - Recipe paths recommendations[0].Recipe.RecipePath.ShouldEqual(Path.Combine(saveDirectoryPathEcsProject, "ECS-CDK.recipe")); recommendations[1].Recipe.RecipePath.ShouldEqual(Path.Combine(saveDirectoryPathEbsProject, "EBS-CDK.recipe")); // ASSERT - custom recipe IDs recommendations[0].Recipe.Id.ShouldEqual(customEcsRecipeId); recommendations[1].Recipe.Id.ShouldEqual(customEbsRecipeId); File.Exists(Path.Combine(webAppWithDockerFilePath, "aws-deployments.json")).ShouldBeTrue(); } [Fact] public async Task GenerateRecommendationsFromCustomRecipesWithoutManifestFile() { // ARRANGE var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var webAppNoDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppNoDockerFile"); var orchestrator = await GetOrchestrator(webAppNoDockerFilePath); await _commandLineWrapper.Run("git init", tempDirectoryPath); var saveDirectoryPathEcsProject = Path.Combine(tempDirectoryPath, "ECS-CDK"); var saveDirectoryPathEbsProject = Path.Combine(tempDirectoryPath, "EBS-CDK"); var customEcsRecipeName = "Custom ECS Fargate Recipe"; var customEbsRecipeName = "Custom Elastic Beanstalk Recipe"; // Select ECS Fargate recipe await Utilities.CreateCDKDeploymentProjectWithRecipeName(webAppWithDockerFilePath, customEcsRecipeName, "1", saveDirectoryPathEcsProject); // Select Elastic Beanstalk recipe await Utilities.CreateCDKDeploymentProjectWithRecipeName(webAppWithDockerFilePath, customEbsRecipeName, "3", saveDirectoryPathEbsProject); // Get custom recipe IDs var customEcsRecipeId = await GetCustomRecipeId(Path.Combine(saveDirectoryPathEcsProject, "ECS-CDK.recipe")); var customEbsRecipeId = await GetCustomRecipeId(Path.Combine(saveDirectoryPathEbsProject, "EBS-CDK.recipe")); // ACT var recommendations = await orchestrator.GenerateDeploymentRecommendations(); // ASSERT - Recipes are ordered by priority recommendations.Count.ShouldEqual(8); recommendations[0].Name.ShouldEqual(customEbsRecipeName); recommendations[1].Name.ShouldEqual(customEcsRecipeName); recommendations[2].Name.ShouldEqual("ASP.NET Core App to AWS Elastic Beanstalk on Linux"); recommendations[3].Name.ShouldEqual("ASP.NET Core App to AWS Elastic Beanstalk on Windows"); recommendations[4].Name.ShouldEqual("ASP.NET Core App to Amazon ECS using AWS Fargate"); recommendations[5].Name.ShouldEqual("ASP.NET Core App to AWS App Runner"); recommendations[6].Name.ShouldEqual("ASP.NET Core App to Existing AWS Elastic Beanstalk Environment"); recommendations[7].Name.ShouldEqual("ASP.NET Core App to Existing AWS Elastic Beanstalk Windows Environment"); // ASSERT - Recipe paths recommendations[0].Recipe.RecipePath.ShouldEqual(Path.Combine(saveDirectoryPathEbsProject, "EBS-CDK.recipe")); recommendations[1].Recipe.RecipePath.ShouldEqual(Path.Combine(saveDirectoryPathEcsProject, "ECS-CDK.recipe")); // ASSERT - Custom recipe IDs recommendations[0].Recipe.Id.ShouldEqual(customEbsRecipeId); recommendations[1].Recipe.Id.ShouldEqual(customEcsRecipeId); File.Exists(Path.Combine(webAppNoDockerFilePath, "aws-deployments.json")).ShouldBeFalse(); } [Fact] public async Task GenerateRecommendationsFromCompatibleDeploymentProject() { // ARRANGE var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var orchestrator = await GetOrchestrator(webAppWithDockerFilePath); await _commandLineWrapper.Run("git init", tempDirectoryPath); var saveDirectoryPathEcsProject = Path.Combine(tempDirectoryPath, "ECS-CDK"); var customEcsRecipeName = "Custom ECS Fargate Recipe"; // Select ECS Fargate recipe await Utilities.CreateCDKDeploymentProjectWithRecipeName(webAppWithDockerFilePath, customEcsRecipeName, "1", saveDirectoryPathEcsProject); // Get custom recipe IDs var customEcsRecipeId = await GetCustomRecipeId(Path.Combine(saveDirectoryPathEcsProject, "ECS-CDK.recipe")); // ACT var recommendations = await orchestrator.GenerateRecommendationsFromSavedDeploymentProject(saveDirectoryPathEcsProject); // ASSERT recommendations.Count.ShouldEqual(1); recommendations[0].Name.ShouldEqual("Custom ECS Fargate Recipe"); recommendations[0].Recipe.Id.ShouldEqual(customEcsRecipeId); recommendations[0].Recipe.RecipePath.ShouldEqual(Path.Combine(saveDirectoryPathEcsProject, "ECS-CDK.recipe")); } [Fact] public async Task GenerateRecommendationsFromIncompatibleDeploymentProject() { // ARRANGE var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var webAppWithDockerFilePath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var blazorAppPath = Path.Combine(tempDirectoryPath, "testapps", "BlazorWasm60"); var orchestrator = await GetOrchestrator(blazorAppPath); await _commandLineWrapper.Run("git init", tempDirectoryPath); var saveDirectoryPathEcsProject = Path.Combine(tempDirectoryPath, "ECS-CDK"); await Utilities.CreateCDKDeploymentProject(webAppWithDockerFilePath, saveDirectoryPathEcsProject); // ACT var recommendations = await orchestrator.GenerateRecommendationsFromSavedDeploymentProject(saveDirectoryPathEcsProject); // ASSERT recommendations.ShouldBeEmpty(); } private async Task<Orchestrator> GetOrchestrator(string targetApplicationProjectPath) { var awsResourceQueryer = new TestToolAWSResourceQueryer(); var directoryManager = new DirectoryManager(); var fileManager = new FileManager(); var deploymentManifestEngine = new DeploymentManifestEngine(directoryManager, fileManager); var environmentVariableManager = new Mock<IEnvironmentVariableManager>().Object; var deployToolWorkspaceMetadata = new DeployToolWorkspaceMetadata(directoryManager, environmentVariableManager, fileManager); var localUserSettingsEngine = new LocalUserSettingsEngine(fileManager, directoryManager, deployToolWorkspaceMetadata); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); var recipeHandler = new RecipeHandler(deploymentManifestEngine, _inMemoryInteractiveService, directoryManager, fileManager, optionSettingHandler, validatorFactory); var projectDefinition = await new ProjectDefinitionParser(fileManager, directoryManager).Parse(targetApplicationProjectPath); var session = new OrchestratorSession(projectDefinition); return new Orchestrator(session, _inMemoryInteractiveService, new Mock<ICdkProjectHandler>().Object, new Mock<ICDKManager>().Object, new Mock<ICDKVersionDetector>().Object, awsResourceQueryer, new Mock<IDeploymentBundleHandler>().Object, localUserSettingsEngine, new Mock<IDockerEngine>().Object, recipeHandler, fileManager, directoryManager, new Mock<IAWSServiceHandler>().Object, new OptionSettingHandler(new Mock<IValidatorFactory>().Object), deployToolWorkspaceMetadata); } private async Task<string> GetCustomRecipeId(string recipeFilePath) { var recipeBody = await File.ReadAllTextAsync(recipeFilePath); var recipe = JsonConvert.DeserializeObject<RecipeDefinition>(recipeBody); return recipe.Id; } protected virtual void Dispose(bool disposing) { if (disposing) { _inMemoryInteractiveService.ReadStdOutStartToEnd(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~RecommendationTests() => Dispose(false); } }
293
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using Amazon.CloudFormation; using Amazon.ECS; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Helpers; using AWS.Deploy.CLI.IntegrationTests.Services; using Microsoft.Extensions.DependencyInjection; using Xunit; using Task = System.Threading.Tasks.Task; namespace AWS.Deploy.CLI.IntegrationTests.SaveCdkDeploymentProject { public class RedeploymentTests : IDisposable { private readonly HttpHelper _httpHelper; private readonly CloudFormationHelper _cloudFormationHelper; private readonly ECSHelper _ecsHelper; private readonly App _app; private readonly InMemoryInteractiveService _interactiveService; private bool _isDisposed; private string _stackName; public RedeploymentTests() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); _app = serviceProvider.GetService<App>(); Assert.NotNull(_app); _interactiveService = serviceProvider.GetService<InMemoryInteractiveService>(); Assert.NotNull(_interactiveService); _httpHelper = new HttpHelper(_interactiveService); var cloudFormationClient = new AmazonCloudFormationClient(); _cloudFormationHelper = new CloudFormationHelper(cloudFormationClient); var ecsClient = new AmazonECSClient(); _ecsHelper = new ECSHelper(ecsClient); } [Fact] public async Task AttemptWorkFlow() { _stackName = $"WebAppWithDockerFile{Guid.NewGuid().ToString().Split('-').Last()}"; var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); var projectPath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var compatibleDeploymentProjectPath = Path.Combine(tempDirectoryPath, "DeploymentProjects", "CompatibleCdkApp"); var incompatibleDeploymentProjectPath = Path.Combine(tempDirectoryPath, "DeploymentProjects", "IncompatibleCdkApp"); // perform inital deployment using ECS Fargate recipe await PerformInitialDeployment(projectPath); // Create a compatible CDK deployment project using the ECS recipe await Utilities.CreateCDKDeploymentProjectWithRecipeName(projectPath, "Custom ECS Fargate Recipe", "1", compatibleDeploymentProjectPath, underSourceControl: false); // Create an incompatible CDK deployment project using the App runner recipe await Utilities.CreateCDKDeploymentProjectWithRecipeName(projectPath, "Custom App Runner Recipe", "2", incompatibleDeploymentProjectPath, underSourceControl: false); // attempt re-deployment using incompatible CDK project var deployArgs = new[] { "deploy", "--project-path", projectPath, "--deployment-project", incompatibleDeploymentProjectPath, "--application-name", _stackName, "--diagnostics" }; var returnCode = await _app.Run(deployArgs); Assert.Equal(CommandReturnCodes.USER_ERROR, returnCode); // attempt re-deployment using compatible CDK project await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); deployArgs = new[] { "deploy", "--project-path", projectPath, "--deployment-project", compatibleDeploymentProjectPath, "--application-name", _stackName, "--diagnostics" }; returnCode = await _app.Run(deployArgs); Assert.Equal(CommandReturnCodes.SUCCESS, returnCode); Assert.Equal(StackStatus.UPDATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var cluster = await _ecsHelper.GetCluster(_stackName); Assert.Equal(TaskDefinitionStatus.ACTIVE, cluster.Status); // Delete stack await DeleteStack(); } private async Task PerformInitialDeployment(string projectPath) { // Arrange input for deploy await _interactiveService.StdInWriter.WriteLineAsync("1"); // Select ECS Fargate recommendation await _interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default option settings await _interactiveService.StdInWriter.FlushAsync(); // Deploy var deployArgs = new[] { "deploy", "--project-path", projectPath, "--application-name", _stackName, "--diagnostics" }; var returnCode = await _app.Run(deployArgs); Assert.Equal(CommandReturnCodes.SUCCESS, returnCode); // Verify application is deployed and running Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatus(_stackName)); var cluster = await _ecsHelper.GetCluster(_stackName); Assert.Equal(TaskDefinitionStatus.ACTIVE, cluster.Status); var deployStdOut = _interactiveService.StdOutReader.ReadAllLines(); var applicationUrl = deployStdOut.First(line => line.Trim().StartsWith("Endpoint:")) .Split(" ")[1] .Trim(); // URL could take few more minutes to come live, therefore, we want to wait and keep trying for a specified timeout await _httpHelper.WaitUntilSuccessStatusCode(applicationUrl, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(5)); // list var listArgs = new[] { "list-deployments", "--diagnostics" }; returnCode = await _app.Run(listArgs); Assert.Equal(CommandReturnCodes.SUCCESS, returnCode); // Verify stack exists in list of deployments var listDeployStdOut = _interactiveService.StdOutReader.ReadAllLines().Select(x => x.Split()[0]).ToList(); Assert.Contains(listDeployStdOut, (deployment) => _stackName.Equals(deployment)); } private async Task DeleteStack() { // Arrange input for delete await _interactiveService.StdInWriter.WriteAsync("y"); // Confirm delete await _interactiveService.StdInWriter.FlushAsync(); var deleteArgs = new[] { "delete-deployment", _stackName, "--diagnostics" }; // Delete var returnCode = await _app.Run(deleteArgs); Assert.Equal(CommandReturnCodes.SUCCESS, returnCode); // Verify application is deleted Assert.True(await _cloudFormationHelper.IsStackDeleted(_stackName), $"{_stackName} still exists."); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { var isStackDeleted = _cloudFormationHelper.IsStackDeleted(_stackName).GetAwaiter().GetResult(); if (!isStackDeleted) { _cloudFormationHelper.DeleteStack(_stackName).GetAwaiter().GetResult(); } _interactiveService.ReadStdOutStartToEnd(); } _isDisposed = true; } ~RedeploymentTests() { Dispose(false); } } }
173
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.IntegrationTests.Services; using AWS.Deploy.CLI.Utilities; using Xunit; using Task = System.Threading.Tasks.Task; using Newtonsoft.Json; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.IntegrationTests.SaveCdkDeploymentProject { public class SaveCdkDeploymentProjectTests : IDisposable { private readonly CommandLineWrapper _commandLineWrapper; private readonly InMemoryInteractiveService _inMemoryInteractiveService; public SaveCdkDeploymentProjectTests() { _inMemoryInteractiveService = new InMemoryInteractiveService(); _commandLineWrapper = new CommandLineWrapper(_inMemoryInteractiveService); } [Fact] public async Task DefaultSaveDirectory() { var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); await _commandLineWrapper.Run("git init", tempDirectoryPath); var targetApplicationProjectPath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); await Utilities.CreateCDKDeploymentProject(targetApplicationProjectPath); // Verify a bug fix that the IDictionary for TypeHintData was not getting serialized. var recipeFilePath = Directory.GetFiles(targetApplicationProjectPath + ".Deployment", "*.recipe", SearchOption.TopDirectoryOnly).FirstOrDefault(); Assert.True(File.Exists(recipeFilePath)); var recipeRoot = JsonConvert.DeserializeObject<RecipeDefinition>(File.ReadAllText(recipeFilePath)); var applicationIAMRoleSetting = recipeRoot.OptionSettings.FirstOrDefault(x => string.Equals(x.Id, "ApplicationIAMRole")); Assert.Equal("ecs-tasks.amazonaws.com", applicationIAMRoleSetting.TypeHintData["ServicePrincipal"]); } [Fact] public async Task CustomSaveDirectory() { var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); await _commandLineWrapper.Run("git init", tempDirectoryPath); var targetApplicationProjectPath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var saveDirectoryPath = Path.Combine(tempDirectoryPath, "DeploymentProjects", "MyCdkApp"); await Utilities.CreateCDKDeploymentProject(targetApplicationProjectPath, saveDirectoryPath); } [Fact] public async Task InvalidSaveCdkDirectoryInsideProjectDirectory() { var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); await _commandLineWrapper.Run("git init", tempDirectoryPath); var targetApplicationProjectPath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); var saveDirectoryPath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile", "MyCdkApp"); await Utilities.CreateCDKDeploymentProject(targetApplicationProjectPath, saveDirectoryPath, false); } [Fact] public async Task InvalidNonEmptySaveCdkDirectory() { var tempDirectoryPath = new TestAppManager().GetProjectPath(string.Empty); await _commandLineWrapper.Run("git init", tempDirectoryPath); var targetApplicationProjectPath = Path.Combine(tempDirectoryPath, "testapps", "WebAppWithDockerFile"); Directory.CreateDirectory(Path.Combine(tempDirectoryPath, "MyCdkApp", "MyFolder")); var saveDirectoryPath = Path.Combine(tempDirectoryPath, "MyCdkApp"); await Utilities.CreateCDKDeploymentProject(targetApplicationProjectPath, saveDirectoryPath, false); } protected virtual void Dispose(bool disposing) { if (disposing) { _inMemoryInteractiveService.ReadStdOutStartToEnd(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~SaveCdkDeploymentProjectTests() => Dispose(false); } }
96
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Services; using Microsoft.Extensions.DependencyInjection; using Xunit; using Should; using System.Reflection; namespace AWS.Deploy.CLI.IntegrationTests.SaveCdkDeploymentProject { public static class Utilities { public static async Task CreateCDKDeploymentProject(string targetApplicationPath, string saveDirectoryPath = null, bool isValid = true) { var (app, interactiveService) = GetAppServiceProvider(); Assert.NotNull(app); Assert.NotNull(interactiveService); // Arrange input for saving the CDK deployment project await interactiveService.StdInWriter.WriteAsync(Environment.NewLine); // Select default recommendation await interactiveService.StdInWriter.FlushAsync(); string[] deployArgs; // default save directory if (string.IsNullOrEmpty(saveDirectoryPath)) { saveDirectoryPath = targetApplicationPath + ".Deployment"; deployArgs = new[] { "deployment-project", "generate", "--project-path", targetApplicationPath, "--diagnostics" }; } else { deployArgs = new[] { "deployment-project", "generate", "--project-path", targetApplicationPath, "--output", saveDirectoryPath, "--diagnostics" }; } var returnCode = await app.Run(deployArgs); // Verify project is saved var stdOut = interactiveService.StdOutReader.ReadAllLines(); var successMessage = $"Saving AWS CDK deployment project to: {saveDirectoryPath}"; if (!isValid) { returnCode.ShouldEqual(CommandReturnCodes.USER_ERROR); return; } returnCode.ShouldEqual(CommandReturnCodes.SUCCESS); stdOut.ShouldContain(successMessage); VerifyCreatedArtifacts(targetApplicationPath, saveDirectoryPath); } public static async Task CreateCDKDeploymentProjectWithRecipeName(string targetApplicationPath, string recipeName, string option, string saveDirectoryPath = null, bool isValid = true, bool underSourceControl = true) { var (app, interactiveService) = GetAppServiceProvider(); Assert.NotNull(app); Assert.NotNull(interactiveService); // Arrange input for saving the CDK deployment project await interactiveService.StdInWriter.WriteLineAsync(option); // select recipe to save the CDK deployment project if (!underSourceControl) { await interactiveService.StdInWriter.WriteAsync("y"); // proceed to save without source control. } await interactiveService.StdInWriter.FlushAsync(); string[] deployArgs; // default save directory if (string.IsNullOrEmpty(saveDirectoryPath)) { saveDirectoryPath = targetApplicationPath + ".Deployment"; deployArgs = new[] { "deployment-project", "generate", "--project-path", targetApplicationPath, "--project-display-name", recipeName, "--diagnostics"}; } else { deployArgs = new[] { "deployment-project", "generate", "--project-path", targetApplicationPath, "--output", saveDirectoryPath, "--project-display-name", recipeName, "--diagnostics" }; } var returnCode = await app.Run(deployArgs); // Verify project is saved var stdOut = interactiveService.StdOutReader.ReadAllLines(); var successMessage = $"Saving AWS CDK deployment project to: {saveDirectoryPath}"; if (!isValid) { returnCode.ShouldEqual(CommandReturnCodes.USER_ERROR); return; } returnCode.ShouldEqual(CommandReturnCodes.SUCCESS); stdOut.ShouldContain(successMessage); VerifyCreatedArtifacts(targetApplicationPath, saveDirectoryPath); } private static (App app, InMemoryInteractiveService interactiveService) GetAppServiceProvider() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); var serviceProvider = serviceCollection.BuildServiceProvider(); var app = serviceProvider.GetService<App>(); var interactiveService = serviceProvider.GetService<InMemoryInteractiveService>(); return (app, interactiveService); } private static void VerifyCreatedArtifacts(string targetApplicationPath, string saveDirectoryPath) { var saveDirectoryName = new DirectoryInfo(saveDirectoryPath).Name; Assert.True(Directory.Exists(saveDirectoryPath)); Assert.True(File.Exists(Path.Combine(saveDirectoryPath, "AppStack.cs"))); Assert.True(File.Exists(Path.Combine(saveDirectoryPath, "Program.cs"))); Assert.True(File.Exists(Path.Combine(saveDirectoryPath, "cdk.json"))); Assert.True(File.Exists(Path.Combine(saveDirectoryPath, $"{saveDirectoryName}.recipe"))); Assert.True(File.Exists(Path.Combine(targetApplicationPath, "aws-deployments.json"))); } } }
135
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.IntegrationTests.Utilities; using AWS.Deploy.ServerMode.Client; using AWS.Deploy.ServerMode.Client.Utilities; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.ServerMode { public class DependencyValidationOptionSettings : IDisposable { private bool _isDisposed; private string _stackName; private readonly IServiceProvider _serviceProvider; private readonly string _awsRegion; private readonly TestAppManager _testAppManager; public DependencyValidationOptionSettings() { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); _awsRegion = "us-west-2"; _testAppManager = new TestAppManager(); } [Fact] public async Task DependentOptionSettingsGetInvalidated() { _stackName = $"ServerModeWebAppRunner{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4022; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); var logOutput = new StringBuilder(); await ServerModeExtensions.SetupSignalRConnection(baseUrl, sessionId, logOutput); var beanstalkRecommendation = await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppElasticBeanstalkLinux", _stackName); var applicationIAMRole = (await restClient.GetConfigSettingsAsync(sessionId)).OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.Equal(ValidationStatus.Valid, applicationIAMRole.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(applicationIAMRole.Validation.ValidationMessage)); Assert.Null(applicationIAMRole.Validation.InvalidValue); var validCreateNew = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.Equal(ValidationStatus.Valid, validCreateNew.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(validCreateNew.Validation.ValidationMessage)); Assert.Null(validCreateNew.Validation.InvalidValue); var validRoleArn = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.Equal(ValidationStatus.Valid, validRoleArn.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(validRoleArn.Validation.ValidationMessage)); Assert.Null(validRoleArn.Validation.InvalidValue); var applyConfigResponse = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"ApplicationIAMRole.CreateNew", "false"} } }); applicationIAMRole = (await restClient.GetConfigSettingsAsync(sessionId)).OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.Equal(ValidationStatus.Valid, applicationIAMRole.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(applicationIAMRole.Validation.ValidationMessage)); Assert.Null(applicationIAMRole.Validation.InvalidValue); validCreateNew = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.Equal(ValidationStatus.Valid, validCreateNew.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(validCreateNew.Validation.ValidationMessage)); Assert.Null(validCreateNew.Validation.InvalidValue); validRoleArn = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.Equal(ValidationStatus.Invalid, validRoleArn.Validation.ValidationStatus); Assert.Equal("Invalid IAM Role ARN. The ARN should contain the arn:[PARTITION]:iam namespace, followed by the account ID, and then the resource path. For example - arn:aws:iam::123456789012:role/S3Access is a valid IAM Role ARN. For more information visit https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns", validRoleArn.Validation.ValidationMessage); Assert.NotNull(validRoleArn.Validation.InvalidValue); Assert.True(string.IsNullOrEmpty(validRoleArn.Validation.InvalidValue.ToString())); applyConfigResponse = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"ApplicationIAMRole.CreateNew", "true"} } }); applicationIAMRole = (await restClient.GetConfigSettingsAsync(sessionId)).OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.Equal(ValidationStatus.Valid, applicationIAMRole.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(applicationIAMRole.Validation.ValidationMessage)); Assert.Null(applicationIAMRole.Validation.InvalidValue); validCreateNew = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.Equal(ValidationStatus.Valid, validCreateNew.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(validCreateNew.Validation.ValidationMessage)); Assert.Null(validCreateNew.Validation.InvalidValue); validRoleArn = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.Equal(ValidationStatus.Valid, validRoleArn.Validation.ValidationStatus); Assert.True(string.IsNullOrEmpty(validRoleArn.Validation.ValidationMessage)); Assert.Null(validRoleArn.Validation.InvalidValue); } finally { cancelSource.Cancel(); _stackName = null; } } [Fact] public async Task SettingInvalidValue() { _stackName = $"ServerModeWebAppRunner{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppNoDockerFile", "WebAppNoDockerFile.csproj")); var portNumber = 4022; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); var logOutput = new StringBuilder(); await ServerModeExtensions.SetupSignalRConnection(baseUrl, sessionId, logOutput); var beanstalkRecommendation = await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppElasticBeanstalkLinux", _stackName); var applicationIAMRole = (await restClient.GetConfigSettingsAsync(sessionId)).OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.Null(applicationIAMRole.Validation.InvalidValue); var validCreateNew = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.Null(validCreateNew.Validation.InvalidValue); var validRoleArn = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.Null(validRoleArn.Validation.InvalidValue); var applyConfigResponse = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"ApplicationIAMRole.CreateNew", "false"}, {"ApplicationIAMRole.RoleArn", "fakeArn"} } }); applicationIAMRole = (await restClient.GetConfigSettingsAsync(sessionId)).OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.Null(applicationIAMRole.Validation.InvalidValue); validCreateNew = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.Null(validCreateNew.Validation.InvalidValue); validRoleArn = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.NotNull(validRoleArn.Validation.InvalidValue); Assert.Equal("fakeArn", validRoleArn.Validation.InvalidValue); applyConfigResponse = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"ApplicationIAMRole.CreateNew", "true"} } }); applicationIAMRole = (await restClient.GetConfigSettingsAsync(sessionId)).OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.Null(applicationIAMRole.Validation.InvalidValue); validCreateNew = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.Null(validCreateNew.Validation.InvalidValue); validRoleArn = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.Null(validRoleArn.Validation.InvalidValue); applyConfigResponse = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"ApplicationIAMRole.RoleArn", "fakeArn"} } }); applicationIAMRole = (await restClient.GetConfigSettingsAsync(sessionId)).OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.Null(applicationIAMRole.Validation.InvalidValue); validCreateNew = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.Null(validCreateNew.Validation.InvalidValue); validRoleArn = applicationIAMRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.Null(validRoleArn.Validation.InvalidValue); } finally { cancelSource.Cancel(); _stackName = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; _isDisposed = true; } ~DependencyValidationOptionSettings() { Dispose(false); } } }
245
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.IntegrationTests.Extensions; using AWS.Deploy.CLI.TypeHintResponses; using AWS.Deploy.Common; using AWS.Deploy.ServerMode.Client; using AWS.Deploy.Common.TypeHintData; using Microsoft.Extensions.DependencyInjection; using Moq; using Newtonsoft.Json; using Xunit; using AWS.Deploy.CLI.IntegrationTests.Utilities; using AWS.Deploy.Orchestration; using AWS.Deploy.Common.IO; using Newtonsoft.Json.Linq; using AWS.Deploy.ServerMode.Client.Utilities; namespace AWS.Deploy.CLI.IntegrationTests.ServerMode { public class GetApplyOptionSettings : IDisposable { private bool _isDisposed; private string _stackName; private readonly IServiceProvider _serviceProvider; private readonly string _awsRegion; private readonly TestAppManager _testAppManager; private readonly Mock<IAWSClientFactory> _mockAWSClientFactory; private readonly Mock<IAmazonCloudFormation> _mockCFClient; private readonly Mock<IDeployToolWorkspaceMetadata> _deployToolWorkspaceMetadata; private readonly IFileManager _fileManager; public GetApplyOptionSettings() { _mockAWSClientFactory = new Mock<IAWSClientFactory>(); _mockCFClient = new Mock<IAmazonCloudFormation>(); _deployToolWorkspaceMetadata = new Mock<IDeployToolWorkspaceMetadata>(); _fileManager = new TestFileManager(); var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddTestServices(); _serviceProvider = serviceCollection.BuildServiceProvider(); _awsRegion = "us-west-2"; _testAppManager = new TestAppManager(); } [Fact] public async Task GetAndApplyAppRunnerSettings_RecipeValidatorsAreRun() { _stackName = $"ServerModeWebAppRunner{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4026; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); var logOutput = new StringBuilder(); await ServerModeExtensions.SetupSignalRConnection(baseUrl, sessionId, logOutput); var fargateRecommendation = await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppEcsFargate", _stackName); var applyConfigSettingsResponse = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"TaskCpu", "4096"} } }); Assert.Empty(applyConfigSettingsResponse.FailedConfigUpdates); var exceptionThrown = await Assert.ThrowsAsync<ApiException>(async () => await restClient.StartDeploymentAsync(sessionId)); Assert.Contains("Cpu value 4096 is not compatible with memory value 512.", exceptionThrown.Response); } finally { cancelSource.Cancel(); _stackName = null; } } [Fact] public async Task GetAndApplyAppRunnerSettings_FailedUpdatesReturnSettingId() { _stackName = $"ServerModeWebAppRunner{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4027; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); var logOutput = new StringBuilder(); await ServerModeExtensions.SetupSignalRConnection(baseUrl, sessionId, logOutput); var fargateRecommendation = await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppEcsFargate", _stackName); var applyConfigSettingsResponse = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"DesiredCount", "test"} } }); Assert.Single(applyConfigSettingsResponse.FailedConfigUpdates); Assert.Equal("DesiredCount", applyConfigSettingsResponse.FailedConfigUpdates.Keys.First()); } finally { cancelSource.Cancel(); _stackName = null; } } [Fact] public async Task GetAndApplyAppRunnerSettings_VPCConnector() { _stackName = $"ServerModeWebAppRunner{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4021; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); var logOutput = new StringBuilder(); await ServerModeExtensions.SetupSignalRConnection(baseUrl, sessionId, logOutput); var appRunnerRecommendation = await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppAppRunner", _stackName); var vpcResources = await restClient.GetConfigSettingResourcesAsync(sessionId, "VPCConnector.VpcId"); var subnetsResourcesEmpty = await restClient.GetConfigSettingResourcesAsync(sessionId, "VPCConnector.Subnets"); var securityGroupsResourcesEmpty = await restClient.GetConfigSettingResourcesAsync(sessionId, "VPCConnector.SecurityGroups"); Assert.NotEmpty(vpcResources.Resources); Assert.NotEmpty(subnetsResourcesEmpty.Resources); Assert.NotEmpty(securityGroupsResourcesEmpty.Resources); var vpcId = vpcResources.Resources.First().SystemName; await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"VPCConnector.UseVPCConnector", "true"}, {"VPCConnector.CreateNew", "true"}, {"VPCConnector.VpcId", vpcId} } }); var subnetsResources = await restClient.GetConfigSettingResourcesAsync(sessionId, "VPCConnector.Subnets"); var securityGroupsResources = await restClient.GetConfigSettingResourcesAsync(sessionId, "VPCConnector.SecurityGroups"); Assert.NotEmpty(subnetsResources.Resources); Assert.NotEmpty(securityGroupsResources.Resources); var subnet = subnetsResources.Resources.Last().SystemName; var securityGroup = securityGroupsResources.Resources.First().SystemName; var setConfigResult = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"VPCConnector.Subnets", JsonConvert.SerializeObject(new List<string>{subnet})}, {"VPCConnector.SecurityGroups", JsonConvert.SerializeObject(new List<string>{securityGroup})} } }); var generateCloudFormationTemplateResponse = await restClient.GenerateCloudFormationTemplateAsync(sessionId); var metadata = await ServerModeExtensions.GetAppSettingsFromCFTemplate(_mockAWSClientFactory, _mockCFClient, generateCloudFormationTemplateResponse.CloudFormationTemplate, _stackName, _deployToolWorkspaceMetadata, _fileManager); Assert.True(metadata.Settings.ContainsKey("VPCConnector")); var vpcConnector = JsonConvert.DeserializeObject<VPCConnectorTypeHintResponse>(metadata.Settings["VPCConnector"].ToString()); Assert.True(vpcConnector.UseVPCConnector); Assert.True(vpcConnector.CreateNew); Assert.Equal(vpcId, vpcConnector.VpcId); Assert.Contains<string>(subnet, vpcConnector.Subnets); Assert.Contains<string>(securityGroup, vpcConnector.SecurityGroups); } finally { cancelSource.Cancel(); _stackName = null; } } [Fact] public async Task GetAppRunnerConfigSettings_TypeHintData() { _stackName = $"ServerModeWebAppRunner{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4002; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); var logOutput = new StringBuilder(); await ServerModeExtensions.SetupSignalRConnection(baseUrl, sessionId, logOutput); await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppAppRunner", _stackName); var configSettings = restClient.GetConfigSettingsAsync(sessionId); Assert.NotEmpty(configSettings.Result.OptionSettings); var iamRoleSetting = Assert.Single(configSettings.Result.OptionSettings, o => o.Id == "ApplicationIAMRole"); Assert.NotEmpty(iamRoleSetting.TypeHintData); Assert.Equal("tasks.apprunner.amazonaws.com", iamRoleSetting.TypeHintData[nameof(IAMRoleTypeHintData.ServicePrincipal)]); } finally { cancelSource.Cancel(); _stackName = null; } } /// <summary> /// Tests that GetConfigSettingResourcesAsync for App Runner's /// VPC Connector child settings return TypeHintResourceColumns /// </summary> [Fact] public async Task GetConfigSettingResources_VpcConnectorOptions() { _stackName = $"ServerModeWebAppRunner{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4023; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppAppRunner", _stackName); // Assert that the Subnets and SecurityGroups options are returning columns var subnets = await restClient.GetConfigSettingResourcesAsync(sessionId, "VPCConnector.Subnets"); Assert.Collection(subnets.Columns, column => Assert.NotNull(column), // Subnet Id column => Assert.NotNull(column), // VPC column => Assert.NotNull(column)); // Availability Zone var securityGroups = await restClient.GetConfigSettingResourcesAsync(sessionId, "VPCConnector.SecurityGroups"); Assert.Collection(securityGroups.Columns, column => Assert.NotNull(column), // Name column => Assert.NotNull(column), // Id column => Assert.NotNull(column)); // VPC // This is using a real AWSResourceQueryer, // so not asserting on the rows for these two options } finally { cancelSource.Cancel(); _stackName = null; } } /// <summary> /// Tests that the LoadBalancer.InternetFacing option setting correctly toggles the /// <see href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-scheme">load balancer scheme</see>. /// </summary> /// <param name="internetFacingValue">desired LoadBalancer.InternetFacing option setting value</param> /// <param name="expectedLoadBalancerScheme">Expected load balancer scheme in the generated CloudFormation template</param> [Theory] [InlineData("true", "internet-facing")] [InlineData("false", "internal")] public async Task GetAndApplyECSFargateSettings_LoadBalancerSchemeConfig(string internetFacingValue, string expectedLoadBalancerScheme) { _stackName = $"ServerModeWebECSFargate{Guid.NewGuid().ToString().Split('-').Last()}"; var projectPath = _testAppManager.GetProjectPath(Path.Combine("testapps", "WebAppWithDockerFile", "WebAppWithDockerFile.csproj")); var portNumber = 4024; using var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); // Running `cdk diff` to assert against the generated CloudFormation template // for this recipe takes longer than the default timeout httpClient.Timeout = new TimeSpan(0, 0, 120); var serverCommand = new ServerModeCommand(_serviceProvider.GetRequiredService<IToolInteractiveService>(), portNumber, null, true); var cancelSource = new CancellationTokenSource(); var serverTask = serverCommand.ExecuteAsync(cancelSource.Token); try { var baseUrl = $"http://localhost:{portNumber}/"; var restClient = new RestAPIClient(baseUrl, httpClient); await restClient.WaitUntilServerModeReady(); var sessionId = await restClient.StartDeploymentSession(projectPath, _awsRegion); var logOutput = new StringBuilder(); await ServerModeExtensions.SetupSignalRConnection(baseUrl, sessionId, logOutput); var recommendation = await restClient.GetRecommendationsAndSetDeploymentTarget(sessionId, "AspNetAppEcsFargate", _stackName); var response = await restClient.ApplyConfigSettingsAsync(sessionId, new ApplyConfigSettingsInput() { UpdatedSettings = new Dictionary<string, string>() { {"LoadBalancer.InternetFacing", internetFacingValue} } }); var generateCloudFormationTemplateResponse = await restClient.GenerateCloudFormationTemplateAsync(sessionId); var cloudFormationTemplate = JObject.Parse(generateCloudFormationTemplateResponse.CloudFormationTemplate); // This should find the AWS::ElasticLoadBalancingV2::LoadBalancer resource in the CloudFormation JSON // based on its "Scheme" property, which is what "LoadBalancer.InternetFacing" ultimately drives. // If multiple resources end up with a Scheme property or the LoadBalancer is missing, // this test should fail because .Single() will throw an exception. var loadBalancerSchemeValue = cloudFormationTemplate.SelectTokens("Resources.*.Properties.Scheme").Single(); Assert.Equal(expectedLoadBalancerScheme, loadBalancerSchemeValue.ToString()); } finally { cancelSource.Cancel(); _stackName = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; _isDisposed = true; } ~GetApplyOptionSettings() { Dispose(false); } } }
410
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using Xunit; using Should; namespace AWS.Deploy.CLI.IntegrationTests.Services { public class InMemoryInteractiveServiceTests { [Fact] public void Write() { var service = new InMemoryInteractiveService(); service.Write("Hello"); Assert.Equal("Hello", service.StdOutReader.ReadToEnd()); service.Write("World"); Assert.Equal("World", service.StdOutReader.ReadToEnd()); } [Fact] public void WriteLine() { var service = new InMemoryInteractiveService(); service.WriteLine("Line 1"); service.WriteLine("Line 2"); service.WriteLine("Line 3"); Assert.Equal("Line 1", service.StdOutReader.ReadLine()); Assert.Equal("Line 2", service.StdOutReader.ReadLine()); Assert.Equal("Line 3", service.StdOutReader.ReadLine()); service.WriteLine("Line 4"); service.WriteLine("Line 5"); service.WriteLine("Line 6"); Assert.Equal("Line 4", service.StdOutReader.ReadLine()); Assert.Equal("Line 5", service.StdOutReader.ReadLine()); Assert.Equal("Line 6", service.StdOutReader.ReadLine()); } [Fact] public void WriteErrorLine() { var service = new InMemoryInteractiveService(); service.WriteErrorLine("Error Line 1"); service.WriteErrorLine("Error Line 2"); service.WriteErrorLine("Error Line 3"); Assert.Equal("Error Line 1", service.StdOutReader.ReadLine()); Assert.Equal("Error Line 2", service.StdOutReader.ReadLine()); Assert.Equal("Error Line 3", service.StdOutReader.ReadLine()); service.WriteErrorLine("Error Line 4"); service.WriteErrorLine("Error Line 5"); service.WriteErrorLine("Error Line 6"); Assert.Equal("Error Line 4", service.StdOutReader.ReadLine()); Assert.Equal("Error Line 5", service.StdOutReader.ReadLine()); Assert.Equal("Error Line 6", service.StdOutReader.ReadLine()); } [Fact] public void WriteDebugLine() { var service = new InMemoryInteractiveService(); service.WriteDebugLine("Debug Line 1"); service.WriteDebugLine("Debug Line 2"); service.WriteDebugLine("Debug Line 3"); Assert.Equal("Debug Line 1", service.StdOutReader.ReadLine()); Assert.Equal("Debug Line 2", service.StdOutReader.ReadLine()); Assert.Equal("Debug Line 3", service.StdOutReader.ReadLine()); service.WriteDebugLine("Debug Line 4"); service.WriteDebugLine("Debug Line 5"); service.WriteDebugLine("Debug Line 6"); Assert.Equal("Debug Line 4", service.StdOutReader.ReadLine()); Assert.Equal("Debug Line 5", service.StdOutReader.ReadLine()); Assert.Equal("Debug Line 6", service.StdOutReader.ReadLine()); } [Fact] public void ReadLine() { var service = new InMemoryInteractiveService(); service.StdInWriter.WriteLine("Line 1"); service.StdInWriter.WriteLine("Line 2"); service.StdInWriter.WriteLine("Line 3"); service.StdInWriter.Flush(); Assert.Equal("Line 1", service.ReadLine()); Assert.Equal("Line 2", service.ReadLine()); Assert.Equal("Line 3", service.ReadLine()); service.StdInWriter.WriteLine("Line 4"); service.StdInWriter.WriteLine("Line 5"); service.StdInWriter.WriteLine("Line 6"); service.StdInWriter.Flush(); Assert.Equal("Line 4", service.ReadLine()); Assert.Equal("Line 5", service.ReadLine()); Assert.Equal("Line 6", service.ReadLine()); } [Fact] public void ReadKey() { var service = new InMemoryInteractiveService(); service.StdInWriter.Write(ConsoleKey.A); service.StdInWriter.Write(ConsoleKey.B); service.StdInWriter.Write(ConsoleKey.C); service.StdInWriter.Flush(); Assert.Equal(ConsoleKey.A, service.ReadKey(false).Key); Assert.Equal(ConsoleKey.B, service.ReadKey(false).Key); Assert.Equal(ConsoleKey.C, service.ReadKey(false).Key); service.StdInWriter.Write(ConsoleKey.D); service.StdInWriter.Write(ConsoleKey.E); service.StdInWriter.Write(ConsoleKey.F); service.StdInWriter.Flush(); Assert.Equal(ConsoleKey.D, service.ReadKey(false).Key); Assert.Equal(ConsoleKey.E, service.ReadKey(false).Key); Assert.Equal(ConsoleKey.F, service.ReadKey(false).Key); } [Fact] public void ReadLineSetToNull() { var service = new InMemoryInteractiveService(); Assert.Throws<InvalidOperationException>(() => service.ReadLine()); } } }
148
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Runtime; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Utilities; using AWS.Deploy.ServerMode.Client; using Moq; using Xunit; namespace AWS.Deploy.CLI.IntegrationTests.Utilities { public static class ServerModeExtensions { public static async Task<string> StartDeploymentSession(this RestAPIClient restClient, string projectPath, string awsRegion) { var startSessionOutput = await restClient.StartDeploymentSessionAsync(new StartDeploymentSessionInput { AwsRegion = awsRegion, ProjectPath = projectPath }); var sessionId = startSessionOutput.SessionId; Assert.NotNull(sessionId); return sessionId; } public static async Task SetupSignalRConnection(string baseUrl, string sessionId, StringBuilder logOutput) { var signalRClient = new DeploymentCommunicationClient(baseUrl); await signalRClient.JoinSession(sessionId); ServerModeTests.RegisterSignalRMessageCallbacks(signalRClient, logOutput); } public static async Task<RecommendationSummary> GetRecommendationsAndSetDeploymentTarget(this RestAPIClient restClient, string sessionId, string recipeId, string stackName) { var getRecommendationOutput = await restClient.GetRecommendationsAsync(sessionId); Assert.NotEmpty(getRecommendationOutput.Recommendations); var beanstalkRecommendation = getRecommendationOutput.Recommendations.FirstOrDefault(x => string.Equals(x.RecipeId, recipeId)); Assert.NotNull(beanstalkRecommendation); await restClient.SetDeploymentTargetAsync(sessionId, new SetDeploymentTargetInput { NewDeploymentName = stackName, NewDeploymentRecipeId = beanstalkRecommendation.RecipeId }); return beanstalkRecommendation; } public static async Task<CloudApplicationMetadata> GetAppSettingsFromCFTemplate(Mock<IAWSClientFactory> mockAWSClientFactory, Mock<IAmazonCloudFormation> mockCFClient, string cloudFormationTemplate, string stackName, Mock<IDeployToolWorkspaceMetadata> deployToolWorkspaceMetadata, IFileManager fileManager) { var templateMetadataReader = GetTemplateMetadataReader(mockAWSClientFactory, mockCFClient, cloudFormationTemplate, deployToolWorkspaceMetadata, fileManager); return await templateMetadataReader.LoadCloudApplicationMetadata(stackName); } public static CloudFormationTemplateReader GetTemplateMetadataReader(Mock<IAWSClientFactory> mockAWSClientFactory, Mock<IAmazonCloudFormation> mockCFClient, string templateBody, Mock<IDeployToolWorkspaceMetadata> deployToolWorkspaceMetadata, IFileManager fileManager) { var templateMetadataReader = new CloudFormationTemplateReader(mockAWSClientFactory.Object, deployToolWorkspaceMetadata.Object, fileManager); var cfResponse = new GetTemplateResponse(); cfResponse.TemplateBody = templateBody; mockAWSClientFactory.Setup(x => x.GetAWSClient<IAmazonCloudFormation>(It.IsAny<string>())).Returns(mockCFClient.Object); mockCFClient.Setup(x => x.GetTemplateAsync(It.IsAny<GetTemplateRequest>(), It.IsAny<CancellationToken>())).ReturnsAsync(cfResponse); return templateMetadataReader; } public static async Task<DeploymentStatus> WaitForDeployment(this RestAPIClient restApiClient, string sessionId) { // Do an initial delay to avoid a race condition of the status being checked before the deployment has kicked off. await Task.Delay(TimeSpan.FromSeconds(3)); GetDeploymentStatusOutput output = null; await Orchestration.Utilities.Helpers.WaitUntil(async () => { output = (await restApiClient.GetDeploymentStatusAsync(sessionId)); return output.Status != DeploymentStatus.Executing; }, TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(15)); if (output.Exception != null) { throw new Exception("Error waiting on stack status: " + output.Exception.Message); } return output.Status; } } }
102
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Amazon.AppRunner.Model; using Amazon.CloudControlApi.Model; using Amazon.CloudFormation.Model; using Amazon.CloudFront.Model; using Amazon.CloudWatchEvents.Model; using Amazon.EC2.Model; using Amazon.ECR.Model; using Amazon.ECS.Model; using Amazon.ElasticBeanstalk.Model; using Amazon.ElasticLoadBalancingV2; using Amazon.IdentityManagement.Model; using Amazon.Runtime; using Amazon.SecurityToken.Model; using AWS.Deploy.Common.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.CLI.IntegrationTests.Utilities { public class TestToolAWSResourceQueryer : IAWSResourceQueryer { public Task<PlatformSummary> GetLatestElasticBeanstalkPlatformArn(BeanstalkPlatformType platformType) { return System.Threading.Tasks.Task.FromResult(new PlatformSummary() { PlatformArn = string.Empty }); } public Task<string> CreateEC2KeyPair(string keyName, string saveLocation) => throw new NotImplementedException(); public Task<Repository> CreateECRRepository(string repositoryName) => throw new NotImplementedException(); public Task<List<StackResource>> DescribeCloudFormationResources(string stackName) => throw new NotImplementedException(); public Task<DescribeRuleResponse> DescribeCloudWatchRule(string ruleName) => throw new NotImplementedException(); public Task<EnvironmentDescription> DescribeElasticBeanstalkEnvironment(string environmentId) => throw new NotImplementedException(); public Task<Amazon.ElasticLoadBalancingV2.Model.LoadBalancer> DescribeElasticLoadBalancer(string loadBalancerArn) => throw new NotImplementedException(); public Task<List<Amazon.ElasticLoadBalancingV2.Model.Listener>> DescribeElasticLoadBalancerListeners(string loadBalancerArn) => throw new NotImplementedException(); public Task<List<Stack>> GetCloudFormationStacks() => throw new NotImplementedException(); public Task<Stack> GetCloudFormationStack(string stackName) => throw new NotImplementedException(); public Task<List<AuthorizationData>> GetECRAuthorizationToken() => throw new NotImplementedException(); public Task<List<Repository>> GetECRRepositories(List<string> repositoryNames) => throw new NotImplementedException(); public Task<List<PlatformSummary>> GetElasticBeanstalkPlatformArns(params BeanstalkPlatformType[] platformTypes) => throw new NotImplementedException(); public Task<List<Vpc>> GetListOfVpcs() => throw new NotImplementedException(); public Task<string> GetS3BucketLocation(string bucketName) => throw new NotImplementedException(); public Task<Amazon.S3.Model.WebsiteConfiguration> GetS3BucketWebSiteConfiguration(string bucketName) => throw new NotImplementedException(); public Task<List<KeyPairInfo>> ListOfEC2KeyPairs() => throw new NotImplementedException(); public Task<List<Cluster>> ListOfECSClusters(string ecsClusterName) => throw new NotImplementedException(); public Task<List<ApplicationDescription>> ListOfElasticBeanstalkApplications(string applicationName) => throw new NotImplementedException(); public Task<List<EnvironmentDescription>> ListOfElasticBeanstalkEnvironments(string applicationName, string environmentName) => throw new NotImplementedException(); public Task<List<Role>> ListOfIAMRoles(string servicePrincipal) => throw new NotImplementedException(); public Task<Amazon.AppRunner.Model.Service> DescribeAppRunnerService(string serviceArn) => throw new NotImplementedException(); public Task<List<Amazon.ElasticLoadBalancingV2.Model.LoadBalancer>> ListOfLoadBalancers(LoadBalancerTypeEnum loadBalancerType) => throw new NotImplementedException(); public Task<Distribution> GetCloudFrontDistribution(string distributionId) => throw new NotImplementedException(); public Task<List<string>> ListOfDyanmoDBTables() => throw new NotImplementedException(); public Task<List<string>> ListOfSQSQueuesUrls() => throw new NotImplementedException(); public Task<List<string>> ListOfSNSTopicArns() => throw new NotImplementedException(); public Task<List<Amazon.S3.Model.S3Bucket>> ListOfS3Buckets() => throw new NotImplementedException(); public Task<List<InstanceTypeInfo>> ListOfAvailableInstanceTypes() => throw new NotImplementedException(); public Task<InstanceTypeInfo> DescribeInstanceType(string instanceType) => throw new NotImplementedException(); public Task<List<StackEvent>> GetCloudFormationStackEvents(string stackName) => throw new NotImplementedException(); public Task<List<Amazon.ElasticBeanstalk.Model.Tag>> ListElasticBeanstalkResourceTags(string resourceArn) => throw new NotImplementedException(); public Task<List<ConfigurationOptionSetting>> GetBeanstalkEnvironmentConfigurationSettings(string environmentId) => throw new NotImplementedException(); public Task<GetCallerIdentityResponse> GetCallerIdentity(string awsRegion) => throw new NotImplementedException(); public Task<Repository> DescribeECRRepository(string respositoryName) => throw new NotImplementedException(); public Task<List<VpcConnector>> DescribeAppRunnerVpcConnectors() => throw new NotImplementedException(); public Task<List<Subnet>> DescribeSubnets(string vpcID = null) => throw new NotImplementedException(); public Task<List<SecurityGroup>> DescribeSecurityGroups(string vpcID = null) => throw new NotImplementedException(); public Task<string> GetParameterStoreTextValue(string parameterName) => throw new NotImplementedException(); public Task<ResourceDescription> GetCloudControlApiResource(string type, string identifier) => throw new NotImplementedException(); public Task<Vpc> GetDefaultVpc() => throw new NotImplementedException(); } }
75
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.TypeHintResponses; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Recipes; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using Moq; using Newtonsoft.Json; using Xunit; using Assert = Should.Core.Assertions.Assert; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Common.Data; using Amazon.CloudControlApi.Model; using Amazon.ElasticBeanstalk.Model; using AWS.Deploy.Common.DeploymentManifest; namespace AWS.Deploy.CLI.UnitTests { public class ApplyPreviousSettingsTests { private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Orchestrator _orchestrator; private readonly Mock<IServiceProvider> _serviceProvider; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly TestToolOrchestratorInteractiveService _orchestratorInteractiveService; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IRecipeHandler _recipeHandler; public ApplyPreviousSettingsTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); _directoryManager = new DirectoryManager(); _fileManager = new FileManager(); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService, _directoryManager, _fileManager, optionSettingHandler, validatorFactory); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); _orchestrator = new Orchestrator(null, _orchestratorInteractiveService, null, null, null, null, null, null, null, null, null, null, null, _optionSettingHandler, null); } private async Task<RecommendationEngine> BuildRecommendationEngine(string testProjectName) { var fullPath = SystemIOUtilities.ResolvePath(testProjectName); var parser = new ProjectDefinitionParser(_fileManager, _directoryManager); var awsCredentials = new Mock<AWSCredentials>(); var session = new OrchestratorSession( await parser.Parse(fullPath), awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; return new RecommendationEngine(session, _recipeHandler); } [Fact] public async Task ApplyPreviousSettings_InvalidType() { var engine = await BuildRecommendationEngine("WebAppWithDockerFile"); var recommendations = await engine.ComputeRecommendations(); var fargateRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); var serializedSettings = @$" {{ ""AdditionalECSServiceSecurityGroups"": ""sg-1234abcd"" }}"; var settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedSettings); fargateRecommendation = await _orchestrator.ApplyRecommendationPreviousSettings(fargateRecommendation, settings); var additionalECSServiceSecurityGroupsOptionSetting = fargateRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("AdditionalECSServiceSecurityGroups")); Assert.Contains($"Unable to retrieve value of '{additionalECSServiceSecurityGroupsOptionSetting.Name}' from previous deployment. Make sure to set it again prior to redeployment.", _orchestratorInteractiveService.ErrorMessages); } [Theory] [InlineData(true, null)] [InlineData(false, "arn:aws:iam::123456789012:group/Developers")] public async Task ApplyApplicationIAMRolePreviousSettings(bool createNew, string roleArn) { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var roleArnValue = roleArn == null ? "null" : $"\"{roleArn}\""; var serializedSettings = @$" {{ ""ApplicationIAMRole"": {{ ""RoleArn"": {roleArnValue}, ""CreateNew"": {createNew.ToString().ToLower()} }} }}"; var settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedSettings); beanstalkRecommendation = await _orchestrator.ApplyRecommendationPreviousSettings(beanstalkRecommendation, settings); var applicationIAMRoleOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("ApplicationIAMRole")); var typeHintResponse = _optionSettingHandler.GetOptionSettingValue<IAMRoleTypeHintResponse>(beanstalkRecommendation, applicationIAMRoleOptionSetting); Assert.Equal(roleArn, typeHintResponse.RoleArn); Assert.Equal(createNew, typeHintResponse.CreateNew); } [Theory] [InlineData(true, false, "")] [InlineData(false, true, "")] [InlineData(false, false, "vpc-88888888")] public async Task ApplyVpcPreviousSettings(bool isDefault, bool createNew, string vpcId) { var engine = await BuildRecommendationEngine("WebAppWithDockerFile"); var recommendations = await engine.ComputeRecommendations(); var fargateRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); var vpcIdValue = string.IsNullOrEmpty(vpcId) ? "\"\"" : $"\"{vpcId}\""; var serializedSettings = @$" {{ ""Vpc"": {{ ""IsDefault"": {isDefault.ToString().ToLower()}, ""CreateNew"": {createNew.ToString().ToLower()}, ""VpcId"": {vpcIdValue} }} }}"; var settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedSettings); fargateRecommendation = await _orchestrator.ApplyRecommendationPreviousSettings(fargateRecommendation, settings); var vpcOptionSetting = fargateRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("Vpc")); Assert.Equal(isDefault, _optionSettingHandler.GetOptionSettingValue(fargateRecommendation, vpcOptionSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("IsDefault")))); Assert.Equal(createNew, _optionSettingHandler.GetOptionSettingValue(fargateRecommendation, vpcOptionSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("CreateNew")))); Assert.Equal(vpcId, _optionSettingHandler.GetOptionSettingValue(fargateRecommendation, vpcOptionSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("VpcId")))); } [Fact] public async Task ApplyECSClusterNamePreviousSettings() { _awsResourceQueryer.Setup(x => x.GetCloudControlApiResource(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new ResourceDescription { Identifier = "WebApp" }); var engine = await BuildRecommendationEngine("WebAppWithDockerFile"); var recommendations = await engine.ComputeRecommendations(); var fargateRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); var serializedSettings = @$" {{ ""ECSCluster"": {{ ""CreateNew"": true, ""NewClusterName"": ""WebApp"" }} }}"; var settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedSettings); fargateRecommendation = await _orchestrator.ApplyRecommendationPreviousSettings(fargateRecommendation, settings); var ecsClusterSetting = fargateRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("ECSCluster")); Assert.Equal(true, _optionSettingHandler.GetOptionSettingValue(fargateRecommendation, ecsClusterSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("CreateNew")))); Assert.Equal("WebApp", _optionSettingHandler.GetOptionSettingValue(fargateRecommendation, ecsClusterSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("NewClusterName")))); } [Fact] public async Task ApplyBeanstalkApplicationNamePreviousSettings() { _awsResourceQueryer.Setup(x => x.ListOfElasticBeanstalkApplications(It.IsAny<string>())).ReturnsAsync(new List<ApplicationDescription> { new ApplicationDescription { ApplicationName = "WebApp" } }); var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var serializedSettings = @$" {{ ""BeanstalkApplication"": {{ ""CreateNew"": true, ""ApplicationName"": ""WebApp"" }} }}"; var settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedSettings); beanstalkRecommendation = await _orchestrator.ApplyRecommendationPreviousSettings(beanstalkRecommendation, settings); var applicationSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("BeanstalkApplication")); Assert.Equal(true, _optionSettingHandler.GetOptionSettingValue(beanstalkRecommendation, applicationSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("CreateNew")))); Assert.Equal("WebApp", _optionSettingHandler.GetOptionSettingValue(beanstalkRecommendation, applicationSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("ApplicationName")))); } [Fact] public async Task ApplyBeanstalkEnvironmentNamePreviousSettings() { _awsResourceQueryer.Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<EnvironmentDescription> { new EnvironmentDescription { EnvironmentName = "WebApp" } }); var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var serializedSettings = @$" {{ ""BeanstalkEnvironment"": {{ ""EnvironmentName"": ""WebApp"" }} }}"; var settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(serializedSettings); beanstalkRecommendation = await _orchestrator.ApplyRecommendationPreviousSettings(beanstalkRecommendation, settings); var environmentSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("BeanstalkEnvironment")); Assert.Equal("WebApp", _optionSettingHandler.GetOptionSettingValue(beanstalkRecommendation, environmentSetting.ChildOptionSettings.First(optionSetting => optionSetting.Id.Equals("EnvironmentName")))); } } }
253
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Text; using AWS.Deploy.Recipes; using Xunit; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit.Abstractions; namespace AWS.Deploy.CLI.UnitTests { public class CategoryTests { private readonly ITestOutputHelper _output; public CategoryTests(ITestOutputHelper output) { this._output = output; } [Fact] public void ValidateSettingCategories() { var recipes = Directory.GetFiles(RecipeLocator.FindRecipeDefinitionsPath(), "*.recipe", SearchOption.TopDirectoryOnly); foreach(var recipe in recipes) { _output.WriteLine($"Validating recipe: {recipe}"); var root = JsonConvert.DeserializeObject(File.ReadAllText(recipe)) as JObject; _output.WriteLine("\tCategories"); var categoryIds = new HashSet<string>(); var categoryOrders = new HashSet<int>(); foreach(JObject category in root["Categories"]) { _output.WriteLine($"\t\t{category["Id"]}"); categoryIds.Add(category["Id"].ToString()); // Make sure all order ids are unique in recipe var order = (int)category["Order"]; Assert.DoesNotContain(order, categoryOrders); categoryOrders.Add(order); } _output.WriteLine("\tSettings"); foreach (JObject setting in root["OptionSettings"]) { var settingCategoryId = setting["Category"]?.ToString(); _output.WriteLine($"\t\t{settingCategoryId}"); Assert.Contains(settingCategoryId, categoryIds); } } } } }
60
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.EC2.Model; using Amazon.Runtime; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.CLI.Utilities; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Should; using Xunit; using AWS.Deploy.Common.Data; namespace AWS.Deploy.CLI.UnitTests { public class ConsoleUtilitiesTests { private readonly IDirectoryManager _directoryManager; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public ConsoleUtilitiesTests() { _directoryManager = new TestDirectoryManager(); _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } private readonly List<OptionItem> _options = new List<OptionItem> { new() { DisplayName = "Option1", Identifier = "Identifier1" }, new() { DisplayName = "Option2", Identifier = "Identifier2" }, }; [Fact] public async Task AskUserForList() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var subnetsOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.Subnets"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "1", "1", "1", "2", "3" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var userInputConfiguration = new UserInputConfiguration<Subnet>( option => option.SubnetId, option => option.SubnetId, option => false) { AskNewName = true }; var availableData = new List<Subnet>() { new Subnet() { SubnetId = "subnet1" }, new Subnet() { SubnetId = "subnet2" } }; var userResponse = consoleUtilities.AskUserForList<Subnet>(userInputConfiguration, availableData, subnetsOptionSetting, appRunnerRecommendation); Assert.Equal(2, userResponse.Count); Assert.Contains("subnet1", userResponse); Assert.Contains("subnet2", userResponse); } [Fact] public void AskUserToChooseOrCreateNew() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "3", "CustomNewIdentifier" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var userInputConfiguration = new UserInputConfiguration<OptionItem>( option => option.DisplayName, option => option.DisplayName, option => option.Identifier.Equals("Identifier2"), "NewIdentifier") { AskNewName = true }; var userResponse = consoleUtilities.AskUserToChooseOrCreateNew(_options, "Title", userInputConfiguration); Assert.True(interactiveServices.OutputContains("Title")); Assert.True(interactiveServices.OutputContains("1: Option1")); Assert.True(interactiveServices.OutputContains("2: Option2")); Assert.True(interactiveServices.OutputContains($"3: {Deploy.Constants.CLI.CREATE_NEW_LABEL}")); Assert.Null(userResponse.SelectedOption); Assert.True(interactiveServices.OutputContains("(default 2")); Assert.True(interactiveServices.OutputContains("(default NewIdentifier")); Assert.True(userResponse.CreateNew); Assert.Equal("CustomNewIdentifier", userResponse.NewName); } [Fact] public void AskUserToChooseOrCreateNewPickExisting() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "1" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var userInputConfiguration = new UserInputConfiguration<OptionItem>( option => option.DisplayName, option => option.DisplayName, option => option.Identifier.Equals("Identifier2"), "NewIdentifier") { AskNewName = true }; var userResponse = consoleUtilities.AskUserToChooseOrCreateNew(_options, "Title", userInputConfiguration); Assert.Equal("Title", interactiveServices.OutputMessages[0]); Assert.True(interactiveServices.OutputContains("Title")); Assert.True(interactiveServices.OutputContains("1: Option1")); Assert.True(interactiveServices.OutputContains("2: Option2")); Assert.True(interactiveServices.OutputContains("(default 2")); Assert.Equal(_options[0], userResponse.SelectedOption); Assert.False(userResponse.CreateNew); Assert.Null(userResponse.NewName); } [Fact] public void AskUserToChooseOrCreateNewNoOptions() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "1" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var userInputConfiguration = new UserInputConfiguration<OptionItem>( option => option.DisplayName, option => option.DisplayName, option => option.Identifier.Equals("Identifier2"), "NewIdentifier") { AskNewName = false, CreateNew = true, EmptyOption = false }; var userResponse = consoleUtilities.AskUserToChooseOrCreateNew(Array.Empty<OptionItem>(), "Title", userInputConfiguration); Assert.Equal("Title", interactiveServices.OutputMessages[0]); Assert.True(interactiveServices.OutputContains("Title")); Assert.True(interactiveServices.OutputContains("1: *** Create new *** (default)")); Assert.True(userResponse.CreateNew); Assert.Null(userResponse.SelectedOption); Assert.Null(userResponse.NewName); Assert.False(userResponse.IsEmpty); } [Fact] public void AskUserToChooseStringsPickDefault() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskUserToChoose(new List<string> { "Option1", "Option2" }, "Title", "Option2"); Assert.Equal("Option2", selectedValue); Assert.Equal("Title", interactiveServices.OutputMessages[0]); Assert.True(interactiveServices.OutputContains("Title")); Assert.True(interactiveServices.OutputContains("1: Option1")); Assert.True(interactiveServices.OutputContains("2: Option2")); Assert.True(interactiveServices.OutputContains("(default 2")); } [Fact] public void AskUserToChooseStringsPicksNoDefault() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "1" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskUserToChoose(new List<string> { "Option1", "Option2" }, "Title", "Option2"); Assert.Equal("Option1", selectedValue); } [Fact] public void AskUserToChooseStringsFirstSelectInvalid() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "a", "10", "1" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskUserToChoose(new List<string> { "Option1", "Option2" }, "Title", "Option2"); Assert.Equal("Option1", selectedValue); } [Fact] public void AskUserToChooseStringsNoTitle() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "a", "10", "1" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskUserToChoose(new List<string> { "Option1", "Option2" }, null, "Option2"); Assert.Equal("Option1", selectedValue); Assert.Equal("1: Option1", interactiveServices.OutputMessages[0]); } [Fact] public void AskUserForValueCanBeSetToEmptyString() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "<reset>" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskUserForValue( "message", "defaultValue", allowEmpty: true); selectedValue.ShouldEqual(string.Empty); } [Fact] public void AskUserForValueCanBeSetToEmptyStringNoDefault() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "<reset>" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskUserForValue( "message", "", allowEmpty: true); selectedValue.ShouldEqual(string.Empty); } [Fact] public void AskYesNoPickDefault() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { string.Empty }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskYesNoQuestion("Do you want to deploy", YesNo.Yes); Assert.Equal(YesNo.Yes, selectedValue); Assert.Contains("(default y)", interactiveServices.OutputMessages[0]); } [Fact] public void AskYesNoPickNonDefault() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "n" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskYesNoQuestion("Do you want to deploy", YesNo.Yes); Assert.Equal(YesNo.No, selectedValue); } [Fact] public void AskYesNoPickNoDefault() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "n" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskYesNoQuestion("Do you want to deploy"); Assert.Equal(YesNo.No, selectedValue); Assert.DoesNotContain("(default:", interactiveServices.OutputMessages[0]); } [Fact] public void AskYesNoPickInvalidChoice() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "q", "n" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var selectedValue = consoleUtilities.AskYesNoQuestion("Do you want to deploy", YesNo.Yes); Assert.Equal(YesNo.No, selectedValue); interactiveServices.OutputContains("Invalid option."); } [Fact] public void DisplayRow() { var interactiveServices = new TestToolInteractiveServiceImpl(); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); consoleUtilities.DisplayRow(new[] { ("Hello", 10), ("World", 20) }); Assert.Equal("Hello | World ", interactiveServices.OutputMessages[0]); } [Fact] public void GetMFACode() { var options = new AssumeRoleAWSCredentialsOptions { MfaSerialNumber = "serial-number", ExternalId = "external-id" }; var interactiveServices = new TestToolInteractiveServiceImpl(); interactiveServices.QueueConsoleInfos(ConsoleKey.A, ConsoleKey.B, ConsoleKey.C, ConsoleKey.Enter); var callback = new AssumeRoleMfaTokenCodeCallback(interactiveServices, _directoryManager, _optionSettingHandler, options); var code = callback.Execute(); Assert.Equal("ABC", code); Assert.Empty(interactiveServices.InputConsoleKeyInfos); Assert.Equal(5, interactiveServices.OutputMessages.Count); Assert.StartsWith("Enter", interactiveServices.OutputMessages[1]); Assert.Equal("*", interactiveServices.OutputMessages[2]); Assert.Equal("*", interactiveServices.OutputMessages[3]); Assert.Equal("*", interactiveServices.OutputMessages[4]); } [Fact] public void GetMFACodeWithBackspace() { var options = new AssumeRoleAWSCredentialsOptions { MfaSerialNumber = "serial-number", ExternalId = "external-id" }; var interactiveServices = new TestToolInteractiveServiceImpl(); interactiveServices.QueueConsoleInfos(ConsoleKey.A, ConsoleKey.B, ConsoleKey.C, ConsoleKey.Backspace, ConsoleKey.D, ConsoleKey.Enter); var callback = new AssumeRoleMfaTokenCodeCallback(interactiveServices, _directoryManager, _optionSettingHandler, options); var code = callback.Execute(); Assert.Equal("ABD", code); Assert.Empty(interactiveServices.InputConsoleKeyInfos); Assert.Equal(7, interactiveServices.OutputMessages.Count); Assert.StartsWith("Enter", interactiveServices.OutputMessages[1]); Assert.Equal("*", interactiveServices.OutputMessages[2]); Assert.Equal("*", interactiveServices.OutputMessages[3]); Assert.Equal("*", interactiveServices.OutputMessages[4]); Assert.Equal("\b \b", interactiveServices.OutputMessages[5]); Assert.Equal("*", interactiveServices.OutputMessages[6]); } private class OptionItem { public string DisplayName { get; set; } public string Identifier { get; set; } } } }
387
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.CLI.UnitTests { internal static class Constants { public const string ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID = "AspNetAppEcsFargate"; public const string ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID = "AspNetAppElasticBeanstalkLinux"; public const string ASPNET_CORE_BEANSTALK_WINDOWS_RECIPE_ID = "AspNetAppElasticBeanstalkWindows"; public const string ASPNET_CORE_APPRUNNER_ID = "AspNetAppAppRunner"; public const string CONSOLE_APP_FARGATE_SERVICE_RECIPE_ID = "ConsoleAppEcsFargateService"; public const string CONSOLE_APP_FARGATE_SCHEDULE_TASK_RECIPE_ID = "ConsoleAppEcsFargateScheduleTask"; public const string BLAZOR_WASM = "BlazorWasm"; } }
19
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using AWS.Deploy.Recipes; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class DeploymentBundleHandlerTests { private readonly DeploymentBundleHandler _deploymentBundleHandler; private readonly TestToolCommandLineWrapper _commandLineWrapper; private readonly TestDirectoryManager _directoryManager; private readonly ProjectDefinitionParser _projectDefinitionParser; private readonly RecipeDefinition _recipeDefinition; private readonly TestFileManager _fileManager; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly IRecipeHandler _recipeHandler; public DeploymentBundleHandlerTests() { var awsResourceQueryer = new TestToolAWSResourceQueryer(); var interactiveService = new TestToolOrchestratorInteractiveService(); var zipFileManager = new TestZipFileManager(); var serviceProvider = new Mock<IServiceProvider>().Object; _commandLineWrapper = new TestToolCommandLineWrapper(); _fileManager = new TestFileManager(); _directoryManager = new TestDirectoryManager(); var recipeFiles = Directory.GetFiles(RecipeLocator.FindRecipeDefinitionsPath(), "*.recipe", SearchOption.TopDirectoryOnly); _directoryManager.AddedFiles.Add(RecipeLocator.FindRecipeDefinitionsPath(), new HashSet<string> (recipeFiles)); foreach (var recipeFile in recipeFiles) _fileManager.InMemoryStore.Add(recipeFile, File.ReadAllText(recipeFile)); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); var validatorFactory = new ValidatorFactory(serviceProvider); var optionSettingHandler = new OptionSettingHandler(validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService, _directoryManager, _fileManager, optionSettingHandler, validatorFactory); _projectDefinitionParser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); _deploymentBundleHandler = new DeploymentBundleHandler(_commandLineWrapper, awsResourceQueryer, interactiveService, _directoryManager, zipFileManager, new FileManager()); _recipeDefinition = new Mock<RecipeDefinition>( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<DeploymentTypes>(), It.IsAny<DeploymentBundleTypes>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()).Object; } [Fact] public async Task BuildDockerImage_DockerExecutionDirectoryNotSet() { var projectPath = SystemIOUtilities.ResolvePath("ConsoleAppTask"); var project = await _projectDefinitionParser.Parse(projectPath); var options = new List<OptionSettingItem>() { new OptionSettingItem("DockerfilePath", "", "", "") }; var recommendation = new Recommendation(_recipeDefinition, project, 100, new Dictionary<string, object>()); var cloudApplication = new CloudApplication("ConsoleAppTask", String.Empty, CloudApplicationResourceType.CloudFormationStack, string.Empty); var imageTag = "imageTag"; await _deploymentBundleHandler.BuildDockerImage(cloudApplication, recommendation, imageTag); var expectedDockerFile = Path.GetFullPath(Path.Combine(".", "Dockerfile"), recommendation.GetProjectDirectory()); var dockerExecutionDirectory = Directory.GetParent(Path.GetFullPath(recommendation.ProjectPath)).Parent.Parent; Assert.Equal($"docker build -t {imageTag} -f \"{expectedDockerFile}\" .", _commandLineWrapper.CommandsToExecute.First().Command); Assert.Equal(dockerExecutionDirectory.FullName, _commandLineWrapper.CommandsToExecute.First().WorkingDirectory); } [Fact] public async Task BuildDockerImage_DockerExecutionDirectorySet() { var projectPath = new DirectoryInfo(SystemIOUtilities.ResolvePath("ConsoleAppTask")).FullName; var project = await _projectDefinitionParser.Parse(projectPath); var options = new List<OptionSettingItem>() { new OptionSettingItem("DockerfilePath", "", "", "") }; var recommendation = new Recommendation(_recipeDefinition, project, 100, new Dictionary<string, object>()); recommendation.DeploymentBundle.DockerExecutionDirectory = projectPath; var cloudApplication = new CloudApplication("ConsoleAppTask", string.Empty, CloudApplicationResourceType.CloudFormationStack, string.Empty); var imageTag = "imageTag"; await _deploymentBundleHandler.BuildDockerImage(cloudApplication, recommendation, imageTag); var expectedDockerFile = Path.GetFullPath(Path.Combine(".", "Dockerfile"), recommendation.GetProjectDirectory()); Assert.Equal($"docker build -t {imageTag} -f \"{expectedDockerFile}\" .", _commandLineWrapper.CommandsToExecute.First().Command); Assert.Equal(projectPath, _commandLineWrapper.CommandsToExecute.First().WorkingDirectory); } /// <summary> /// Tests the Dockerfile being located in a subfolder instead of the project root /// </summary> [Fact] public async Task BuildDockerImage_AlternativeDockerfilePathSet() { var projectPath = SystemIOUtilities.ResolvePath("ConsoleAppTask"); var project = await _projectDefinitionParser.Parse(projectPath); var options = new List<OptionSettingItem>() { new OptionSettingItem("DockerfilePath", "", "", "") }; var recommendation = new Recommendation(_recipeDefinition, project, 100, new Dictionary<string, object>()); var dockerfilePath = Path.Combine(projectPath, "Docker", "Dockerfile"); var expectedDockerExecutionDirectory = Directory.GetParent(Path.GetFullPath(recommendation.ProjectPath)).Parent.Parent; recommendation.DeploymentBundle.DockerfilePath = dockerfilePath; var cloudApplication = new CloudApplication("ConsoleAppTask", string.Empty, CloudApplicationResourceType.CloudFormationStack, recommendation.Recipe.Id); var imageTag = "imageTag"; await _deploymentBundleHandler.BuildDockerImage(cloudApplication, recommendation, imageTag); Assert.Equal($"docker build -t {imageTag} -f \"{dockerfilePath}\" .", _commandLineWrapper.CommandsToExecute.First().Command); Assert.Equal(expectedDockerExecutionDirectory.FullName, _commandLineWrapper.CommandsToExecute.First().WorkingDirectory); } [Fact] public async Task PushDockerImage_RepositoryNameCheck() { var projectPath = SystemIOUtilities.ResolvePath("ConsoleAppTask"); var project = await _projectDefinitionParser.Parse(projectPath); var recommendation = new Recommendation(_recipeDefinition, project, 100, new Dictionary<string, object>()); var repositoryName = "repository"; await _deploymentBundleHandler.PushDockerImageToECR(recommendation, repositoryName, "ConsoleAppTask:latest"); Assert.Equal(repositoryName, recommendation.DeploymentBundle.ECRRepositoryName); } [Fact] public async Task CreateDotnetPublishZip_NotSelfContained() { var projectPath = SystemIOUtilities.ResolvePath("ConsoleAppTask"); var project = await _projectDefinitionParser.Parse(projectPath); var recommendation = new Recommendation(_recipeDefinition, project, 100, new Dictionary<string, object>()); recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild = false; recommendation.DeploymentBundle.DotnetPublishBuildConfiguration = "Release"; recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments = "--nologo"; await _deploymentBundleHandler.CreateDotnetPublishZip(recommendation); var expectedCommand = $"dotnet publish \"{project.ProjectPath}\"" + $" -o \"{_directoryManager.CreatedDirectories.First()}\"" + " -c Release" + " " + " --nologo"; Assert.Equal(expectedCommand, _commandLineWrapper.CommandsToExecute.First().Command); } [Fact] public async Task CreateDotnetPublishZip_SelfContained() { var projectPath = SystemIOUtilities.ResolvePath("ConsoleAppTask"); var project = await _projectDefinitionParser.Parse(projectPath); var recommendation = new Recommendation(_recipeDefinition, project, 100, new Dictionary<string, object>()); recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild = true; recommendation.DeploymentBundle.DotnetPublishBuildConfiguration = "Release"; recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments = "--nologo"; await _deploymentBundleHandler.CreateDotnetPublishZip(recommendation); var expectedCommand = $"dotnet publish \"{project.ProjectPath}\"" + $" -o \"{_directoryManager.CreatedDirectories.First()}\"" + " -c Release" + " --runtime linux-x64" + " --nologo" + " --self-contained true"; Assert.Equal(expectedCommand, _commandLineWrapper.CommandsToExecute.First().Command); } private async Task<RecommendationEngine> BuildRecommendationEngine(string testProjectName) { var fullPath = SystemIOUtilities.ResolvePath(testProjectName); var parser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var awsCredentials = new Mock<AWSCredentials>(); var session = new OrchestratorSession( await parser.Parse(fullPath), awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; return new RecommendationEngine(session, _recipeHandler); } [Fact] public async Task DockerExecutionDirectory_SolutionLevel() { var projectPath = Path.Combine("docker", "WebAppWithSolutionParentLevel", "WebAppWithSolutionParentLevel"); var engine = await BuildRecommendationEngine(projectPath); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.FirstOrDefault(x => x.Recipe.DeploymentBundle.Equals(DeploymentBundleTypes.Container)); var cloudApplication = new CloudApplication("WebAppWithSolutionParentLevel", string.Empty, CloudApplicationResourceType.CloudFormationStack, string.Empty); var imageTag = "imageTag"; await _deploymentBundleHandler.BuildDockerImage(cloudApplication, recommendation, imageTag); Assert.Equal(Directory.GetParent(SystemIOUtilities.ResolvePath(projectPath)).FullName, recommendation.DeploymentBundle.DockerExecutionDirectory); } [Fact] public async Task DockerExecutionDirectory_DockerfileLevel() { var projectPath = Path.Combine("docker", "WebAppNoSolution"); var engine = await BuildRecommendationEngine(projectPath); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.FirstOrDefault(x => x.Recipe.DeploymentBundle.Equals(DeploymentBundleTypes.Container)); var cloudApplication = new CloudApplication("WebAppNoSolution", string.Empty, CloudApplicationResourceType.CloudFormationStack, string.Empty); var imageTag = "imageTag"; await _deploymentBundleHandler.BuildDockerImage(cloudApplication, recommendation, imageTag); Assert.Equal(Path.GetFullPath(SystemIOUtilities.ResolvePath(projectPath)), recommendation.DeploymentBundle.DockerExecutionDirectory); } } }
262
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Reflection; using System.Threading.Tasks; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.DockerEngine; using Should; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class DockerTests { [Theory] [InlineData("WebAppNoSolution", "")] [InlineData("WebAppWithSolutionSameLevel", "")] [InlineData("WebAppWithSolutionParentLevel", "WebAppWithSolutionParentLevel")] [InlineData("WebAppDifferentAssemblyName", "")] [InlineData("WebAppProjectDependencies", "WebAppProjectDependencies")] [InlineData("WebAppDifferentTargetFramework", "")] [InlineData("ConsoleSdkType", "")] [InlineData("WorkerServiceExample", "")] [InlineData("WebAppNet7", "")] public async Task DockerGenerate(string topLevelFolder, string projectName) { await DockerGenerateTestHelper(topLevelFolder, projectName); } /// <summary> /// Tests that we throw the intended exception when attempting to generate /// a Dockerfile that would reference projects located above the solution /// </summary> [Fact] public async Task DockerGenerate_ParentDependency_Fails() { try { await DockerGenerateTestHelper("WebAppProjectDependenciesAboveSolution", "WebAppProjectDependencies"); Assert.True(false, $"Expected to be unable to generate a Dockerfile"); } catch (Exception ex) { Assert.NotNull(ex); Assert.IsType<DockerEngineException>(ex); Assert.Equal(DeployToolErrorCode.FailedToGenerateDockerFile, (ex as DeployToolException).ErrorCode); } } [Fact] public void DockerFileConfigExists() { var dockerFileConfig = ProjectUtilities.ReadDockerFileConfig(); Assert.False(string.IsNullOrWhiteSpace(dockerFileConfig)); } [Fact] public void DockerfileTemplateExists() { var dockerFileTemplate = ProjectUtilities.ReadTemplate(); Assert.False(string.IsNullOrWhiteSpace(dockerFileTemplate)); } /// <summary> /// Generates the Dockerfile for a specified project from the testapps\Docker\ folder /// and compares it to the hardcoded ReferenceDockerfile /// </summary> private async Task DockerGenerateTestHelper(string topLevelFolder, string projectName) { var projectPath = ResolvePath(Path.Combine(topLevelFolder, projectName)); var fileManager = new FileManager(); var project = await new ProjectDefinitionParser(fileManager, new DirectoryManager()).Parse(projectPath); var engine = new DockerEngine.DockerEngine(project, fileManager, new TestDirectoryManager()); engine.GenerateDockerFile(); AssertDockerFilesAreEqual(projectPath); } private string ResolvePath(string projectName) { var testsPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); while (testsPath != null && !string.Equals(new DirectoryInfo(testsPath).Name, "test", StringComparison.OrdinalIgnoreCase)) { testsPath = Directory.GetParent(testsPath).FullName; } return Path.Combine(testsPath, "..", "testapps", "docker", projectName); } private void AssertDockerFilesAreEqual(string path, string generatedFile = "Dockerfile", string referenceFile = "ReferenceDockerfile") { var generated = File.ReadAllText(Path.Combine(path, generatedFile)); var reference = File.ReadAllText(Path.Combine(path, referenceFile)); // normalize line endings generated = generated.Replace("\r\n", "\n"); reference = reference.Replace("\r\n", "\n"); generated.ShouldEqual(reference); } } }
112
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using AWS.Deploy.Common; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class ExceptionExtensionsTests { [Fact] public void GetTruncatedErrorMessage_EmptyMessage() { // ARRANGE var ex = new Exception(string.Empty); // ACT and ASSERT Assert.Equal(string.Empty, ex.GetTruncatedErrorMessage()); } [Fact] public void GetTruncatedErrorMessage_NoTruncation() { // ARRANGE var message = "This is an AWSDeployToolException"; var ex = new Exception(message); // ACT and ASSERT // No truncation is performed because the message length < 2 * k Assert.Equal(message, ex.GetTruncatedErrorMessage(numChars: 50)); } [Fact] public void GetTruncatedErrorMessage() { // ARRANGE var message = "error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. " + "error text. error text. error text. error text. error text. error text. error text."; var ex = new Exception(message); // ACT var truncatedErrorMessage = ex.GetTruncatedErrorMessage(numChars: 50); // ACT and ASSERT var expectedMessage = @"error text. error text. error text. error text. er ... Error truncated to the first and last 50 characters ... t. error text. error text. error text. error text."; Assert.Equal(expectedMessage, truncatedErrorMessage); } } }
67
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class GetOptionSettingsMapTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IServiceProvider> _serviceProvider; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IProjectDefinitionParser _projectDefinitionParser; public GetOptionSettingsMapTests() { _serviceProvider = new Mock<IServiceProvider>(); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); _directoryManager = new DirectoryManager(); _fileManager = new FileManager(); _projectDefinitionParser = new ProjectDefinitionParser(_fileManager, _directoryManager); } [Fact] public async Task GetOptionSettingsMap() { // ARRANGE - select recommendation var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", _fileManager, _directoryManager, "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppAppRunner")); // ARRANGE - get project definition var projectPath = SystemIOUtilities.ResolvePath("WebAppWithDockerFile"); var projectDefinition = await _projectDefinitionParser.Parse(projectPath); // ARRANGE - Modify option setting items await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ServiceName", "MyAppRunnerService", true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "Port", "100", true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ECRRepositoryName", "my-ecr-repository", true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerfilePath", Path.Combine(projectPath, "Dockerfile"), true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerExecutionDirectory", projectPath, true); // ACT and ASSERT - OptionSettingType.All var container = _optionSettingHandler.GetOptionSettingsMap(selectedRecommendation, projectDefinition, _directoryManager); Assert.Equal("MyAppRunnerService", container["ServiceName"]); Assert.Equal(100, container["Port"]); Assert.Equal("my-ecr-repository", container["ECRRepositoryName"]); Assert.Equal("Dockerfile", container["DockerfilePath"]); // path relative to projectPath Assert.Equal(".", container["DockerExecutionDirectory"]); // path relative to projectPath // ACT and ASSERT - OptionSettingType.Recipe container = _optionSettingHandler.GetOptionSettingsMap(selectedRecommendation, projectDefinition, _directoryManager, OptionSettingsType.Recipe); Assert.Equal("MyAppRunnerService", container["ServiceName"]); Assert.Equal(100, container["Port"]); Assert.False(container.ContainsKey("Dockerfile")); Assert.False(container.ContainsKey("DockerExecutionDirectory")); Assert.False(container.ContainsKey("ECRRepositoryName")); // ACT and ASSERT - OptionSettingType.DeploymentBundle container = _optionSettingHandler.GetOptionSettingsMap(selectedRecommendation, projectDefinition, _directoryManager, OptionSettingsType.DeploymentBundle); Assert.Equal("my-ecr-repository", container["ECRRepositoryName"]); Assert.Equal("Dockerfile", container["DockerfilePath"]); // path relative to projectPath Assert.Equal(".", container["DockerExecutionDirectory"]); // path relative to projectPath Assert.False(container.ContainsKey("ServiceName")); Assert.False(container.ContainsKey("Port")); } } }
88
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.EC2.Model; using Amazon.Runtime; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using AWS.Deploy.Recipes; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class GetOptionSettingTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IRecipeHandler _recipeHandler; public GetOptionSettingTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); _directoryManager = new DirectoryManager(); _fileManager = new FileManager(); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService, _directoryManager, _fileManager, optionSettingHandler, validatorFactory); _serviceProvider .Setup(x => x.GetService(typeof(IOptionSettingHandler))) .Returns(_optionSettingHandler); } private async Task<RecommendationEngine> BuildRecommendationEngine(string testProjectName) { var fullPath = SystemIOUtilities.ResolvePath(testProjectName); var parser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var awsCredentials = new Mock<AWSCredentials>(); var session = new OrchestratorSession( await parser.Parse(fullPath), awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; return new RecommendationEngine(session, _recipeHandler); } [Theory] [InlineData("ApplicationIAMRole.RoleArn", "RoleArn")] public async Task GetOptionSettingTests_OptionSettingExists(string jsonPath, string targetId) { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var optionSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, jsonPath); Assert.NotNull(optionSetting); Assert.Equal(optionSetting.Id, targetId); } [Theory] [InlineData("ApplicationIAMRole.Foo")] public async Task GetOptionSettingTests_OptionSettingDoesNotExist(string jsonPath) { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); Assert.Throws<OptionSettingItemDoesNotExistException>(() => _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, jsonPath)); } [Theory] [InlineData("ElasticBeanstalkManagedPlatformUpdates", "ManagedActionsEnabled", true, 3)] [InlineData("ElasticBeanstalkManagedPlatformUpdates", "ManagedActionsEnabled", false, 1)] public async Task GetOptionSettingTests_GetDisplayableChildren(string optionSetting, string childSetting, bool childValue, int displayableCount) { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var managedActionsEnabled = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, $"{optionSetting}.{childSetting}"); await _optionSettingHandler.SetOptionSettingValue(beanstalkRecommendation, managedActionsEnabled, childValue); var elasticBeanstalkManagedPlatformUpdates = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, optionSetting); var elasticBeanstalkManagedPlatformUpdatesValue = _optionSettingHandler.GetOptionSettingValue<Dictionary<string, object>>(beanstalkRecommendation, elasticBeanstalkManagedPlatformUpdates); Assert.Equal(displayableCount, elasticBeanstalkManagedPlatformUpdatesValue.Count); } [Fact] public async Task GetOptionSettingTests_ListType_InvalidValue() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var testVpc = new Vpc { VpcId = "vpc1" }; var listVpcs = new List<Vpc> { testVpc }; _awsResourceQueryer.Setup(x => x.GetDefaultVpc()).ReturnsAsync(testVpc); _awsResourceQueryer.Setup(x => x.GetListOfVpcs()).ReturnsAsync(listVpcs); _awsResourceQueryer.Setup(x => x.DescribeSubnets(It.IsAny<string>())).ReturnsAsync(new List<Subnet>()); _awsResourceQueryer.Setup(x => x.DescribeSecurityGroups(It.IsAny<string>())).ReturnsAsync(new List<SecurityGroup>()); var useVpcConnector = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.UseVPCConnector"); var createNew = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.CreateNew"); var createNewVpc = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.CreateNewVpc"); var vpcId = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.VpcId"); var subnets = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.Subnets"); var securityGroups = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.SecurityGroups"); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, useVpcConnector, true); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, createNew, true); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, createNewVpc, false); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, vpcId, "vpc-1234abcd"); await Assert.ThrowsAsync<ValidationFailedException>(async () => await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, subnets, new SortedSet<string>(){ "subnet1" })); await Assert.ThrowsAsync<ValidationFailedException>(async () => await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, securityGroups, new SortedSet<string>(){ "securityGroup1" })); } [Fact] public async Task GetOptionSettingTests_VPCConnector_DisplayableItems() { var SETTING_ID_VPCCONNECTOR = "VPCConnector"; var SETTING_ID_USEVPCCONNECTOR = "UseVPCConnector"; var SETTING_ID_CREATENEW = "CreateNew"; var SETTING_ID_VPCCONNECTORID = "VpcConnectorId"; var SETTING_ID_CREATENEWVPC = "CreateNewVpc"; var SETTING_ID_VPCID = "VpcId"; var SETTING_ID_SUBNETS = "Subnets"; var SETTING_ID_SECURITYGROUPS = "SecurityGroups"; var engine = await BuildRecommendationEngine("WebAppWithDockerFile"); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var testVpc = new Vpc { VpcId = "vpc1" }; var listVpcs = new List<Vpc> { testVpc }; _awsResourceQueryer.Setup(x => x.GetDefaultVpc()).ReturnsAsync(testVpc); _awsResourceQueryer.Setup(x => x.GetListOfVpcs()).ReturnsAsync(listVpcs); _awsResourceQueryer.Setup(x => x.DescribeSubnets(It.IsAny<string>())).ReturnsAsync(new List<Subnet>()); _awsResourceQueryer.Setup(x => x.DescribeSecurityGroups(It.IsAny<string>())).ReturnsAsync(new List<SecurityGroup>()); var vpcConnector = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, SETTING_ID_VPCCONNECTOR); var vpcConnectorChildren = vpcConnector.ChildOptionSettings.Where(x => _optionSettingHandler.IsOptionSettingDisplayable(appRunnerRecommendation, x)).ToList(); Assert.Single(vpcConnectorChildren); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_USEVPCCONNECTOR))); var useVpcConnector = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, $"{SETTING_ID_VPCCONNECTOR}.{SETTING_ID_USEVPCCONNECTOR}"); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, useVpcConnector, true); vpcConnectorChildren = vpcConnector.ChildOptionSettings.Where(x => _optionSettingHandler.IsOptionSettingDisplayable(appRunnerRecommendation, x)).ToList(); Assert.Equal(3, vpcConnectorChildren.Count); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_USEVPCCONNECTOR))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_CREATENEW))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_VPCCONNECTORID))); var createNewVpc = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, $"{SETTING_ID_VPCCONNECTOR}.{SETTING_ID_CREATENEWVPC}"); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, createNewVpc, true); vpcConnectorChildren = vpcConnector.ChildOptionSettings.Where(x => _optionSettingHandler.IsOptionSettingDisplayable(appRunnerRecommendation, x)).ToList(); Assert.Equal(3, vpcConnectorChildren.Count); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_USEVPCCONNECTOR))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_CREATENEW))); var createNew = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, $"{SETTING_ID_VPCCONNECTOR}.{SETTING_ID_CREATENEW}"); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, createNew, true); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, createNewVpc, false); vpcConnectorChildren = vpcConnector.ChildOptionSettings.Where(x => _optionSettingHandler.IsOptionSettingDisplayable(appRunnerRecommendation, x)).ToList(); Assert.Equal(4, vpcConnectorChildren.Count); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_USEVPCCONNECTOR))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_CREATENEW))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_CREATENEWVPC))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_VPCID))); var vpcId = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, $"{SETTING_ID_VPCCONNECTOR}.{SETTING_ID_VPCID}"); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, vpcId, "vpc-abcd1234"); vpcConnectorChildren = vpcConnector.ChildOptionSettings.Where(x => _optionSettingHandler.IsOptionSettingDisplayable(appRunnerRecommendation, x)).ToList(); Assert.Equal(6, vpcConnectorChildren.Count); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_USEVPCCONNECTOR))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_CREATENEW))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_CREATENEWVPC))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_VPCID))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_SUBNETS))); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_SECURITYGROUPS))); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, useVpcConnector, false); vpcConnectorChildren = vpcConnector.ChildOptionSettings.Where(x => _optionSettingHandler.IsOptionSettingDisplayable(appRunnerRecommendation, x)).ToList(); Assert.Single(vpcConnectorChildren); Assert.NotNull(vpcConnectorChildren.First(x => x.Id.Equals(SETTING_ID_USEVPCCONNECTOR))); } [Fact] public async Task GetOptionSettingTests_ListType() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var subnets = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.Subnets"); var emptySubnetsValue = _optionSettingHandler.GetOptionSettingValue(appRunnerRecommendation, subnets); await _optionSettingHandler.SetOptionSettingValue(appRunnerRecommendation, subnets, new SortedSet<string>(){ "subnet-1234abcd" }); var subnetsValue = _optionSettingHandler.GetOptionSettingValue(appRunnerRecommendation, subnets); var emptySubnetsString = Assert.IsType<string>(emptySubnetsValue); Assert.True(string.IsNullOrEmpty(emptySubnetsString)); var subnetsList = Assert.IsType<SortedSet<string>>(subnetsValue); Assert.Single(subnetsList); Assert.Contains("subnet-1234abcd", subnetsList); } } }
251
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Constants; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class IsOptionSettingModifiedTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IServiceProvider> _serviceProvider; public IsOptionSettingModifiedTests() { _serviceProvider = new Mock<IServiceProvider>(); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task IsOptionSettingModified_ElasticBeanstalk() { // ARRANGE - select recommendation var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppElasticBeanstalkLinux")); // ARRANGE - add replacement tokens selectedRecommendation.AddReplacementToken(RecipeIdentifier.REPLACE_TOKEN_LATEST_DOTNET_BEANSTALK_PLATFORM_ARN, "Latest-ARN"); selectedRecommendation.AddReplacementToken(RecipeIdentifier.REPLACE_TOKEN_STACK_NAME, "MyAppStack"); selectedRecommendation.AddReplacementToken(RecipeIdentifier.REPLACE_TOKEN_DEFAULT_VPC_ID, "vpc-12345678"); // ARRANGE - modify settings so that they are different from their default values await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "BeanstalkEnvironment.EnvironmentName", "MyEnvironment", skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "EnvironmentType", "LoadBalanced", skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ApplicationIAMRole.CreateNew", false, skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ApplicationIAMRole.RoleArn", "MyRoleArn", skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "XRayTracingSupportEnabled", true, skipValidation: true); var modifiedSettingsId = new HashSet<string> { "BeanstalkEnvironment", "EnvironmentType", "ApplicationIAMRole", "XRayTracingSupportEnabled" }; // ACT and ASSERT foreach (var optionSetting in selectedRecommendation.GetConfigurableOptionSettingItems()) { if (modifiedSettingsId.Contains(optionSetting.FullyQualifiedId)) { Assert.True(_optionSettingHandler.IsOptionSettingModified(selectedRecommendation, optionSetting)); } else { Assert.False(_optionSettingHandler.IsOptionSettingModified(selectedRecommendation, optionSetting)); } } } [Fact] public async Task IsOptionSettingModified_ECSFargate() { // ARRANGE - select recommendation var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var selectedRecommendation = recommendations.FirstOrDefault(x => string.Equals(x.Recipe.Id, "AspNetAppEcsFargate")); // ARRANGE - add replacement tokens selectedRecommendation.AddReplacementToken(RecipeIdentifier.REPLACE_TOKEN_STACK_NAME, "MyAppStack"); selectedRecommendation.AddReplacementToken(RecipeIdentifier.REPLACE_TOKEN_DEFAULT_VPC_ID, "vpc-12345678"); selectedRecommendation.AddReplacementToken(RecipeIdentifier.REPLACE_TOKEN_HAS_DEFAULT_VPC, true); // ARRANGE - modify settings so that they are different from their default values await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ECSServiceName", "MyECSService", skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DesiredCount", 10, skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ECSCluster.CreateNew", false, skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "ECSCluster.ClusterArn", "MyClusterArn", skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerfilePath", "Path/To/DockerFile", skipValidation: true); await _optionSettingHandler.SetOptionSettingValue(selectedRecommendation, "DockerExecutionDirectory", "Path/To/ExecutionDirectory", skipValidation: true); var modifiedSettingsId = new HashSet<string> { "ECSServiceName", "DesiredCount", "ECSCluster", "DockerfilePath", "DockerExecutionDirectory" }; // ACT and ASSERT foreach (var optionSetting in selectedRecommendation.GetConfigurableOptionSettingItems()) { if (modifiedSettingsId.Contains(optionSetting.FullyQualifiedId)) { Assert.True(_optionSettingHandler.IsOptionSettingModified(selectedRecommendation, optionSetting)); } else { Assert.False(_optionSettingHandler.IsOptionSettingModified(selectedRecommendation, optionSetting)); } } } } }
122
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading.Tasks; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using Xunit; using Should; using AWS.Deploy.CLI.Utilities; namespace AWS.Deploy.CLI.UnitTests { public class ProjectParserUtilityTests { [Theory] [InlineData("WebAppWithDockerFile", "WebAppWithDockerFile.csproj")] [InlineData("WebAppNoDockerFile", "WebAppNoDockerFile.csproj")] [InlineData("ConsoleAppTask", "ConsoleAppTask.csproj")] [InlineData("ConsoleAppService", "ConsoleAppService.csproj")] [InlineData("MessageProcessingApp", "MessageProcessingApp.csproj")] [InlineData("ContosoUniversityBackendService", "ContosoUniversityBackendService.csproj")] [InlineData("ContosoUniversityWeb", "ContosoUniversity.csproj")] [InlineData("BlazorWasm60", "BlazorWasm60.csproj")] public async Task ParseProjectDefinitionWithRelativeProjectPath(string projectName, string csprojName) { //Arrange var currrentWorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var projectDirectoryPath = SystemIOUtilities.ResolvePath(projectName); var absoluteProjectDirectoryPath = new DirectoryInfo(projectDirectoryPath).FullName; var absoluteProjectPath = Path.Combine(absoluteProjectDirectoryPath, csprojName); var relativeProjectDirectoryPath = Path.GetRelativePath(currrentWorkingDirectory, absoluteProjectDirectoryPath); var projectSolutionPath = SystemIOUtilities.ResolvePathToSolution(); var projectDefinitionParser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var projectParserUtility = new ProjectParserUtility(projectDefinitionParser, new DirectoryManager()); // Act var projectDefinition = await projectParserUtility.Parse(relativeProjectDirectoryPath); // Assert projectDefinition.ShouldNotBeNull(); Assert.Equal(absoluteProjectPath, projectDefinition.ProjectPath); Assert.Equal(projectSolutionPath, projectDefinition.ProjectSolutionPath); } [Theory] [InlineData("WebAppWithDockerFile", "WebAppWithDockerFile.csproj")] [InlineData("WebAppNoDockerFile", "WebAppNoDockerFile.csproj")] [InlineData("ConsoleAppTask", "ConsoleAppTask.csproj")] [InlineData("ConsoleAppService", "ConsoleAppService.csproj")] [InlineData("MessageProcessingApp", "MessageProcessingApp.csproj")] [InlineData("ContosoUniversityBackendService", "ContosoUniversityBackendService.csproj")] [InlineData("ContosoUniversityWeb", "ContosoUniversity.csproj")] [InlineData("BlazorWasm60", "BlazorWasm60.csproj")] public async Task ParseProjectDefinitionWithAbsoluteProjectPath(string projectName, string csprojName) { //Arrange var projectDirectoryPath = SystemIOUtilities.ResolvePath(projectName); var absoluteProjectDirectoryPath = new DirectoryInfo(projectDirectoryPath).FullName; var absoluteProjectPath = Path.Combine(absoluteProjectDirectoryPath, csprojName); var projectSolutionPath = SystemIOUtilities.ResolvePathToSolution(); var projectDefinitionParser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var projectParserUtility = new ProjectParserUtility(projectDefinitionParser, new DirectoryManager()); // Act var projectDefinition = await projectParserUtility.Parse(absoluteProjectPath); // Assert projectDefinition.ShouldNotBeNull(); Assert.Equal(absoluteProjectPath, projectDefinition.ProjectPath); Assert.Equal(projectSolutionPath, projectDefinition.ProjectSolutionPath); } [Theory] [InlineData("C:\\MyProject\\doesNotExistSrc")] [InlineData("C:\\MyProject\\src\\doesNotExist.csproj")] public async Task Throws_FailedToFindDeployableTargetException_WithInvalidProjectPaths(string projectPath) { // Arrange var projectDefinitionParser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var projectParserUtility = new ProjectParserUtility(projectDefinitionParser, new DirectoryManager()); // Act and Assert var ex = await Assert.ThrowsAsync<FailedToFindDeployableTargetException>(async () => await projectParserUtility.Parse(projectPath)); Assert.Equal($"Failed to find a valid .csproj or .fsproj file at path {projectPath}", ex.Message); } } }
95
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.TypeHintResponses; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using AWS.Deploy.Recipes; using Moq; using Should; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class RecommendationTests { private OrchestratorSession _session; private readonly TestDirectoryManager _directoryManager; private readonly Mock<IValidatorFactory> _validatorFactory; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly SubnetsInVpcValidator _subnetsInVpcValidator; private readonly Mock<IServiceProvider> _serviceProvider; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly TestFileManager _fileManager; private readonly IRecipeHandler _recipeHandler; public RecommendationTests() { _directoryManager = new TestDirectoryManager(); _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _validatorFactory = new Mock<IValidatorFactory>(); _optionSettingHandler = new OptionSettingHandler(_validatorFactory.Object); _subnetsInVpcValidator = new SubnetsInVpcValidator(_awsResourceQueryer.Object, _optionSettingHandler); _serviceProvider .Setup(x => x.GetService(typeof(IOptionSettingItemValidator))) .Returns(_subnetsInVpcValidator); _directoryManager = new TestDirectoryManager(); _fileManager = new TestFileManager(); var recipeFiles = Directory.GetFiles(RecipeLocator.FindRecipeDefinitionsPath(), "*.recipe", SearchOption.TopDirectoryOnly); _directoryManager.AddedFiles.Add(RecipeLocator.FindRecipeDefinitionsPath(), new HashSet<string>(recipeFiles)); foreach (var recipeFile in recipeFiles) _fileManager.InMemoryStore.Add(recipeFile, File.ReadAllText(recipeFile)); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService, _directoryManager, _fileManager, _optionSettingHandler, _validatorFactory.Object); } private async Task<RecommendationEngine> BuildRecommendationEngine(string testProjectName) { var fullPath = SystemIOUtilities.ResolvePath(testProjectName); var parser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var awsCredentials = new Mock<AWSCredentials>(); _session = new OrchestratorSession( await parser.Parse(fullPath), awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; return new RecommendationEngine(_session, _recipeHandler); } [Fact] public async Task WebAppNoDockerFileTest() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); recommendations .Any(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); recommendations .Any(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); } [Fact] public async Task WebApiNET6() { var engine = await BuildRecommendationEngine("WebApiNET6"); var recommendations = await engine.ComputeRecommendations(); recommendations .Any(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); recommendations .Any(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); recommendations .Any(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_APPRUNNER_ID); } [Fact] public async Task WebAppWithDockerFileTest() { var engine = await BuildRecommendationEngine("WebAppWithDockerFile"); var recommendations = await engine.ComputeRecommendations(); recommendations .Any(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); recommendations .Any(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); } [Fact] public async Task MessageProcessingAppTest() { var projectPath = SystemIOUtilities.ResolvePath("MessageProcessingApp"); var engine = await BuildRecommendationEngine("MessageProcessingApp"); var recommendations = await engine.ComputeRecommendations(); recommendations .Any(r => r.Recipe.Id == Constants.CONSOLE_APP_FARGATE_SERVICE_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.CONSOLE_APP_FARGATE_SERVICE_RECIPE_ID); recommendations .Any(r => r.Recipe.Id == Constants.CONSOLE_APP_FARGATE_SCHEDULE_TASK_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.CONSOLE_APP_FARGATE_SCHEDULE_TASK_RECIPE_ID); } [Theory] [InlineData("BlazorWasm60")] public async Task BlazorWasmTest(string projectName) { var engine = await BuildRecommendationEngine(projectName); var recommendations = await engine.ComputeRecommendations(); var blazorRecommendation = recommendations.FirstOrDefault(r => r.Recipe.Id == Constants.BLAZOR_WASM); Assert.NotNull(blazorRecommendation); } [Fact] public async Task WorkerServiceTest() { var engine = await BuildRecommendationEngine("WorkerServiceExample"); var recommendations = await engine.ComputeRecommendations(); Assert.Single(recommendations); recommendations .Any(r => r.Recipe.Id == Constants.CONSOLE_APP_FARGATE_SERVICE_RECIPE_ID) .ShouldBeTrue("Failed to receive Recommendation: " + Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); } [Fact] public async Task ValueMappingWithDefaultValue() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var environmentTypeOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("EnvironmentType")); Assert.Equal("SingleInstance", _optionSettingHandler.GetOptionSettingValue(beanstalkRecommendation, environmentTypeOptionSetting)); } [Fact] public async Task ResetOptionSettingValue_Int() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "<reset>" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var fargateRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); var desiredCountOptionSetting = fargateRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("DesiredCount")); var originalDefaultValue = _optionSettingHandler.GetOptionSettingDefaultValue<int>(fargateRecommendation, desiredCountOptionSetting); await _optionSettingHandler.SetOptionSettingValue(fargateRecommendation, desiredCountOptionSetting, 2); Assert.Equal(2, _optionSettingHandler.GetOptionSettingValue<int>(fargateRecommendation, desiredCountOptionSetting)); await _optionSettingHandler.SetOptionSettingValue(fargateRecommendation, desiredCountOptionSetting, consoleUtilities.AskUserForValue("Title", "2", true, originalDefaultValue.ToString())); Assert.Equal(originalDefaultValue, _optionSettingHandler.GetOptionSettingValue<int>(fargateRecommendation, desiredCountOptionSetting)); } [Fact] public async Task ResetOptionSettingValue_String() { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "<reset>" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var fargateRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); fargateRecommendation.AddReplacementToken("{StackName}", "MyAppStack"); var ecsServiceNameOptionSetting = fargateRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("ECSServiceName")); var originalDefaultValue = _optionSettingHandler.GetOptionSettingDefaultValue<string>(fargateRecommendation, ecsServiceNameOptionSetting); await _optionSettingHandler.SetOptionSettingValue(fargateRecommendation, ecsServiceNameOptionSetting, "TestService"); Assert.Equal("TestService", _optionSettingHandler.GetOptionSettingValue<string>(fargateRecommendation, ecsServiceNameOptionSetting)); await _optionSettingHandler.SetOptionSettingValue(fargateRecommendation, ecsServiceNameOptionSetting, consoleUtilities.AskUserForValue("Title", "TestService", true, originalDefaultValue)); Assert.Equal(originalDefaultValue, _optionSettingHandler.GetOptionSettingValue<string>(fargateRecommendation, ecsServiceNameOptionSetting)); } [Fact] public async Task ObjectMappingWithDefaultValue() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var applicationIAMRoleOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("ApplicationIAMRole")); var iamRoleTypeHintResponse = _optionSettingHandler.GetOptionSettingValue<IAMRoleTypeHintResponse>(beanstalkRecommendation, applicationIAMRoleOptionSetting); Assert.Null(iamRoleTypeHintResponse.RoleArn); Assert.True(iamRoleTypeHintResponse.CreateNew); } [Fact] public async Task ObjectMappingWithoutDefaultValue() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var applicationIAMRoleOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("ApplicationIAMRole")); Assert.Null(_optionSettingHandler.GetOptionSettingDefaultValue(beanstalkRecommendation, applicationIAMRoleOptionSetting)); } [Fact] public async Task ValueMappingSetWithValue() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var environmentTypeOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("EnvironmentType")); await _optionSettingHandler.SetOptionSettingValue(beanstalkRecommendation, environmentTypeOptionSetting, "LoadBalanced"); Assert.Equal("LoadBalanced", _optionSettingHandler.GetOptionSettingValue(beanstalkRecommendation, environmentTypeOptionSetting)); } [Fact] public async Task ObjectMappingSetWithValue() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var applicationIAMRoleOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("ApplicationIAMRole")); await _optionSettingHandler.SetOptionSettingValue(beanstalkRecommendation, applicationIAMRoleOptionSetting, new IAMRoleTypeHintResponse {CreateNew = false, RoleArn = "arn:aws:iam::123456789012:group/Developers" }); var iamRoleTypeHintResponse = _optionSettingHandler.GetOptionSettingValue<IAMRoleTypeHintResponse>(beanstalkRecommendation, applicationIAMRoleOptionSetting); Assert.Equal("arn:aws:iam::123456789012:group/Developers", iamRoleTypeHintResponse.RoleArn); Assert.False(iamRoleTypeHintResponse.CreateNew); } [Fact] public async Task ApplyProjectNameToSettings() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.FirstOrDefault(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var beanstalEnvNameSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "BeanstalkEnvironment.EnvironmentName"); beanstalkRecommendation.AddReplacementToken("{StackName}", "MyAppStack"); Assert.Equal("MyAppStack-dev", _optionSettingHandler.GetOptionSettingValue<string>(beanstalkRecommendation, beanstalEnvNameSetting)); beanstalkRecommendation.AddReplacementToken("{StackName}", "CustomAppStack"); Assert.Equal("CustomAppStack-dev", _optionSettingHandler.GetOptionSettingValue<string>(beanstalkRecommendation, beanstalEnvNameSetting)); } [Fact] public async Task GetKeyValueOptionSettingServerMode() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.FirstOrDefault(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var envVarsSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "ElasticBeanstalkEnvironmentVariables"); Assert.Equal(OptionSettingValueType.KeyValue, envVarsSetting.Type); } [Fact] public async Task GetKeyValueOptionSettingConfigFile() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.FirstOrDefault(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var envVarsSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "ElasticBeanstalkEnvironmentVariables.Key"); Assert.Equal(OptionSettingValueType.KeyValue, envVarsSetting.Type); } [Theory] [MemberData(nameof(ShouldIncludeTestCases))] public void ShouldIncludeTests(RuleEffect effect, bool testPass, bool expectedResult) { var awsCredentials = new Mock<AWSCredentials>(); var session = new OrchestratorSession( null, awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; var engine = new RecommendationEngine(session, _recipeHandler); Assert.Equal(expectedResult, engine.ShouldInclude(effect, testPass)); } public static IEnumerable<object[]> ShouldIncludeTestCases => new List<object[]> { // No effect defined new object[]{ new RuleEffect { }, true, true }, new object[]{ new RuleEffect { }, false, false }, // Negative Rule new object[]{ new RuleEffect { Pass = new EffectOptions {Include = false }, Fail = new EffectOptions { Include = true } }, true, false }, new object[]{ new RuleEffect { Pass = new EffectOptions {Include = false }, Fail = new EffectOptions { Include = true } }, false, true }, // Explicitly define effects new object[]{ new RuleEffect { Pass = new EffectOptions {Include = true }, Fail = new EffectOptions { Include = false} }, true, true }, new object[]{ new RuleEffect { Pass = new EffectOptions {Include = true }, Fail = new EffectOptions { Include = false} }, false, false }, // Positive rule to adjust priority new object[]{ new RuleEffect { Pass = new EffectOptions {PriorityAdjustment = 55 } }, true, true }, new object[]{ new RuleEffect { Pass = new EffectOptions { PriorityAdjustment = 55 }, Fail = new EffectOptions { Include = true } }, false, true }, // Negative rule to adjust priority new object[]{ new RuleEffect { Fail = new EffectOptions {PriorityAdjustment = -55 } }, true, true }, new object[]{ new RuleEffect { Fail = new EffectOptions { PriorityAdjustment = -55 } }, false, true }, }; [Fact] public async Task IsDisplayable_OneDependency() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var environmentTypeOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("EnvironmentType")); var loadBalancerTypeOptionSetting = beanstalkRecommendation.Recipe.OptionSettings.First(optionSetting => optionSetting.Id.Equals("LoadBalancerType")); Assert.Equal("SingleInstance", _optionSettingHandler.GetOptionSettingValue(beanstalkRecommendation, environmentTypeOptionSetting)); // Before dependency isn't satisfied Assert.False(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, loadBalancerTypeOptionSetting)); // Satisfy dependency await _optionSettingHandler.SetOptionSettingValue(beanstalkRecommendation, environmentTypeOptionSetting, "LoadBalanced"); Assert.Equal("LoadBalanced", _optionSettingHandler.GetOptionSettingValue(beanstalkRecommendation, environmentTypeOptionSetting)); // Verify Assert.True(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, loadBalancerTypeOptionSetting)); } [Fact] public async Task IsDisplayable_ManyDependencies() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var fargateRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_ASPNET_CORE_FARGATE_RECIPE_ID); var isDefaultOptionSetting = _optionSettingHandler.GetOptionSetting(fargateRecommendation, "Vpc.IsDefault"); var createNewOptionSetting = _optionSettingHandler.GetOptionSetting(fargateRecommendation, "Vpc.CreateNew"); var vpcIdOptionSetting = _optionSettingHandler.GetOptionSetting(fargateRecommendation, "Vpc.VpcId"); // Before dependency aren't satisfied Assert.False(_optionSettingHandler.IsOptionSettingDisplayable(fargateRecommendation, vpcIdOptionSetting)); // Satisfy dependencies await _optionSettingHandler.SetOptionSettingValue(fargateRecommendation, isDefaultOptionSetting, false); Assert.False(_optionSettingHandler.GetOptionSettingValue<bool>(fargateRecommendation, isDefaultOptionSetting)); // Default value for Vpc.CreateNew already false, this is to show explicitly setting an override that satisfies Vpc Id option setting await _optionSettingHandler.SetOptionSettingValue(fargateRecommendation, createNewOptionSetting, false); Assert.False(_optionSettingHandler.GetOptionSettingValue<bool>(fargateRecommendation, createNewOptionSetting)); // Verify Assert.True(_optionSettingHandler.IsOptionSettingDisplayable(fargateRecommendation, vpcIdOptionSetting)); } [Fact] public async Task IsDisplayable_NotEmptyOperation() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var useVpcOptionSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "VPC.UseVPC"); var createNewOptionSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "VPC.CreateNew"); var vpcIdOptionSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "VPC.VpcId"); var subnetsSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "VPC.Subnets"); // Before dependency aren't satisfied Assert.True(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, useVpcOptionSetting)); Assert.False(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, createNewOptionSetting)); Assert.False(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, vpcIdOptionSetting)); Assert.False(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, subnetsSetting)); // Satisfy dependencies await _optionSettingHandler.SetOptionSettingValue(beanstalkRecommendation, useVpcOptionSetting, true); await _optionSettingHandler.SetOptionSettingValue(beanstalkRecommendation, createNewOptionSetting, false); await _optionSettingHandler.SetOptionSettingValue(beanstalkRecommendation, vpcIdOptionSetting, "vpc-1234abcd"); Assert.True(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, vpcIdOptionSetting)); Assert.True(_optionSettingHandler.IsOptionSettingDisplayable(beanstalkRecommendation, subnetsSetting)); } [Fact] public void LoadAvailableRecommendationTests() { var tests = RecommendationTestFactory.LoadAvailableTests(); Assert.True(tests.Count > 0); // Look to see if the known system test FileExists has been found by LoadAvailableTests. Assert.Contains(new FileExistsTest().Name, tests); } [Fact] public async Task PackageReferenceTest() { var projectPath = SystemIOUtilities.ResolvePath("MessageProcessingApp"); var projectDefinition = await new ProjectDefinitionParser(new FileManager(), new DirectoryManager()).Parse(projectPath); var test = new NuGetPackageReferenceTest(); Assert.True(await test.Execute(new RecommendationTestInput( new RuleTest( test.Name, new RuleCondition { NuGetPackageName = "AWSSDK.SQS" }), projectDefinition, _session))); Assert.False(await test.Execute(new RecommendationTestInput( new RuleTest( test.Name, new RuleCondition { NuGetPackageName = "AWSSDK.S3" }), projectDefinition, _session))); } } }
524
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Security.Claims; using System.Threading.Tasks; using AWS.Deploy.CLI.ServerMode; using AWS.Deploy.CLI.ServerMode.Services; using Xunit; using Amazon.Runtime; using AWS.Deploy.ServerMode.Client; using System.Security.Cryptography; using Newtonsoft.Json; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.UnitTests.Utilities; using System.Threading; using System.Globalization; using AWS.Deploy.CLI.IntegrationTests.Services; namespace AWS.Deploy.CLI.UnitTests { public class ServerModeAuthTests { [Fact] public async Task GetBasicCredentialsFromClaimsPrincipal() { var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(AwsCredentialsAuthenticationHandler.ClaimAwsAccessKeyId, "accessKeyId"), new Claim(AwsCredentialsAuthenticationHandler.ClaimAwsSecretKey, "secretKey") }); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var awsCredentials = claimsPrincipal.ToAWSCredentials(); Assert.IsType<Amazon.Runtime.BasicAWSCredentials>(awsCredentials); var imutCreds = await awsCredentials.GetCredentialsAsync(); Assert.Equal("accessKeyId", imutCreds.AccessKey); Assert.Equal("secretKey", imutCreds.SecretKey); } [Fact] public async Task GetSessionCredentialsFromClaimsPrincipal() { var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(AwsCredentialsAuthenticationHandler.ClaimAwsAccessKeyId, "accessKeyId"), new Claim(AwsCredentialsAuthenticationHandler.ClaimAwsSecretKey, "secretKey"), new Claim(AwsCredentialsAuthenticationHandler.ClaimAwsSessionToken, "sessionToken"), }); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var awsCredentials = claimsPrincipal.ToAWSCredentials(); Assert.IsType<Amazon.Runtime.SessionAWSCredentials>(awsCredentials); var imutCreds = await awsCredentials.GetCredentialsAsync(); Assert.Equal("accessKeyId", imutCreds.AccessKey); Assert.Equal("secretKey", imutCreds.SecretKey); Assert.Equal("sessionToken", imutCreds.Token); } [Fact] public void NoCredentialsSetForClaimsPrincipal() { var claimsIdentity = new ClaimsIdentity(new Claim[] { }); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var awsCredentials = claimsPrincipal.ToAWSCredentials(); Assert.Null(awsCredentials); } [Fact] public void ProcessAuthorizationHeaderSuccess() { var request = new HttpRequestMessage(); var creds = new ImmutableCredentials("accessKeyId", "secretKey", "token"); ServerModeHttpClientAuthorizationHandler.AddAuthorizationHeader(request, creds); if (!request.Headers.TryGetValues("Authorization", out var value)) { throw new Exception("Missing Authorization header"); } var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader(value.FirstOrDefault(), new NoEncryptionProvider()); Assert.True(authResults.Succeeded); } [Fact] public void ProcessAuthorizationHeaderFailNoSchema() { var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader("no-schema-value", new NoEncryptionProvider()); Assert.False(authResults.Succeeded); Assert.Contains("Incorrect format Authorization header", authResults.Failure.Message); } [Fact] public void ProcessAuthorizationHeaderFailWrongSchema() { var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader("wrong-schema value", new NoEncryptionProvider()); Assert.False(authResults.Succeeded); Assert.Contains("Unsupported authorization schema", authResults.Failure.Message); } [Fact] public void ProcessAuthorizationHeaderFailInValidJson() { var base64BadJson = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("you are not json")); var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader($"aws-deploy-tool-server-mode {base64BadJson}", new NoEncryptionProvider()); Assert.False(authResults.Succeeded); Assert.Equal("Error decoding authorization value", authResults.Failure.Message); } [Fact] public void AuthPassCredentialsEncrypted() { var aes = Aes.Create(); var request = new HttpRequestMessage(); var creds = new ImmutableCredentials("accessKeyId", "secretKey", "token"); ServerModeHttpClientAuthorizationHandler.AddAuthorizationHeader(request, creds, aes); if (!request.Headers.TryGetValues("Authorization", out var value)) { throw new Exception("Missing Authorization header"); } var authPayloadBase64 = value.FirstOrDefault().Split(' ')[1]; var authPayload = Encoding.UTF8.GetString(Convert.FromBase64String(authPayloadBase64)); // This should fail because the payload is encrypted. Assert.Throws<JsonReaderException>(() => JsonConvert.DeserializeObject(authPayload)); var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader(value.FirstOrDefault(), new AesEncryptionProvider(aes)); Assert.True(authResults.Succeeded); var accessKeyId = authResults.Principal.Claims.FirstOrDefault(x => string.Equals(AwsCredentialsAuthenticationHandler.ClaimAwsAccessKeyId, x.Type))?.Value; Assert.Equal(creds.AccessKey, accessKeyId); var secretKey = authResults.Principal.Claims.FirstOrDefault(x => string.Equals(AwsCredentialsAuthenticationHandler.ClaimAwsSecretKey, x.Type))?.Value; Assert.Equal(creds.SecretKey, secretKey); var token = authResults.Principal.Claims.FirstOrDefault(x => string.Equals(AwsCredentialsAuthenticationHandler.ClaimAwsSessionToken, x.Type))?.Value; Assert.Equal(creds.Token, token); } [Fact] public void AuthMissingIssueDate() { var authValue = MockAuthorizationHeaderValue("access", "secret", null, null); var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader(authValue, new NoEncryptionProvider()); Assert.False(authResults.Succeeded); Assert.Equal($"Authorization header missing {AwsCredentialsAuthenticationHandler.ClaimAwsIssueDate} property", authResults.Failure.Message); } [Fact] public void AuthExpiredIssueDate() { var authValue = MockAuthorizationHeaderValue("access", "secret", null, DateTime.UtcNow.AddMinutes(-5)); var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader(authValue, new NoEncryptionProvider()); Assert.False(authResults.Succeeded); Assert.Equal("Issue date has expired", authResults.Failure.Message); } [Fact] public void AuthFutureIssueDate() { var authValue = MockAuthorizationHeaderValue("access", "secret", null, DateTime.UtcNow.AddMinutes(5)); var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader(authValue, new NoEncryptionProvider()); Assert.False(authResults.Succeeded); Assert.Equal("Issue date invalid set in the future", authResults.Failure.Message); } [Fact] public void AuthInvalidFormatForIssueDate() { var authValue = MockAuthorizationHeaderValue("access", "secret", null, "not a date"); var authResults = AwsCredentialsAuthenticationHandler.ProcessAuthorizationHeader(authValue, new NoEncryptionProvider()); Assert.False(authResults.Succeeded); Assert.Equal("Failed to parse issue date", authResults.Failure.Message); } [Fact] public async Task AuthMissingEncryptionInfoVersion() { InMemoryInteractiveService interactiveService = new InMemoryInteractiveService(); var portNumber = 4010; var aes = Aes.Create(); aes.GenerateKey(); aes.GenerateIV(); var keyInfo = new EncryptionKeyInfo { Key = Convert.ToBase64String(aes.Key), IV = Convert.ToBase64String(aes.IV) }; var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo))); await interactiveService.StdInWriter.WriteAsync(keyInfoStdin); await interactiveService.StdInWriter.FlushAsync(); var serverCommand = new ServerModeCommand(interactiveService, portNumber, null, false); var cancelSource = new CancellationTokenSource(); Exception actualException = null; try { await serverCommand.ExecuteAsync(cancelSource.Token); } catch(InvalidEncryptionKeyInfoException e) { actualException = e; } finally { cancelSource.Cancel(); } Assert.NotNull(actualException); Assert.Equal("Missing required \"Version\" property in the symmetric key", actualException.Message); } [Fact] public async Task AuthEncryptionWithInvalidVersion() { InMemoryInteractiveService interactiveService = new InMemoryInteractiveService(); var portNumber = 4010; var aes = Aes.Create(); aes.GenerateKey(); aes.GenerateIV(); var keyInfo = new EncryptionKeyInfo { Version = "not-valid", Key = Convert.ToBase64String(aes.Key), IV = Convert.ToBase64String(aes.IV) }; var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo))); await interactiveService.StdInWriter.WriteAsync(keyInfoStdin); await interactiveService.StdInWriter.FlushAsync(); var serverCommand = new ServerModeCommand(interactiveService, portNumber, null, false); var cancelSource = new CancellationTokenSource(); Exception actualException = null; try { await serverCommand.ExecuteAsync(cancelSource.Token); } catch (InvalidEncryptionKeyInfoException e) { actualException = e; } finally { cancelSource.Cancel(); } Assert.NotNull(actualException); Assert.Equal("Unsupported symmetric key not-valid", actualException.Message); } [Fact] public void AuthMissingRequestId() { var authParameters = new Dictionary<string, string> { {"awsAccessKeyId", "accessKey" }, {"awsSecretKey", "secretKey" }, {"issueDate", DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo) } }; var results = AwsCredentialsAuthenticationHandler.ValidateAuthParameters(authParameters); Assert.False(results.Succeeded); Assert.Equal($"Authorization header missing {AwsCredentialsAuthenticationHandler.ClaimAwsRequestId} property", results.Failure.Message); } [Fact] public void AuthAttemptReplayRequestId() { var authParameters = new Dictionary<string, string> { {"awsAccessKeyId", "accessKey" }, {"awsSecretKey", "secretKey" }, {"requestId", Guid.NewGuid().ToString() }, {"issueDate", DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo) } }; var results = AwsCredentialsAuthenticationHandler.ValidateAuthParameters(authParameters); Assert.Null(results); results = AwsCredentialsAuthenticationHandler.ValidateAuthParameters(authParameters); Assert.False(results.Succeeded); Assert.Equal($"Value for authorization header has already been used", results.Failure.Message); } [Fact] public void AuthExpiredRequestIdAreClearedFromCache() { Dictionary<string, string> GenerateAuthParameters() { return new Dictionary<string, string> { {"awsAccessKeyId", "accessKey" }, {"awsSecretKey", "secretKey" }, {"requestId", Guid.NewGuid().ToString() }, {"issueDate", DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo) } }; } var request1 = GenerateAuthParameters(); AwsCredentialsAuthenticationHandler.ValidateAuthParameters(request1); Assert.Contains(request1["requestId"], AwsCredentialsAuthenticationHandler.ProcessRequestIds); var request2 = GenerateAuthParameters(); AwsCredentialsAuthenticationHandler.ValidateAuthParameters(request2); Assert.Contains(request1["requestId"], AwsCredentialsAuthenticationHandler.ProcessRequestIds); Assert.Contains(request2["requestId"], AwsCredentialsAuthenticationHandler.ProcessRequestIds); Thread.Sleep(AwsCredentialsAuthenticationHandler.MaxIssueDateDuration.Add(TimeSpan.FromSeconds(3))); var request3 = GenerateAuthParameters(); AwsCredentialsAuthenticationHandler.ValidateAuthParameters(request3); Assert.DoesNotContain(request1["requestId"], AwsCredentialsAuthenticationHandler.ProcessRequestIds); Assert.DoesNotContain(request2["requestId"], AwsCredentialsAuthenticationHandler.ProcessRequestIds); Assert.Contains(request3["requestId"], AwsCredentialsAuthenticationHandler.ProcessRequestIds); } private string MockAuthorizationHeaderValue(string accessKey, string secretKey, string sessionToken, object issueDate) { var authParameters = new Dictionary<string, string> { {AwsCredentialsAuthenticationHandler.ClaimAwsAccessKeyId, accessKey }, {AwsCredentialsAuthenticationHandler.ClaimAwsSecretKey, secretKey }, {AwsCredentialsAuthenticationHandler.ClaimAwsRequestId, Guid.NewGuid().ToString() } }; if (!string.IsNullOrEmpty(sessionToken)) { authParameters[AwsCredentialsAuthenticationHandler.ClaimAwsSessionToken] = sessionToken; } if (issueDate != null) { if(issueDate is DateTime) { authParameters[AwsCredentialsAuthenticationHandler.ClaimAwsIssueDate] = ((DateTime)issueDate).ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo); } else { authParameters[AwsCredentialsAuthenticationHandler.ClaimAwsIssueDate] = issueDate.ToString(); } } var json = Newtonsoft.Json.JsonConvert.SerializeObject(authParameters); var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); return AwsCredentialsAuthenticationHandler.SchemaName + " " + base64; } } }
375
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Linq; using System.Threading.Tasks; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.ServerMode.Controllers; using AWS.Deploy.CLI.ServerMode.Models; using AWS.Deploy.Orchestration; using Microsoft.AspNetCore.Mvc; using Xunit; using Moq; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.CLI.Utilities; using AWS.Deploy.Common; using AWS.Deploy.CLI.UnitTests.Utilities; using System.Collections.Generic; using System.IO; using AWS.Deploy.Common.Recipes; using DeploymentTypes = AWS.Deploy.CLI.ServerMode.Models.DeploymentTypes; using System; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Recipes; namespace AWS.Deploy.CLI.UnitTests { public class ServerModeTests { /// <summary> /// This test is to make sure the CLI is using at least version 5.0.0 of System.Text.Json. If we use verisons less then /// 5.0.0 types that do not have a parameterless constructor will fail to deserialize. This affects the server mode model types. /// The unit and integ test project force a newer version of System.Text.Json then would be used by default in the CLI masking the issue. /// </summary> [Fact] public void EnsureMinimumSystemTextJsonVersion() { var assembly = typeof(ServerModeCommand).Assembly; var jsonAssemblyName = assembly.GetReferencedAssemblies().FirstOrDefault(x => string.Equals("System.Text.Json", x.Name, StringComparison.OrdinalIgnoreCase)); Assert.True(jsonAssemblyName.Version >= Version.Parse("5.0.0")); } [Fact] public async Task TcpPortIsInUseTest() { var serverModeCommand1 = new ServerModeCommand(new TestToolInteractiveServiceImpl(), 1234, null, true); var serverModeCommand2 = new ServerModeCommand(new TestToolInteractiveServiceImpl(), 1234, null, true); var serverModeTask1 = serverModeCommand1.ExecuteAsync(); var serverModeTask2 = serverModeCommand2.ExecuteAsync(); await Task.WhenAny(serverModeTask1, serverModeTask2); Assert.False(serverModeTask1.IsCompleted); Assert.True(serverModeTask2.IsCompleted); Assert.True(serverModeTask2.IsFaulted); Assert.NotNull(serverModeTask2.Exception); Assert.Single(serverModeTask2.Exception.InnerExceptions); Assert.IsType<TcpPortInUseException>(serverModeTask2.Exception.InnerException); } [Theory] [InlineData("")] [InlineData("InvalidId")] public async Task RecipeController_GetRecipe_EmptyId(string recipeId) { var directoryManager = new DirectoryManager(); var fileManager = new FileManager(); var deploymentManifestEngine = new DeploymentManifestEngine(directoryManager, fileManager); var consoleInteractiveServiceImpl = new ConsoleInteractiveServiceImpl(); var consoleOrchestratorLogger = new ConsoleOrchestratorLogger(consoleInteractiveServiceImpl); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); var recipeHandler = new RecipeHandler(deploymentManifestEngine, consoleOrchestratorLogger, directoryManager, fileManager, optionSettingHandler, validatorFactory); var projectDefinitionParser = new ProjectDefinitionParser(fileManager, directoryManager); var recipeController = new RecipeController(recipeHandler, projectDefinitionParser); var response = await recipeController.GetRecipe(recipeId); Assert.IsType<BadRequestObjectResult>(response); } [Fact] public async Task RecipeController_GetRecipe_HappyPath() { var directoryManager = new DirectoryManager(); var fileManager = new FileManager(); var deploymentManifestEngine = new DeploymentManifestEngine(directoryManager, fileManager); var consoleInteractiveServiceImpl = new ConsoleInteractiveServiceImpl(); var consoleOrchestratorLogger = new ConsoleOrchestratorLogger(consoleInteractiveServiceImpl); var projectDefinitionParser = new ProjectDefinitionParser(fileManager, directoryManager); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); var recipeHandler = new RecipeHandler(deploymentManifestEngine, consoleOrchestratorLogger, directoryManager, fileManager, optionSettingHandler, validatorFactory); var recipeController = new RecipeController(recipeHandler, projectDefinitionParser); var recipeDefinitions = await recipeHandler.GetRecipeDefinitions(null); var recipe = recipeDefinitions.First(); var response = await recipeController.GetRecipe(recipe.Id); var result = Assert.IsType<OkObjectResult>(response); var resultRecipe = Assert.IsType<RecipeSummary>(result.Value); Assert.Equal(recipe.Id, resultRecipe.Id); } [Fact] public async Task RecipeController_GetRecipe_WithProjectPath() { var directoryManager = new DirectoryManager(); var fileManager = new FileManager(); var projectDefinitionParser = new ProjectDefinitionParser(fileManager, directoryManager); var deploymentManifestEngine = new Mock<IDeploymentManifestEngine>(); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); var customLocatorCalls = 0; var sourceProjectDirectory = SystemIOUtilities.ResolvePath("WebAppWithDockerFile"); deploymentManifestEngine .Setup(x => x.GetRecipeDefinitionPaths(It.IsAny<string>())) .Callback<string>((csProjectPath) => { customLocatorCalls++; Assert.Equal(new DirectoryInfo(sourceProjectDirectory).FullName, Directory.GetParent(csProjectPath).FullName); }) .ReturnsAsync(new List<string>()); var orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); var recipeHandler = new RecipeHandler(deploymentManifestEngine.Object, orchestratorInteractiveService, directoryManager, fileManager, optionSettingHandler, validatorFactory); var projectDefinition = await projectDefinitionParser.Parse(sourceProjectDirectory); var recipePaths = new HashSet<string> { RecipeLocator.FindRecipeDefinitionsPath() }; var customRecipePaths = await recipeHandler.LocateCustomRecipePaths(projectDefinition); var recipeDefinitions = await recipeHandler.GetRecipeDefinitions(recipeDefinitionPaths: recipePaths.Union(customRecipePaths).ToList()); var recipe = recipeDefinitions.First(); Assert.NotEqual(0, customLocatorCalls); customLocatorCalls = 0; var recipeController = new RecipeController(recipeHandler, projectDefinitionParser); var response = await recipeController.GetRecipe(recipe.Id, sourceProjectDirectory); Assert.NotEqual(0, customLocatorCalls); var result = Assert.IsType<OkObjectResult>(response); var resultRecipe = Assert.IsType<RecipeSummary>(result.Value); Assert.Equal(recipe.Id, resultRecipe.Id); } [Theory] [InlineData(CloudApplicationResourceType.CloudFormationStack, DeploymentTypes.CloudFormationStack)] [InlineData(CloudApplicationResourceType.BeanstalkEnvironment, DeploymentTypes.BeanstalkEnvironment)] public void ExistingDeploymentSummary_ContainsCorrectDeploymentType(CloudApplicationResourceType resourceType, DeploymentTypes expectedDeploymentType) { var existingDeploymentSummary = new ExistingDeploymentSummary( "name", "baseRecipeId", "recipeId", "recipeName", new List<CategorySummary>(), false, "shortDescription", "description", "targetService", System.DateTime.Now, true, resourceType, "uniqueId"); Assert.Equal(expectedDeploymentType, existingDeploymentSummary.DeploymentType); } [Theory] [InlineData(Deploy.Common.Recipes.DeploymentTypes.CdkProject, DeploymentTypes.CloudFormationStack)] [InlineData(Deploy.Common.Recipes.DeploymentTypes.BeanstalkEnvironment, DeploymentTypes.BeanstalkEnvironment)] public void RecommendationSummary_ContainsCorrectDeploymentType(Deploy.Common.Recipes.DeploymentTypes deploymentType, DeploymentTypes expectedDeploymentType) { var recommendationSummary = new RecommendationSummary( "baseRecipeId", "recipeId", "name", new List<CategorySummary>(), false, "shortDescription", "description", "targetService", deploymentType); Assert.Equal(expectedDeploymentType, recommendationSummary.DeploymentType); } } }
202
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using AWS.Deploy.Recipes; using Moq; using Newtonsoft.Json; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class SetOptionSettingTests { private readonly List<Recommendation> _recommendations; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly IServiceProvider _serviceProvider; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IRecipeHandler _recipeHandler; public SetOptionSettingTests() { var projectPath = SystemIOUtilities.ResolvePath("WebAppNoDockerFile"); _directoryManager = new DirectoryManager(); _fileManager = new FileManager(); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService, _directoryManager, _fileManager, optionSettingHandler, validatorFactory); var parser = new ProjectDefinitionParser(new FileManager(), _directoryManager); var awsCredentials = new Mock<AWSCredentials>(); var session = new OrchestratorSession( parser.Parse(projectPath).Result, awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; var engine = new RecommendationEngine(session, _recipeHandler); _recommendations = engine.ComputeRecommendations().GetAwaiter().GetResult(); _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); var mockServiceProvider = new Mock<IServiceProvider>(); mockServiceProvider.Setup(x => x.GetService(typeof(IDirectoryManager))).Returns(_directoryManager); mockServiceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _serviceProvider = mockServiceProvider.Object; _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider)); } [Fact] public async Task SetOptionSettingTests_DisallowedValues() { var beanstalkApplication = new List<Amazon.ElasticBeanstalk.Model.ApplicationDescription> { new Amazon.ElasticBeanstalk.Model.ApplicationDescription { ApplicationName = "WebApp1"} }; _awsResourceQueryer.Setup(x => x.ListOfElasticBeanstalkApplications(It.IsAny<string>())).ReturnsAsync(beanstalkApplication); var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var optionSetting = _optionSettingHandler.GetOptionSetting(recommendation, "BeanstalkApplication.ApplicationName"); await Assert.ThrowsAsync<ValidationFailedException>(() => _optionSettingHandler.SetOptionSettingValue(recommendation, optionSetting, "WebApp1")); } /// <summary> /// This test is to make sure no exception is throw when we set a valid value. /// The values in AllowedValues are the only values allowed to be set. /// </summary> [Fact] public async Task SetOptionSettingTests_AllowedValues() { var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var optionSetting = recommendation.Recipe.OptionSettings.First(x => x.Id.Equals("EnvironmentType")); await _optionSettingHandler.SetOptionSettingValue(recommendation, optionSetting, optionSetting.AllowedValues.First()); Assert.Equal(optionSetting.AllowedValues.First(), _optionSettingHandler.GetOptionSettingValue<string>(recommendation, optionSetting)); } /// <summary> /// This test asserts that an exception will be thrown if we set an invalid value. /// _optionSetting.ValueMapping.Values contain display values and are not /// considered valid values to be set for an option setting. Only values /// in AllowedValues can be set. Any other value will throw an exception. /// </summary> [Fact] public async Task SetOptionSettingTests_MappedValues() { var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var optionSetting = recommendation.Recipe.OptionSettings.First(x => x.Id.Equals("EnvironmentType")); await Assert.ThrowsAsync<InvalidOverrideValueException>(async () => await _optionSettingHandler.SetOptionSettingValue(recommendation, optionSetting, optionSetting.ValueMapping.Values.First())); } [Fact] public async Task SetOptionSettingTests_KeyValueType() { var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var optionSetting = recommendation.Recipe.OptionSettings.First(x => x.Id.Equals("ElasticBeanstalkEnvironmentVariables")); var values = new Dictionary<string, string>() { { "key", "value" } }; await _optionSettingHandler.SetOptionSettingValue(recommendation, optionSetting, values); Assert.Equal(values, _optionSettingHandler.GetOptionSettingValue<Dictionary<string, string>>(recommendation, optionSetting)); } [Fact] public async Task SetOptionSettingTests_KeyValueType_String() { var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var optionSetting = recommendation.Recipe.OptionSettings.First(x => x.Id.Equals("ElasticBeanstalkEnvironmentVariables")); var dictionary = new Dictionary<string, string>() { { "key", "value" } }; var dictionaryString = JsonConvert.SerializeObject(dictionary); await _optionSettingHandler.SetOptionSettingValue(recommendation, optionSetting, dictionaryString); Assert.Equal(dictionary, _optionSettingHandler.GetOptionSettingValue<Dictionary<string, string>>(recommendation, optionSetting)); } [Fact] public async Task SetOptionSettingTests_KeyValueType_Error() { var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var optionSetting = recommendation.Recipe.OptionSettings.First(x => x.Id.Equals("ElasticBeanstalkEnvironmentVariables")); await Assert.ThrowsAsync<UnsupportedOptionSettingType>(async () => await _optionSettingHandler.SetOptionSettingValue(recommendation, optionSetting, "string")); } /// <summary> /// Verifies that calling SetOptionSettingValue for Docker-related settings /// also sets the corresponding value in recommendation.DeploymentBundle /// </summary> [Fact] public async Task DeploymentBundleWriteThrough_Docker() { var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var dockerExecutionDirectory = SystemIOUtilities.ResolvePath("WebAppNoDockerFile"); var dockerBuildArgs = "arg1=val1, arg2=val2"; await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, "DockerExecutionDirectory"), dockerExecutionDirectory); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, "DockerBuildArgs"), dockerBuildArgs); Assert.Equal(dockerExecutionDirectory, recommendation.DeploymentBundle.DockerExecutionDirectory); Assert.Equal(dockerBuildArgs, recommendation.DeploymentBundle.DockerBuildArgs); } /// <summary> /// Verifies that calling SetOptionSettingValue for dotnet publish settings /// also sets the corresponding value in recommendation.DeploymentBundle /// </summary> [Fact] public async Task DeploymentBundleWriteThrough_Dotnet() { var recommendation = _recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var dotnetBuildConfiguration = "Debug"; var dotnetPublishArgs = "--force --nologo"; var selfContainedBuild = true; await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, "DotnetBuildConfiguration"), dotnetBuildConfiguration); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, "DotnetPublishArgs"), dotnetPublishArgs); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, "SelfContainedBuild"), selfContainedBuild); Assert.Equal(dotnetBuildConfiguration, recommendation.DeploymentBundle.DotnetPublishBuildConfiguration); Assert.Equal(dotnetPublishArgs, recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments); Assert.True(recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild); } } }
188
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using AWS.Deploy.CLI.Extensions; using Xunit; namespace AWS.Deploy.CLI.UnitTests { public class StringTruncateTests { [Fact] public void Truncate_MaxLengthLessThanThree_Ellipsis_Throws() { var exception = Assert.Throws<ArgumentOutOfRangeException>(() => { "Hi".Truncate(2, true); }); Assert.Equal("maxLength must be greater than three when replacing with an ellipsis. (Parameter 'maxLength')", exception.Message); } [Theory] [InlineData("Hello World", "He...")] public void Truncate_Ellipsis(string input, string expectedOutput) { var output = input.Truncate(5, true); Assert.Equal(expectedOutput, output); } [Theory] [InlineData("Hello World", "Hello")] [InlineData("Hello", "Hello")] [InlineData("", "")] public void Truncate(string input, string expectedOutput) { var output = input.Truncate(5); Assert.Equal(expectedOutput, output); } } }
41
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.IO; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Xunit; using AWS.Deploy.Orchestration.Utilities; using Moq; using System.Collections.Generic; using AWS.Deploy.CLI.TypeHintResponses; using Newtonsoft.Json; using AWS.Deploy.Orchestration; using AWS.Deploy.Common.IO; namespace AWS.Deploy.CLI.UnitTests { public class TemplateMetadataReaderTests { private readonly Mock<IDeployToolWorkspaceMetadata> _deployToolWorkspaceMetadata; private readonly Mock<IFileManager> _fileManager; public TemplateMetadataReaderTests() { _deployToolWorkspaceMetadata = new Mock<IDeployToolWorkspaceMetadata>(); _fileManager = new Mock<IFileManager>(); } [Fact] public async Task ReadJSONMetadata() { // ARRANGE var templateBody = File.ReadAllText("./TestFiles/ReadJsonTemplateMetadata.json"); var mockClient = new Mock<IAmazonCloudFormation>(); mockClient .Setup(x => x.GetTemplateAsync(It.IsAny<GetTemplateRequest>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(new GetTemplateResponse { TemplateBody = templateBody })); var templateMetadataReader = new CloudFormationTemplateReader(new TestAWSClientFactory(mockClient.Object), _deployToolWorkspaceMetadata.Object, _fileManager.Object); // ACT var metadata = await templateMetadataReader.LoadCloudApplicationMetadata(""); // ASSERT Assert.Equal("SingleInstance", metadata.Settings["EnvironmentType"].ToString()); Assert.Equal("application", metadata.Settings["LoadBalancerType"].ToString()); var applicationIAMRole = JsonConvert.DeserializeObject<IAMRoleTypeHintResponse>(metadata.Settings["ApplicationIAMRole"].ToString()); Assert.True(applicationIAMRole.CreateNew); Assert.Equal("Dockerfile", metadata.DeploymentBundleSettings["DockerfilePath"]); Assert.Equal(".", metadata.DeploymentBundleSettings["DockerExecutionDirectory"]); Assert.Equal("webappwithdockerfile", metadata.DeploymentBundleSettings["ECRRepositoryName"]); } [Fact] public async Task ReadYamlMetadata() { // ARRANGE var templateBody = File.ReadAllText("./TestFiles/ReadYamlTemplateMetadata.yml"); var mockClient = new Mock<IAmazonCloudFormation>(); mockClient .Setup(x => x.GetTemplateAsync(It.IsAny<GetTemplateRequest>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult(new GetTemplateResponse { TemplateBody = templateBody })); var templateMetadataReader = new CloudFormationTemplateReader(new TestAWSClientFactory(mockClient.Object), _deployToolWorkspaceMetadata.Object, _fileManager.Object); // ACT var metadata = await templateMetadataReader.LoadCloudApplicationMetadata(""); // ASSERT Assert.Equal("aws-elasticbeanstalk-role", metadata.Settings["ApplicationIAMRole"].ToString()); Assert.Equal("Dockerfile", metadata.DeploymentBundleSettings["DockerfilePath"]); Assert.Equal(".", metadata.DeploymentBundleSettings["DockerExecutionDirectory"]); Assert.Equal("webappwithdockerfile", metadata.DeploymentBundleSettings["ECRRepositoryName"]); } } }
90
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Linq; using Amazon.Extensions.NETCore.Setup; using Amazon.Runtime; using AWS.Deploy.Common; namespace AWS.Deploy.CLI.UnitTests { /// <summary> /// Helpful fake of <see cref="IAWSClientFactory"/>. Pass in one or more /// Mock <see cref="IAmazonService"/>s and this will handle the plumbing. /// </summary> public class TestAWSClientFactory : IAWSClientFactory { private readonly IAmazonService[] _clients; public TestAWSClientFactory(params IAmazonService[] clientMocks) { _clients = clientMocks ?? new IAmazonService[0]; } public T GetAWSClient<T>(string awsRegion = null) where T : IAmazonService { var match = _clients.OfType<T>().FirstOrDefault(); if (null == match) throw new Exception( $"Test setup exception. Somebody wanted a [{typeof(T)}] but I don't have it." + $"I have the following clients: {string.Join(",", _clients.Select(x => x.GetType().Name))}"); return match; } public void ConfigureAWSOptions(Action<AWSOptions> awsOptionsAction) => throw new NotImplementedException(); } }
40
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; namespace AWS.Deploy.CLI.UnitTests { public class TestToolInteractiveServiceImpl : IToolInteractiveService { public IList<string> DebugMessages { get; } = new List<string>(); public IList<string> OutputMessages { get; } = new List<string>(); public IList<string> ErrorMessages { get; } = new List<string>(); private IList<string> InputCommands { get; set; } public TestToolInteractiveServiceImpl(): this(new List<string>()) { } public TestToolInteractiveServiceImpl(IList<string> inputCommands) { InputCommands = inputCommands; } public void WriteLine(string message) { OutputMessages.Add(message); } public void WriteDebugLine(string message) { DebugMessages.Add(message); } public void WriteErrorLine(string message) { ErrorMessages.Add(message); } public int InputReadCounter { get; private set; } = 0; public string ReadLine() { if (InputCommands.Count <= InputReadCounter) { throw new Exception("Attempting to read more then test case said"); } var line = InputCommands[InputReadCounter]; InputReadCounter++; return line; } public bool Diagnostics { get; set; } public bool OutputContains(string subString) { foreach (var message in OutputMessages) { if (message.Contains(subString)) { return true; } } return false; } public void Write(string message) { OutputMessages.Add(message); } public void QueueConsoleInfos(params ConsoleKey[] keys) { foreach(var key in keys) { InputConsoleKeyInfos.Enqueue(new ConsoleKeyInfo(key.ToString()[0], key, false, false, false)); } } public Queue<ConsoleKeyInfo> InputConsoleKeyInfos { get; } = new Queue<ConsoleKeyInfo>(); public bool DisableInteractive { get; set; } public ConsoleKeyInfo ReadKey(bool intercept) { if(InputConsoleKeyInfos.Count == 0) { throw new Exception("No queued console key infos"); } return InputConsoleKeyInfos.Dequeue(); } } }
98
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.S3; using Amazon.S3.Model; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using Amazon.SQS; using Amazon.SQS.Model; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Data; using Moq; using Xunit; using AWS.Deploy.Common.Data; namespace AWS.Deploy.CLI.UnitTests { public class TypeHintTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public TypeHintTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task TestDynamoDBTableNameTypeHint() { var listPaginator = new Mock<IListTablesPaginator>(); listPaginator.Setup(x => x.TableNames) .Returns(new MockPaginatedEnumerable<string>(new string[] { "Table1", "Table2" })); var ddbPaginators = new Mock<IDynamoDBv2PaginatorFactory>(); ddbPaginators.Setup(x => x.ListTables(It.IsAny<ListTablesRequest>())) .Returns(listPaginator.Object); var ddbClient = new Mock<IAmazonDynamoDB>(); ddbClient.Setup(x => x.Paginators) .Returns(ddbPaginators.Object); var awsClientFactory = new Mock<IAWSClientFactory>(); awsClientFactory.Setup(x => x.GetAWSClient<IAmazonDynamoDB>(It.IsAny<string>())) .Returns(ddbClient.Object); var awsResourceQueryer = new AWSResourceQueryer(awsClientFactory.Object); var typeHintCommand = new DynamoDBTableCommand(awsResourceQueryer, null, _optionSettingHandler); var resources = await typeHintCommand.GetResources(null, null); Assert.Equal(2, resources.Rows.Count); Assert.Equal("Table1", resources.Rows[0].DisplayName); Assert.Equal("Table1", resources.Rows[0].SystemName); Assert.Equal("Table2", resources.Rows[1].DisplayName); Assert.Equal("Table2", resources.Rows[1].SystemName); } [Fact] public async Task TestSQSQueueUrlTypeHint() { var listPaginator = new Mock<IListQueuesPaginator>(); listPaginator.Setup(x => x.QueueUrls) .Returns(new MockPaginatedEnumerable<string>(new string[] { "https://sqs.us-west-2.amazonaws.com/123412341234/queue1", "https://sqs.us-west-2.amazonaws.com/123412341234/queue2" })); var sqsPaginators = new Mock<ISQSPaginatorFactory>(); sqsPaginators.Setup(x => x.ListQueues(It.IsAny<ListQueuesRequest>())) .Returns(listPaginator.Object); var sqsClient = new Mock<IAmazonSQS>(); sqsClient.Setup(x => x.Paginators) .Returns(sqsPaginators.Object); var awsClientFactory = new Mock<IAWSClientFactory>(); awsClientFactory.Setup(x => x.GetAWSClient<IAmazonSQS>(It.IsAny<string>())) .Returns(sqsClient.Object); var awsResourceQueryer = new AWSResourceQueryer(awsClientFactory.Object); var typeHintCommand = new SQSQueueUrlCommand(awsResourceQueryer, null, _optionSettingHandler); var resources = await typeHintCommand.GetResources(null, null); Assert.Equal(2, resources.Rows.Count); Assert.Equal("queue1", resources.Rows[0].DisplayName); Assert.Equal("https://sqs.us-west-2.amazonaws.com/123412341234/queue1", resources.Rows[0].SystemName); Assert.Equal("queue2", resources.Rows[1].DisplayName); Assert.Equal("https://sqs.us-west-2.amazonaws.com/123412341234/queue2", resources.Rows[1].SystemName); } [Fact] public async Task TestSNSTopicArnTypeHint() { var listPaginator = new Mock<IListTopicsPaginator>(); listPaginator.Setup(x => x.Topics) .Returns(new MockPaginatedEnumerable<Topic>(new Topic[] { new Topic { TopicArn = "arn:aws:sns:us-west-2:123412341234:Topic1" }, new Topic { TopicArn = "arn:aws:sns:us-west-2:123412341234:Topic2" } })); var snsPaginators = new Mock<ISimpleNotificationServicePaginatorFactory>(); snsPaginators.Setup(x => x.ListTopics(It.IsAny<ListTopicsRequest>())) .Returns(listPaginator.Object); var snsClient = new Mock<IAmazonSimpleNotificationService>(); snsClient.Setup(x => x.Paginators) .Returns(snsPaginators.Object); var awsClientFactory = new Mock<IAWSClientFactory>(); awsClientFactory.Setup(x => x.GetAWSClient<IAmazonSimpleNotificationService>(It.IsAny<string>())) .Returns(snsClient.Object); var awsResourceQueryer = new AWSResourceQueryer(awsClientFactory.Object); var typeHintCommand = new SNSTopicArnsCommand(awsResourceQueryer, null, _optionSettingHandler); var resources = await typeHintCommand.GetResources(null, null); Assert.Equal(2, resources.Rows.Count); Assert.Equal("Topic1", resources.Rows[0].DisplayName); Assert.Equal("arn:aws:sns:us-west-2:123412341234:Topic1", resources.Rows[0].SystemName); Assert.Equal("Topic2", resources.Rows[1].DisplayName); Assert.Equal("arn:aws:sns:us-west-2:123412341234:Topic2", resources.Rows[1].SystemName); } [Fact] public async Task TestS3BucketNameTypeHint() { var s3Client = new Mock<IAmazonS3>(); s3Client.Setup(x => x.ListBucketsAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(new ListBucketsResponse { Buckets = new List<S3Bucket> { new S3Bucket {BucketName = "Bucket1" }, new S3Bucket { BucketName = "Bucket2" } } })); var awsClientFactory = new Mock<IAWSClientFactory>(); awsClientFactory.Setup(x => x.GetAWSClient<IAmazonS3>(It.IsAny<string>())) .Returns(s3Client.Object); var awsResourceQueryer = new AWSResourceQueryer(awsClientFactory.Object); var typeHintCommand = new S3BucketNameCommand(awsResourceQueryer, null, _optionSettingHandler); var resources = await typeHintCommand.GetResources(null, null); Assert.Equal(2, resources.Rows.Count); Assert.Equal("Bucket1", resources.Rows[0].DisplayName); Assert.Equal("Bucket1", resources.Rows[0].SystemName); Assert.Equal("Bucket2", resources.Rows[1].DisplayName); Assert.Equal("Bucket2", resources.Rows[1].SystemName); } } }
158
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.EC2.Model; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Data; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests.TypeHintCommands { public class ExistingSecurityGroubsCommandTest { private readonly Mock<IAWSResourceQueryer> _mockAWSResourceQueryer; private readonly IDirectoryManager _directoryManager; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public ExistingSecurityGroubsCommandTest() { _mockAWSResourceQueryer = new Mock<IAWSResourceQueryer>(); _directoryManager = new TestDirectoryManager(); _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task GetResources() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var securityGroupsOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.SecurityGroups"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string>()); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new ExistingSecurityGroupsCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.DescribeSecurityGroups(It.IsAny<string>())) .ReturnsAsync(new List<SecurityGroup>() { new SecurityGroup() { GroupId = "group1" } }); var resources = await command.GetResources(appRunnerRecommendation, securityGroupsOptionSetting); Assert.Single(resources.Rows); Assert.Equal("group1", resources.Rows[0].DisplayName); Assert.Equal("group1", resources.Rows[0].SystemName); } [Fact] public async Task Execute() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var securityGroupsOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.SecurityGroups"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "1", "1", "3" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new ExistingSecurityGroupsCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.DescribeSecurityGroups(It.IsAny<string>())) .ReturnsAsync(new List<SecurityGroup>() { new SecurityGroup() { GroupId = "group1", GroupName = "groupName1", VpcId = "vpc1" } }); var typeHintResponse = await command.Execute(appRunnerRecommendation, securityGroupsOptionSetting); var sortedSetResponse = Assert.IsType<SortedSet<string>>(typeHintResponse); Assert.Single(sortedSetResponse); Assert.Contains("group1", sortedSetResponse); } } }
129
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.EC2.Model; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Data; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests.TypeHintCommands { public class ExistingSubnetsCommandTest { private readonly Mock<IAWSResourceQueryer> _mockAWSResourceQueryer; private readonly IDirectoryManager _directoryManager; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public ExistingSubnetsCommandTest() { _mockAWSResourceQueryer = new Mock<IAWSResourceQueryer>(); _directoryManager = new TestDirectoryManager(); _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task GetResources() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var subnetsOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.Subnets"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string>()); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new ExistingSubnetsCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.DescribeSubnets(It.IsAny<string>())) .ReturnsAsync(new List<Subnet>() { new Subnet() { SubnetId = "subnet1" } }); var resources = await command.GetResources(appRunnerRecommendation, subnetsOptionSetting); Assert.Single(resources.Rows); Assert.Equal("subnet1", resources.Rows[0].DisplayName); Assert.Equal("subnet1", resources.Rows[0].SystemName); } [Fact] public async Task Execute() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var subnetsOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector.Subnets"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "1", "1", "3" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new ExistingSubnetsCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.DescribeSubnets(It.IsAny<string>())) .ReturnsAsync(new List<Subnet>() { new Subnet() { SubnetId = "subnet1", VpcId = "vpc1", AvailabilityZone = "us-west-2" } }); var typeHintResponse = await command.Execute(appRunnerRecommendation, subnetsOptionSetting); var sortedSetResponse = Assert.IsType<SortedSet<string>>(typeHintResponse); Assert.Single(sortedSetResponse); Assert.Contains("subnet1", sortedSetResponse); } } }
129
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.EC2.Model; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Data; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests.TypeHintCommands { public class ExistingVpcCommandTest { private readonly Mock<IAWSResourceQueryer> _mockAWSResourceQueryer; private readonly IDirectoryManager _directoryManager; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IServiceProvider> _serviceProvider; public ExistingVpcCommandTest() { _mockAWSResourceQueryer = new Mock<IAWSResourceQueryer>(); _directoryManager = new TestDirectoryManager(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_mockAWSResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task GetResources() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppNoDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var vpcOptionSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "VPC.VpcId"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string>()); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new ExistingVpcCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.GetListOfVpcs()) .ReturnsAsync(new List<Vpc>() { new Vpc() { VpcId = "vpc1" } }); var resources = await command.GetResources(beanstalkRecommendation, vpcOptionSetting); Assert.Single(resources.Rows); Assert.Equal("vpc1", resources.Rows[0].DisplayName); Assert.Equal("vpc1", resources.Rows[0].SystemName); } [Fact] public async Task Execute() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppNoDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var vpcOptionSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "VPC.VpcId"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "2" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new ExistingVpcCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.GetListOfVpcs()) .ReturnsAsync(new List<Vpc>() { new Vpc() { VpcId = "vpc1" } }); var typeHintResponse = await command.Execute(beanstalkRecommendation, vpcOptionSetting); var stringResponse = Assert.IsType<string>(typeHintResponse); Assert.Equal("vpc1", stringResponse); } } }
122
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.EC2.Model; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Constants; using AWS.Deploy.Orchestration; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests.TypeHintCommands { public class InstanceTypeCommandTest { private readonly Mock<IAWSResourceQueryer> _mockAWSResourceQueryer; private readonly IDirectoryManager _directoryManager; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; public InstanceTypeCommandTest() { _mockAWSResourceQueryer = new Mock<IAWSResourceQueryer>(); _directoryManager = new TestDirectoryManager(); _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task WindowsGetResources() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_WINDOWS_RECIPE_ID); var instanceTypeSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "InstanceType"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string>()); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new WindowsInstanceTypeCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.ListOfAvailableInstanceTypes()) .ReturnsAsync(new List<InstanceTypeInfo>() { new InstanceTypeInfo() { InstanceType = "t1.any", ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64, EC2.FILTER_ARCHITECTURE_ARM64 } } }, new InstanceTypeInfo() { InstanceType = "t1.x86_64", ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64 } } }, new InstanceTypeInfo() { InstanceType = "t1.arm64", ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_ARM64 } } }, }); var resources = await command.GetResources(beanstalkRecommendation, instanceTypeSetting); Assert.Contains(resources.Rows, x => string.Equals("t1.any", x.SystemName, StringComparison.OrdinalIgnoreCase)); Assert.Contains(resources.Rows, x => string.Equals("t1.x86_64", x.SystemName, StringComparison.OrdinalIgnoreCase)); Assert.DoesNotContain(resources.Rows, x => string.Equals("t1.arm64", x.SystemName, StringComparison.OrdinalIgnoreCase)); } [Fact] public async Task LinuxGetResources() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var instanceTypeSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "InstanceType"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string>()); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new LinuxInstanceTypeCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.ListOfAvailableInstanceTypes()) .ReturnsAsync(new List<InstanceTypeInfo>() { new InstanceTypeInfo() { InstanceType = "t1.any", ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64, EC2.FILTER_ARCHITECTURE_ARM64 } } }, new InstanceTypeInfo() { InstanceType = "t1.x86_64", ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64 } } }, new InstanceTypeInfo() { InstanceType = "t1.arm64", ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_ARM64 } } }, }); var resources = await command.GetResources(beanstalkRecommendation, instanceTypeSetting); Assert.Contains(resources.Rows, x => string.Equals("t1.any", x.SystemName, StringComparison.OrdinalIgnoreCase)); Assert.Contains(resources.Rows, x => string.Equals("t1.x86_64", x.SystemName, StringComparison.OrdinalIgnoreCase)); Assert.Contains(resources.Rows, x => string.Equals("t1.arm64", x.SystemName, StringComparison.OrdinalIgnoreCase)); } [Fact] public async Task WindowsExecute() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_WINDOWS_RECIPE_ID); var instanceTypeSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "InstanceType"); _mockAWSResourceQueryer .Setup(x => x.ListOfAvailableInstanceTypes()) .ReturnsAsync(new List<InstanceTypeInfo>() { new InstanceTypeInfo() { InstanceType = "t1.any", FreeTierEligible = true, VCpuInfo = new VCpuInfo { DefaultCores = 1, }, MemoryInfo = new MemoryInfo { SizeInMiB = 1000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64, EC2.FILTER_ARCHITECTURE_ARM64 } } }, new InstanceTypeInfo() { InstanceType = "t1.x86_64", FreeTierEligible = true, VCpuInfo = new VCpuInfo { DefaultCores = 2, }, MemoryInfo = new MemoryInfo { SizeInMiB = 2000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64 } } }, new InstanceTypeInfo() { InstanceType = "t1.x86_64v2", FreeTierEligible = true, VCpuInfo = new VCpuInfo { DefaultCores = 2, }, MemoryInfo = new MemoryInfo { SizeInMiB = 3000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64 } } }, new InstanceTypeInfo() { InstanceType = "t1.arm64", FreeTierEligible = false, VCpuInfo = new VCpuInfo { DefaultCores = 3, }, MemoryInfo = new MemoryInfo { SizeInMiB = 2000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_ARM64 } } }, }); // Default options { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "y", // Free tier "1", // CPU "1", // Memory "1" // Instance type }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new WindowsInstanceTypeCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); var typeHintResponse = await command.Execute(beanstalkRecommendation, instanceTypeSetting); Assert.Contains("t1.any", typeHintResponse.ToString()); } // Select instance type with 2 cores and 3000 of memory { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "y", // Free tier "2", // CPU "2", // Memory "1" // Instance type }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new WindowsInstanceTypeCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); var typeHintResponse = await command.Execute(beanstalkRecommendation, instanceTypeSetting); Assert.Contains("t1.x86_64v2", typeHintResponse.ToString()); } } [Fact] public async Task LinuxExecute() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var instanceTypeSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "InstanceType"); _mockAWSResourceQueryer .Setup(x => x.ListOfAvailableInstanceTypes()) .ReturnsAsync(new List<InstanceTypeInfo>() { new InstanceTypeInfo() { InstanceType = "t1.any", FreeTierEligible = true, VCpuInfo = new VCpuInfo { DefaultCores = 1, }, MemoryInfo = new MemoryInfo { SizeInMiB = 1000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64, EC2.FILTER_ARCHITECTURE_ARM64 } } }, new InstanceTypeInfo() { InstanceType = "t1.x86_64", FreeTierEligible = true, VCpuInfo = new VCpuInfo { DefaultCores = 2, }, MemoryInfo = new MemoryInfo { SizeInMiB = 2000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64 } } }, new InstanceTypeInfo() { InstanceType = "t1.x86_64v2", FreeTierEligible = true, VCpuInfo = new VCpuInfo { DefaultCores = 2, }, MemoryInfo = new MemoryInfo { SizeInMiB = 3000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_X86_64 } } }, new InstanceTypeInfo() { InstanceType = "t1.arm64", FreeTierEligible = true, VCpuInfo = new VCpuInfo { DefaultCores = 3, }, MemoryInfo = new MemoryInfo { SizeInMiB = 2000 }, ProcessorInfo = new ProcessorInfo() { SupportedArchitectures = new List<string>{ EC2.FILTER_ARCHITECTURE_ARM64 } } }, }); // Default options { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "y", // Free tier "1", // Architecture x86_64 "1", // CPU "1", // Memory "1" // Instance type }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new LinuxInstanceTypeCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); var typeHintResponse = await command.Execute(beanstalkRecommendation, instanceTypeSetting); Assert.Contains("t1.any", typeHintResponse.ToString()); } // Select instance type with ARM CPU 3 cores and 2000 of memory { var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "y", // Free tier "2", // Architecture arm64 "2", // CPU "1", // Memory "1" // Instance type }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new LinuxInstanceTypeCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _optionSettingHandler); var typeHintResponse = await command.Execute(beanstalkRecommendation, instanceTypeSetting); Assert.Contains("t1.arm64", typeHintResponse.ToString()); } } [Fact] public async Task WindowsValidate() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_WINDOWS_RECIPE_ID); var instanceTypeSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "InstanceType"); _mockAWSResourceQueryer .Setup(x => x.DescribeInstanceType(It.IsAny<string>())) .ReturnsAsync((string type) => { if (type == "t1.x86_64") { return new InstanceTypeInfo { ProcessorInfo = new ProcessorInfo { SupportedArchitectures = new List<string> { "x86_64" } } }; } if (type == "t1.arm64") { return new InstanceTypeInfo { ProcessorInfo = new ProcessorInfo { SupportedArchitectures = new List<string> { EC2.FILTER_ARCHITECTURE_ARM64 } } }; } if (type == "t1.both") { return new InstanceTypeInfo { ProcessorInfo = new ProcessorInfo { SupportedArchitectures = new List<string> { "x86_64", EC2.FILTER_ARCHITECTURE_ARM64 } } }; } return null; }); var validator = new WindowsInstanceTypeValidator(_mockAWSResourceQueryer.Object); Assert.True(validator.Validate("t1.x86_64", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); Assert.False(validator.Validate("t1.arm64", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); Assert.True(validator.Validate("t1.both", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); Assert.False(validator.Validate("t1.fake", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); } [Fact] public async Task LinuxValidate() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var beanstalkRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_BEANSTALK_LINUX_RECIPE_ID); var instanceTypeSetting = _optionSettingHandler.GetOptionSetting(beanstalkRecommendation, "InstanceType"); _mockAWSResourceQueryer .Setup(x => x.DescribeInstanceType(It.IsAny<string>())) .ReturnsAsync((string type) => { if (type == "t1.x86_64") { return new InstanceTypeInfo { ProcessorInfo = new ProcessorInfo { SupportedArchitectures = new List<string> { "x86_64" } } }; } if (type == "t1.arm64") { return new InstanceTypeInfo { ProcessorInfo = new ProcessorInfo { SupportedArchitectures = new List<string> { EC2.FILTER_ARCHITECTURE_ARM64 } } }; } if (type == "t1.both") { return new InstanceTypeInfo { ProcessorInfo = new ProcessorInfo { SupportedArchitectures = new List<string> { "x86_64", EC2.FILTER_ARCHITECTURE_ARM64 } } }; } return null; }); var validator = new LinuxInstanceTypeValidator(_mockAWSResourceQueryer.Object); Assert.True(validator.Validate("t1.x86_64", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); Assert.True(validator.Validate("t1.arm64", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); Assert.True(validator.Validate("t1.both", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); Assert.False(validator.Validate("t1.fake", beanstalkRecommendation, instanceTypeSetting).Result.IsValid); } } }
548
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.AppRunner.Model; using Amazon.EC2.Model; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.CLI.TypeHintResponses; using AWS.Deploy.CLI.UnitTests.Utilities; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Data; using Moq; using Xunit; namespace AWS.Deploy.CLI.UnitTests.TypeHintCommands { public class VPCConnectorCommandTest { private readonly Mock<IAWSResourceQueryer> _mockAWSResourceQueryer; private readonly IDirectoryManager _directoryManager; private readonly IToolInteractiveService _toolInteractiveService; private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IServiceProvider> _serviceProvider; public VPCConnectorCommandTest() { _mockAWSResourceQueryer = new Mock<IAWSResourceQueryer>(); _directoryManager = new TestDirectoryManager(); _toolInteractiveService = new TestToolInteractiveServiceImpl(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_mockAWSResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task GetResources() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var vpcConnectorOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string>()); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new VPCConnectorCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _toolInteractiveService, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.DescribeAppRunnerVpcConnectors()) .ReturnsAsync(new List<VpcConnector>() { new VpcConnector() { VpcConnectorArn = "arn:aws:apprunner:us-west-2:123456789010:vpcconnector/fakeVpcConnector", VpcConnectorName = "vpcConnectorName" } }); var resources = await command.GetResources(appRunnerRecommendation, vpcConnectorOptionSetting); Assert.Single(resources.Rows); Assert.Equal("vpcConnectorName", resources.Rows[0].DisplayName); Assert.Equal("arn:aws:apprunner:us-west-2:123456789010:vpcconnector/fakeVpcConnector", resources.Rows[0].SystemName); } [Fact] public async Task Execute_ExistingVPCConnector() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var vpcConnectorOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "y", "n", "1" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new VPCConnectorCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _toolInteractiveService, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.DescribeAppRunnerVpcConnectors()) .ReturnsAsync(new List<VpcConnector>() { new VpcConnector() { VpcConnectorArn = "arn:aws:apprunner:us-west-2:123456789010:vpcconnector/fakeVpcConnector", VpcConnectorName = "vpcConnectorName" } }); var typeHintResponse = await command.Execute(appRunnerRecommendation, vpcConnectorOptionSetting); var vpcConnectorTypeHintResponse = Assert.IsType<VPCConnectorTypeHintResponse>(typeHintResponse); Assert.False(vpcConnectorTypeHintResponse.CreateNew); Assert.Equal("arn:aws:apprunner:us-west-2:123456789010:vpcconnector/fakeVpcConnector", vpcConnectorTypeHintResponse.VpcConnectorId); Assert.Empty(vpcConnectorTypeHintResponse.Subnets); Assert.Empty(vpcConnectorTypeHintResponse.SecurityGroups); } [Fact] public async Task Execute_NewVPCConnector() { var engine = await HelperFunctions.BuildRecommendationEngine( "WebAppWithDockerFile", new FileManager(), new DirectoryManager(), "us-west-2", "123456789012", "default" ); var recommendations = await engine.ComputeRecommendations(); var appRunnerRecommendation = recommendations.First(r => r.Recipe.Id == Constants.ASPNET_CORE_APPRUNNER_ID); var vpcConnectorOptionSetting = _optionSettingHandler.GetOptionSetting(appRunnerRecommendation, "VPCConnector"); var interactiveServices = new TestToolInteractiveServiceImpl(new List<string> { "y", "y", "n", "1", "1", "1", "3", "1", "1", "3" }); var consoleUtilities = new ConsoleUtilities(interactiveServices, _directoryManager, _optionSettingHandler); var command = new VPCConnectorCommand(_mockAWSResourceQueryer.Object, consoleUtilities, _toolInteractiveService, _optionSettingHandler); _mockAWSResourceQueryer .Setup(x => x.DescribeAppRunnerVpcConnectors()) .ReturnsAsync(new List<VpcConnector>() { new VpcConnector() { VpcConnectorArn = "arn:aws:apprunner:us-west-2:123456789010:vpcconnector/fakeVpcConnector" } }); _mockAWSResourceQueryer .Setup(x => x.GetListOfVpcs()) .ReturnsAsync(new List<Vpc>() { new Vpc() { VpcId = "vpc1" } }); _mockAWSResourceQueryer .Setup(x => x.DescribeSubnets("vpc1")) .ReturnsAsync(new List<Subnet>() { new Subnet() { SubnetId = "subnet1", VpcId = "vpc1", AvailabilityZone = "us-west-2" } }); _mockAWSResourceQueryer .Setup(x => x.DescribeSecurityGroups("vpc1")) .ReturnsAsync(new List<SecurityGroup>() { new SecurityGroup() { GroupId = "group1", GroupName = "groupName1", VpcId = "vpc1" } }); var typeHintResponse = await command.Execute(appRunnerRecommendation, vpcConnectorOptionSetting); var vpcConnectorTypeHintResponse = Assert.IsType<VPCConnectorTypeHintResponse>(typeHintResponse); Assert.True(vpcConnectorTypeHintResponse.CreateNew); Assert.Null(vpcConnectorTypeHintResponse.VpcConnectorId); Assert.Single(vpcConnectorTypeHintResponse.Subnets); Assert.Contains("subnet1", vpcConnectorTypeHintResponse.Subnets); Assert.Single(vpcConnectorTypeHintResponse.SecurityGroups); Assert.Contains("group1", vpcConnectorTypeHintResponse.SecurityGroups); } } }
222
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.Common; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.RecommendationEngine; using AWS.Deploy.Recipes; using Moq; namespace AWS.Deploy.CLI.UnitTests.Utilities { public class HelperFunctions { public static async Task<RecommendationEngine> BuildRecommendationEngine( string testProjectName, IFileManager fileManager, IDirectoryManager directoryManager, string awsRegion, string awsAccountId, string awsProfile) { var fullPath = SystemIOUtilities.ResolvePath(testProjectName); var deploymentManifestEngine = new DeploymentManifestEngine(directoryManager, fileManager); var orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); var recipeHandler = new RecipeHandler(deploymentManifestEngine, orchestratorInteractiveService, directoryManager, fileManager, optionSettingHandler, validatorFactory); var parser = new ProjectDefinitionParser(fileManager, directoryManager); var awsCredentials = new Mock<AWSCredentials>(); var session = new OrchestratorSession( await parser.Parse(fullPath), awsCredentials.Object, awsRegion, awsAccountId) { AWSProfileName = awsProfile }; return new RecommendationEngine(session, recipeHandler); } } }
52
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace AWS.Deploy.CLI.UnitTests.Utilities { public class MockPaginatedEnumerable<T> : IPaginatedEnumerable<T> { readonly T[] _data; public MockPaginatedEnumerable(T[] data) { _data = data; } public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new MockAsyncEnumerator(_data); } class MockAsyncEnumerator : IAsyncEnumerator<T> { readonly T[] _data; int _position; public MockAsyncEnumerator(T[] data) { _data = data; } public T Current => _data[_position - 1]; public ValueTask DisposeAsync() => new ValueTask(Task.CompletedTask); public ValueTask<bool> MoveNextAsync() { _position++; return new ValueTask<bool>(_position <= _data.Length); } } } }
47
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Reflection; namespace AWS.Deploy.CLI.UnitTests.Utilities { internal static class SystemIOUtilities { public static string ResolvePath(string projectName) { var testsPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); while (testsPath != null && !string.Equals(new DirectoryInfo(testsPath).Name, "test", StringComparison.OrdinalIgnoreCase)) { testsPath = Directory.GetParent(testsPath).FullName; } return Path.Combine(testsPath, "..", "testapps", projectName); } public static string ResolvePathToSolution() { var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); while (path != null && !string.Equals(new DirectoryInfo(path).Name, "aws-dotnet-deploy", StringComparison.OrdinalIgnoreCase)) { path = Directory.GetParent(path).FullName; } return new DirectoryInfo(Path.Combine(path, "AWS.Deploy.sln")).FullName; } } }
36
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.AppRunner.Model; using Amazon.CloudControlApi.Model; using Amazon.CloudFormation.Model; using Amazon.CloudFront.Model; using Amazon.CloudWatchEvents.Model; using Amazon.EC2.Model; using Amazon.ECR.Model; using Amazon.ElasticBeanstalk.Model; using Amazon.ElasticLoadBalancingV2; using Amazon.IdentityManagement.Model; using Amazon.Runtime; using Amazon.S3; using Amazon.SecurityToken.Model; using AWS.Deploy.Common.Data; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.CLI.UnitTests.Utilities { public class TestToolAWSResourceQueryer : IAWSResourceQueryer { public Task<Amazon.AppRunner.Model.Service> DescribeAppRunnerService(string serviceArn) => throw new NotImplementedException(); public Task<string> CreateEC2KeyPair(string keyName, string saveLocation) => throw new NotImplementedException(); public Task<Repository> CreateECRRepository(string repositoryName) => throw new NotImplementedException(); public Task<List<Stack>> GetCloudFormationStacks() => throw new NotImplementedException(); public Task<Stack> GetCloudFormationStack(string stackName) => throw new NotImplementedException(); public Task<List<AuthorizationData>> GetECRAuthorizationToken() { var authorizationData = new AuthorizationData { // Test authorization token is encoded dummy 'username:password' string AuthorizationToken = "dXNlcm5hbWU6cGFzc3dvcmQ=", ProxyEndpoint = "endpoint" }; return Task.FromResult<List<AuthorizationData>>(new List<AuthorizationData>(){ authorizationData }); } public Task<List<Repository>> GetECRRepositories(List<string> repositoryNames) { if (repositoryNames.Count == 0) return Task.FromResult<List<Repository>>(new List<Repository>() { }); var repository = new Repository { RepositoryName = repositoryNames[0] }; return Task.FromResult<List<Repository>>(new List<Repository>() { repository }); } public Task<PlatformSummary> GetLatestElasticBeanstalkPlatformArn(BeanstalkPlatformType platformType) { return Task.FromResult(new PlatformSummary() { PlatformArn = string.Empty }); } public Task<List<PlatformSummary>> GetElasticBeanstalkPlatformArns(params BeanstalkPlatformType[] platformTypes) => throw new NotImplementedException(); public Task<List<Vpc>> GetListOfVpcs() => throw new NotImplementedException(); public Task<List<KeyPairInfo>> ListOfEC2KeyPairs() => throw new NotImplementedException(); public Task<List<Amazon.ECS.Model.Cluster>> ListOfECSClusters(string ecsClusterName) => throw new NotImplementedException(); public Task<List<ApplicationDescription>> ListOfElasticBeanstalkApplications(string applicationName) => throw new NotImplementedException(); public Task<List<EnvironmentDescription>> ListOfElasticBeanstalkEnvironments(string applicationName, string environmentName) => throw new NotImplementedException(); public Task<List<Role>> ListOfIAMRoles(string servicePrincipal) => throw new NotImplementedException(); public Task<List<StackResource>> DescribeCloudFormationResources(string stackName) => throw new NotImplementedException(); public Task<EnvironmentDescription> DescribeElasticBeanstalkEnvironment(string environmentId) => throw new NotImplementedException(); public Task<Amazon.ElasticLoadBalancingV2.Model.LoadBalancer> DescribeElasticLoadBalancer(string loadBalancerArn) => throw new NotImplementedException(); public Task<S3Region> GetS3BucketLocation(string bucketName) => throw new NotImplementedException(); public Task<Amazon.S3.Model.WebsiteConfiguration> GetS3BucketWebSiteConfiguration(string bucketName) => throw new NotImplementedException(); public Task<List<Amazon.ElasticLoadBalancingV2.Model.Listener>> DescribeElasticLoadBalancerListeners(string loadBalancerArn) => throw new NotImplementedException(); public Task<DescribeRuleResponse> DescribeCloudWatchRule(string ruleName) => throw new NotImplementedException(); Task<string> IAWSResourceQueryer.GetS3BucketLocation(string bucketName) => throw new NotImplementedException(); public Task<List<Amazon.ElasticLoadBalancingV2.Model.LoadBalancer>> ListOfLoadBalancers(LoadBalancerTypeEnum loadBalancerType) => throw new NotImplementedException(); public Task<Distribution> GetCloudFrontDistribution(string distributionId) => throw new NotImplementedException(); public Task<List<string>> ListOfDyanmoDBTables() => throw new NotImplementedException(); public Task<List<string>> ListOfSQSQueuesUrls() => throw new NotImplementedException(); public Task<List<string>> ListOfSNSTopicArns() => throw new NotImplementedException(); public Task<List<Amazon.S3.Model.S3Bucket>> ListOfS3Buckets() => throw new NotImplementedException(); public Task<List<InstanceTypeInfo>> ListOfAvailableInstanceTypes() => throw new NotImplementedException(); public Task<InstanceTypeInfo> DescribeInstanceType(string instanceType) => throw new NotImplementedException(); public Task<List<StackEvent>> GetCloudFormationStackEvents(string stackName) => throw new NotImplementedException(); public Task<List<Amazon.ElasticBeanstalk.Model.Tag>> ListElasticBeanstalkResourceTags(string resourceArn) => throw new NotImplementedException(); public Task<List<ConfigurationOptionSetting>> GetBeanstalkEnvironmentConfigurationSettings(string environmentId) => throw new NotImplementedException(); public Task<GetCallerIdentityResponse> GetCallerIdentity(string awsRegion) => throw new NotImplementedException(); public Task<Repository> DescribeECRRepository(string respositoryName) => throw new NotImplementedException(); public Task<List<VpcConnector>> DescribeAppRunnerVpcConnectors() => throw new NotImplementedException(); public Task<List<Subnet>> DescribeSubnets(string vpcID = null) => throw new NotImplementedException(); public Task<List<SecurityGroup>> DescribeSecurityGroups(string vpcID = null) => throw new NotImplementedException(); public Task<string> GetParameterStoreTextValue(string parameterName) => throw new NotImplementedException(); public Task<ResourceDescription> GetCloudControlApiResource(string type, string identifier) => throw new NotImplementedException(); public Task<Vpc> GetDefaultVpc() => throw new NotImplementedException(); } }
100
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.CLI.UnitTests.Utilities { /// <summary> /// The container that represents a command to be executed by <see cref="TestToolCommandLineWrapper.Run(string, string, bool, Action{TryRunResult}, CancellationToken)"/> /// </summary> public class CommandLineRunObject { /// <summary> /// The command to be executed via the command line wrapper. /// </summary> public string Command { get; set; } /// <summary> /// The working directory from which the command will be executed. /// </summary> public string WorkingDirectory { get; set; } /// <summary> /// Specifies whether to stream the output of the command execution to the interactive service. /// </summary> public bool StreamOutputToInteractiveService { get; set; } /// <summary> /// The action to run upon the completion of the command execution. /// </summary> public Action<TryRunResult> OnCompleteAction { get; set; } /// <summary> /// Specifies whether to redirect standard input, output and error. /// </summary> public bool RedirectIO { get; set; } /// <summary> /// Specifies the input that should be piped into standard input for the process. /// </summary> public string Stdin { get; set; } /// <summary> /// The cancellation token for the async task. /// </summary> public CancellationToken CancelToken { get; set; } } public class TestToolCommandLineWrapper : ICommandLineWrapper { public List<CommandLineRunObject> CommandsToExecute = new List<CommandLineRunObject>(); public Task Run( string command, string workingDirectory = "", bool streamOutputToInteractiveService = true, Action<TryRunResult> onComplete = null, bool redirectIO = true, string stdin = null, IDictionary<string, string> environmentVariables = null, CancellationToken cancelToken = default, bool needAwsCredentials = false) { CommandsToExecute.Add(new CommandLineRunObject { Command = command, WorkingDirectory = workingDirectory, StreamOutputToInteractiveService = streamOutputToInteractiveService, OnCompleteAction = onComplete, RedirectIO = redirectIO, Stdin = stdin, CancelToken = cancelToken }); return Task.CompletedTask; } public void ConfigureProcess(Action<ProcessStartInfo> processStartInfoAction) => throw new NotImplementedException(); } }
86
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using AWS.Deploy.Orchestration; namespace AWS.Deploy.CLI.UnitTests.Utilities { public class TestToolOrchestratorInteractiveService : IOrchestratorInteractiveService { public IList<string> SectionStartMessages { get; } = new List<string>(); public IList<string> DebugMessages { get; } = new List<string>(); public IList<string> OutputMessages { get; } = new List<string>(); public IList<string> ErrorMessages { get; } = new List<string>(); public void LogSectionStart(string message, string description) => SectionStartMessages.Add(message); public void LogDebugMessage(string message) => DebugMessages.Add(message); public void LogErrorMessage(string message) => ErrorMessages.Add(message); public void LogInfoMessage(string message) => OutputMessages.Add(message); } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Threading.Tasks; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.CLI.UnitTests.Utilities { public class TestZipFileManager : IZipFileManager { public readonly List<string> CreatedZipFiles = new List<string>(); public Task CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) { CreatedZipFiles.Add(destinationArchiveFileName); return Task.CompletedTask; } } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.DocGenerator.Generators; using AWS.Deploy.DocGenerator.UnitTests.Utilities; using AWS.Deploy.ServerMode.Client; using Moq; using Xunit; namespace AWS.Deploy.DocGenerator.UnitTests { public class DeploymentSettingsFileGeneratorTests { private readonly Mock<IRestAPIClient> _restClient; private readonly TestFileManager _fileManager; public DeploymentSettingsFileGeneratorTests() { _restClient = new Mock<IRestAPIClient>(); _fileManager = new TestFileManager(); } /// <summary> /// Checks if the generated documentation file is producing the same output as a local copy. /// </summary> [Fact] public async Task GenerateTest() { var recipeSummary = new RecipeSummary { Id = "AspNetAppAppRunner", Name = "ASP.NET Core App to AWS App Runner", Description = "This ASP.NET Core application will be built as a container image on Linux and deployed to AWS App Runner," + " a fully managed service for web applications and APIs." + " If your project does not contain a Dockerfile, it will be automatically generated," + " otherwise an existing Dockerfile will be used. " + "Recommended if you want to deploy your web application as a Linux container image on a fully managed environment." }; var recipeOptionSettingSummary1 = new RecipeOptionSettingSummary { Id = "ServiceName", Name = "Service Name", Description = "The name of the AWS App Runner service.", Type = "String", Settings = new List<RecipeOptionSettingSummary>() }; var recipeOptionSettingSummary2 = new RecipeOptionSettingSummary { Id = "ApplicationIAMRole", Name = "Application IAM Role", Description = "The Identity and Access Management (IAM) role that provides AWS credentials to the application to access AWS services.", Type = "Object", Settings = new List<RecipeOptionSettingSummary> { new RecipeOptionSettingSummary { Id = "CreateNew", Name = "Create New Role", Description = "Do you want to create a new role?", Type = "Bool", Settings = new List<RecipeOptionSettingSummary>() } } }; _restClient.Setup(x => x.ListAllRecipesAsync(It.IsAny<string?>())).ReturnsAsync(new ListAllRecipesOutput { Recipes = new List<RecipeSummary> { recipeSummary } }); _restClient.Setup(x => x.GetRecipeOptionSettingsAsync(It.IsAny<string>(), It.IsAny<string?>())).ReturnsAsync(new List<RecipeOptionSettingSummary> { recipeOptionSettingSummary1, recipeOptionSettingSummary2 }); var deploymentSettingsFileGenerator = new DeploymentSettingsFileGenerator(_restClient.Object, _fileManager); await deploymentSettingsFileGenerator.Generate(); var filePath = _fileManager.InMemoryStore.Keys.First(); var actualResult = _fileManager.InMemoryStore[filePath]; Assert.Equal(File.ReadAllText("./DeploymentSettingsFiles/AspNetAppAppRunner.md"), actualResult); } } }
78
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.Common.IO; namespace AWS.Deploy.DocGenerator.UnitTests.Utilities { public class TestFileManager : IFileManager { public readonly Dictionary<string, string> InMemoryStore = new Dictionary<string, string>(); public bool Exists(string path) => throw new NotImplementedException(); public bool Exists(string path, string directory) => throw new NotImplementedException(); public string GetExtension(string filePath) => throw new NotImplementedException(); public long GetSizeInBytes(string filePath) => throw new NotImplementedException(); public bool IsFileValidPath(string filePath) => throw new NotImplementedException(); public FileStream OpenRead(string filePath) => throw new NotImplementedException(); public Task<string[]> ReadAllLinesAsync(string path) => throw new NotImplementedException(); public Task<string> ReadAllTextAsync(string path) => throw new NotImplementedException(); public Task WriteAllTextAsync(string filePath, string contents, CancellationToken cancellationToken = default) { InMemoryStore[filePath] = contents; return Task.CompletedTask; } } }
28
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Amazon.EC2; using Amazon.EC2.Model; using Amazon.ElasticBeanstalk.Model; using Amazon.Runtime; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using AWS.Deploy.Common; using AWS.Deploy.Orchestration.Data; using Moq; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests { public class AWSResourceQueryerTests { private readonly Mock<IAWSClientFactory> _mockAWSClientFactory; private readonly Mock<IAmazonSecurityTokenService> _mockSTSClient; private readonly Mock<IAmazonSecurityTokenService> _mockSTSClientDefaultRegion; private readonly Mock<IAmazonEC2> _mockEC2Client; public AWSResourceQueryerTests() { _mockAWSClientFactory = new Mock<IAWSClientFactory>(); _mockSTSClient = new Mock<IAmazonSecurityTokenService>(); _mockSTSClientDefaultRegion = new Mock<IAmazonSecurityTokenService>(); _mockEC2Client = new Mock<IAmazonEC2>(); } [Fact] public async Task GetDefaultVPC_UnauthorizedAccess() { var awsResourceQueryer = new AWSResourceQueryer(_mockAWSClientFactory.Object); var vpcResponse = new DescribeVpcsResponse(); var unauthorizedException = new AmazonServiceException("You are not authorized to perform this operation.") { ErrorCode = "UnauthorizedOperation" }; _mockAWSClientFactory.Setup(x => x.GetAWSClient<IAmazonEC2>(It.IsAny<string>())).Returns(_mockEC2Client.Object); _mockEC2Client.Setup(x => x.Paginators.DescribeVpcs(It.IsAny<DescribeVpcsRequest>())).Throws(unauthorizedException); var exceptionThrown = await Assert.ThrowsAsync<ResourceQueryException>(awsResourceQueryer.GetDefaultVpc); Assert.Equal(DeployToolErrorCode.ResourceQuery, exceptionThrown.ErrorCode); Assert.Contains("Error attempting to retrieve the default VPC (UnauthorizedOperation).", exceptionThrown.Message); } [Fact] public async Task GetCallerIdentity_HasRegionAccess() { var awsResourceQueryer = new AWSResourceQueryer(_mockAWSClientFactory.Object); var stsResponse = new GetCallerIdentityResponse(); _mockAWSClientFactory.Setup(x => x.GetAWSClient<IAmazonSecurityTokenService>("ap-southeast-3")).Returns(_mockSTSClient.Object); _mockSTSClient.Setup(x => x.GetCallerIdentityAsync(It.IsAny<GetCallerIdentityRequest>(), It.IsAny<CancellationToken>())).ReturnsAsync(stsResponse); await awsResourceQueryer.GetCallerIdentity("ap-southeast-3"); } [Fact] public async Task GetCallerIdentity_OptInRegion() { var awsResourceQueryer = new AWSResourceQueryer(_mockAWSClientFactory.Object); var stsResponse = new GetCallerIdentityResponse(); _mockAWSClientFactory.Setup(x => x.GetAWSClient<IAmazonSecurityTokenService>("ap-southeast-3")).Returns(_mockSTSClient.Object); _mockSTSClient.Setup(x => x.GetCallerIdentityAsync(It.IsAny<GetCallerIdentityRequest>(), It.IsAny<CancellationToken>())).Throws(new Exception("Invalid token")); _mockAWSClientFactory.Setup(x => x.GetAWSClient<IAmazonSecurityTokenService>("us-east-1")).Returns(_mockSTSClientDefaultRegion.Object); _mockSTSClientDefaultRegion.Setup(x => x.GetCallerIdentityAsync(It.IsAny<GetCallerIdentityRequest>(), It.IsAny<CancellationToken>())).ReturnsAsync(stsResponse); var exceptionThrown = await Assert.ThrowsAsync<UnableToAccessAWSRegionException>(() => awsResourceQueryer.GetCallerIdentity("ap-southeast-3")); Assert.Equal(DeployToolErrorCode.OptInRegionDisabled, exceptionThrown.ErrorCode); } [Fact] public async Task GetCallerIdentity_BadConnection() { var awsResourceQueryer = new AWSResourceQueryer(_mockAWSClientFactory.Object); var stsResponse = new GetCallerIdentityResponse(); _mockAWSClientFactory.Setup(x => x.GetAWSClient<IAmazonSecurityTokenService>("ap-southeast-3")).Returns(_mockSTSClient.Object); _mockSTSClient.Setup(x => x.GetCallerIdentityAsync(It.IsAny<GetCallerIdentityRequest>(), It.IsAny<CancellationToken>())).Throws(new Exception("Invalid token")); _mockAWSClientFactory.Setup(x => x.GetAWSClient<IAmazonSecurityTokenService>("us-east-1")).Returns(_mockSTSClientDefaultRegion.Object); _mockSTSClientDefaultRegion.Setup(x => x.GetCallerIdentityAsync(It.IsAny<GetCallerIdentityRequest>(), It.IsAny<CancellationToken>())).Throws(new Exception("Invalid token")); var exceptionThrown = await Assert.ThrowsAsync<UnableToAccessAWSRegionException>(() => awsResourceQueryer.GetCallerIdentity("ap-southeast-3")); Assert.Equal(DeployToolErrorCode.UnableToAccessAWSRegion, exceptionThrown.ErrorCode); } [Fact] public void SortElasticBeanstalkWindowsPlatforms() { // Use PlatformOwner as a placeholder to store where the summary should be sorted to. var platforms = new List<PlatformSummary>() { new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server 2016", PlatformVersion = "2.0.0", PlatformOwner = "2" }, new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server 2019", PlatformVersion = "2.0.0", PlatformOwner = "0" }, new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server Core 2016", PlatformVersion = "2.0.0", PlatformOwner = "3" }, new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server Core 2019", PlatformVersion = "2.0.0", PlatformOwner = "1" }, new PlatformSummary { PlatformBranchName = "Test Environment", PlatformVersion = "0.5.0", PlatformOwner = "8" }, new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server 2016", PlatformVersion = "1.0.0", PlatformOwner = "6" }, new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server 2019", PlatformVersion = "1.0.0", PlatformOwner = "4" }, new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server Core 2016", PlatformVersion = "1.0.0", PlatformOwner = "7" }, new PlatformSummary { PlatformBranchName = "IIS 10.0 running on 64bit Windows Server Core 2019", PlatformVersion = "1.0.0", PlatformOwner = "5" } }; AWSResourceQueryer.SortElasticBeanstalkWindowsPlatforms(platforms); for(var i = 0; i < platforms.Count; i++) { Assert.Equal(i.ToString(), platforms[i].PlatformOwner); } } } }
170
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.Orchestration.Utilities; using AWS.Deploy.Recipes.CDK.Common; using Moq; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests { public class DeployedApplicationQueryerTests { private readonly Mock<IAWSResourceQueryer> _mockAWSResourceQueryer; private readonly IDirectoryManager _directoryManager; private readonly TestFileManager _fileManager; private readonly Mock<ILocalUserSettingsEngine> _mockLocalUserSettingsEngine; private readonly Mock<IOrchestratorInteractiveService> _mockOrchestratorInteractiveService; public DeployedApplicationQueryerTests() { _mockAWSResourceQueryer = new Mock<IAWSResourceQueryer>(); _directoryManager = new TestDirectoryManager(); _fileManager = new TestFileManager(); _mockLocalUserSettingsEngine = new Mock<ILocalUserSettingsEngine>(); _mockOrchestratorInteractiveService = new Mock<IOrchestratorInteractiveService>(); } [Fact] public async Task GetExistingDeployedApplications_ListDeploymentsCall() { var stack = new Stack { Tags = new List<Amazon.CloudFormation.Model.Tag>() { new Amazon.CloudFormation.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "AspNetAppEcsFargate" } }, Description = Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, StackStatus = StackStatus.CREATE_COMPLETE, StackName = "Stack1" }; _mockAWSResourceQueryer .Setup(x => x.GetCloudFormationStacks()) .Returns(Task.FromResult(new List<Stack>() { stack })); _mockAWSResourceQueryer .Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult(new List<EnvironmentDescription>())); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var deploymentTypes = new List<DeploymentTypes>() { DeploymentTypes.CdkProject, DeploymentTypes.BeanstalkEnvironment }; var result = await deployedApplicationQueryer.GetExistingDeployedApplications(deploymentTypes); Assert.Single(result); var expectedStack = result.First(); Assert.Equal("Stack1", expectedStack.Name); } [Fact] public async Task GetExistingDeployedApplications_CompatibleSystemRecipes() { var stacks = new List<Stack> { new Stack{ Tags = new List<Amazon.CloudFormation.Model.Tag>() { new Amazon.CloudFormation.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "AspNetAppEcsFargate" } }, Description = Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, StackStatus = StackStatus.CREATE_COMPLETE, StackName = "WebApp" }, new Stack{ Tags = new List<Amazon.CloudFormation.Model.Tag>() { new Amazon.CloudFormation.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "ConsoleAppEcsFargateService" } }, Description = Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, StackStatus = StackStatus.CREATE_COMPLETE, StackName = "ServiceProcessor" } }; _mockAWSResourceQueryer .Setup(x => x.GetCloudFormationStacks()) .Returns(Task.FromResult(stacks)); _mockAWSResourceQueryer .Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult(new List<EnvironmentDescription>())); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var recommendations = new List<Recommendation> { new Recommendation(new RecipeDefinition("AspNetAppEcsFargate", "0.2.0", "ASP.NET Core ECS", DeploymentTypes.CdkProject, DeploymentBundleTypes.Container, "", "", "", "", "" ), null, 100, new Dictionary<string, object>()) { } }; var result = await deployedApplicationQueryer.GetCompatibleApplications(recommendations); Assert.Single(result); Assert.Equal("AspNetAppEcsFargate", result[0].RecipeId); } [Fact] public async Task GetExistingDeployedApplications_WithDeploymentProjects() { var stacks = new List<Stack> { // Existing stack from the base recipe which should be valid new Stack{ Tags = new List<Amazon.CloudFormation.Model.Tag>() { new Amazon.CloudFormation.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "AspNetAppEcsFargate" } }, Description = Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, StackStatus = StackStatus.CREATE_COMPLETE, StackName = "WebApp" }, // Existing stack that was deployed custom deployment project. Should be valid. new Stack{ Tags = new List<Amazon.CloudFormation.Model.Tag>() { new Amazon.CloudFormation.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "AspNetAppEcsFargate-Custom" } }, Description = Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, StackStatus = StackStatus.CREATE_COMPLETE, StackName = "WebApp-Custom" }, // Stack created from a different recipe and should not be valid. new Stack{ Tags = new List<Amazon.CloudFormation.Model.Tag>() { new Amazon.CloudFormation.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "ConsoleAppEcsFargateService" } }, Description = Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, StackStatus = StackStatus.CREATE_COMPLETE, StackName = "ServiceProcessor" } }; _mockAWSResourceQueryer .Setup(x => x.GetCloudFormationStacks()) .Returns(Task.FromResult(stacks)); _mockAWSResourceQueryer .Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult(new List<EnvironmentDescription>())); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var recommendations = new List<Recommendation> { new Recommendation(new RecipeDefinition("AspNetAppEcsFargate-Custom", "0.2.0", "Saved Deployment Project", DeploymentTypes.CdkProject, DeploymentBundleTypes.Container, "", "", "", "", "" ) { PersistedDeploymentProject = true, BaseRecipeId = "AspNetAppEcsFargate" }, null, 100, new Dictionary<string, object>()) { } }; var result = await deployedApplicationQueryer.GetCompatibleApplications(recommendations); Assert.Equal(2, result.Count); Assert.Contains(result, x => string.Equals("AspNetAppEcsFargate", x.RecipeId)); Assert.Contains(result, x => string.Equals("AspNetAppEcsFargate-Custom", x.RecipeId)); } [Theory] [InlineData("", Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, "CREATE_COMPLETE")] [InlineData("AspNetAppEcsFargate", "", "CREATE_COMPLETE")] [InlineData("AspNetAppEcsFargate", Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, "DELETE_IN_PROGRESS")] [InlineData("AspNetAppEcsFargate", Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX, "ROLLBACK_COMPLETE")] public async Task GetExistingDeployedApplications_InvalidConfigurations(string recipeId, string stackDecription, string deploymentStatus) { var tags = new List<Amazon.CloudFormation.Model.Tag>(); if (!string.IsNullOrEmpty(recipeId)) tags.Add(new Amazon.CloudFormation.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "AspNetAppEcsFargate" }); var stack = new Stack { Tags = tags, Description = stackDecription, StackStatus = deploymentStatus, StackName = "Stack1" }; _mockAWSResourceQueryer .Setup(x => x.GetCloudFormationStacks()) .Returns(Task.FromResult(new List<Stack>() { stack })); _mockAWSResourceQueryer .Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult(new List<EnvironmentDescription>())); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var deploymentTypes = new List<DeploymentTypes>() { DeploymentTypes.CdkProject, DeploymentTypes.BeanstalkEnvironment }; var result = await deployedApplicationQueryer.GetExistingDeployedApplications(deploymentTypes); Assert.Empty(result); } [Fact] public async Task GetExistingDeployedApplications_ContainsValidBeanstalkEnvironments() { var environments = new List<EnvironmentDescription> { new EnvironmentDescription { EnvironmentName = "env-1", PlatformArn = "dotnet-platform-arn1", EnvironmentArn = "env-arn-1", Status = EnvironmentStatus.Ready }, new EnvironmentDescription { EnvironmentName = "env-2", PlatformArn = "dotnet-platform-arn1", EnvironmentArn = "env-arn-2", Status = EnvironmentStatus.Ready } }; var platforms = new List<PlatformSummary> { new PlatformSummary { PlatformArn = "dotnet-platform-arn1" }, new PlatformSummary { PlatformArn = "dotnet-platform-arn2" } }; _mockAWSResourceQueryer .Setup(x => x.GetCloudFormationStacks()) .Returns(Task.FromResult(new List<Stack>())); _mockAWSResourceQueryer .Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult(environments)); _mockAWSResourceQueryer .Setup(x => x.GetElasticBeanstalkPlatformArns()) .Returns(Task.FromResult(platforms)); _mockAWSResourceQueryer .Setup(x => x.ListElasticBeanstalkResourceTags(It.IsAny<string>())) .Returns(Task.FromResult(new List<Amazon.ElasticBeanstalk.Model.Tag>())); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var deploymentTypes = new List<DeploymentTypes>() { DeploymentTypes.CdkProject, DeploymentTypes.BeanstalkEnvironment }; var result = await deployedApplicationQueryer.GetExistingDeployedApplications(deploymentTypes); Assert.Contains(result, x => string.Equals("env-1", x.Name)); Assert.Contains(result, x => string.Equals("env-2", x.Name)); } [Fact] public async Task GetExistingDeployedApplication_SkipsEnvironmentsWithIncompatiblePlatformArns() { var environments = new List<EnvironmentDescription> { new EnvironmentDescription { EnvironmentName = "env", PlatformArn = "incompatible-platform-arn", EnvironmentArn = "env-arn", Status = EnvironmentStatus.Ready } }; var platforms = new List<PlatformSummary> { new PlatformSummary { PlatformArn = "dotnet-platform-arn1" }, new PlatformSummary { PlatformArn = "dotnet-platform-arn2" } }; _mockAWSResourceQueryer .Setup(x => x.GetCloudFormationStacks()) .Returns(Task.FromResult(new List<Stack>())); _mockAWSResourceQueryer .Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult(environments)); _mockAWSResourceQueryer .Setup(x => x.GetElasticBeanstalkPlatformArns()) .Returns(Task.FromResult(platforms)); _mockAWSResourceQueryer .Setup(x => x.ListElasticBeanstalkResourceTags(It.IsAny<string>())) .Returns(Task.FromResult(new List<Amazon.ElasticBeanstalk.Model.Tag>())); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var deploymentTypes = new List<DeploymentTypes>() { DeploymentTypes.CdkProject, DeploymentTypes.BeanstalkEnvironment }; var result = await deployedApplicationQueryer.GetExistingDeployedApplications(deploymentTypes); Assert.Empty(result); } [Fact] public async Task GetExistingDeployedApplication_SkipsEnvironmentsCreatedFromTheDeployTool() { var environments = new List<EnvironmentDescription> { new EnvironmentDescription { EnvironmentName = "env", PlatformArn = "dotnet-platform-arn1", EnvironmentArn = "env-arn", Status = EnvironmentStatus.Ready } }; var platforms = new List<PlatformSummary> { new PlatformSummary { PlatformArn = "dotnet-platform-arn1" }, new PlatformSummary { PlatformArn = "dotnet-platform-arn2" } }; var tags = new List<Amazon.ElasticBeanstalk.Model.Tag> { new Amazon.ElasticBeanstalk.Model.Tag { Key = Constants.CloudFormationIdentifier.STACK_TAG, Value = "RecipeId" } }; _mockAWSResourceQueryer .Setup(x => x.GetCloudFormationStacks()) .Returns(Task.FromResult(new List<Stack>())); _mockAWSResourceQueryer .Setup(x => x.ListOfElasticBeanstalkEnvironments(It.IsAny<string>(), It.IsAny<string>())) .Returns(Task.FromResult(environments)); _mockAWSResourceQueryer .Setup(x => x.GetElasticBeanstalkPlatformArns()) .Returns(Task.FromResult(platforms)); _mockAWSResourceQueryer .Setup(x => x.ListElasticBeanstalkResourceTags("env-arn")) .Returns(Task.FromResult(tags)); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var deploymentTypes = new List<DeploymentTypes>() { DeploymentTypes.CdkProject, DeploymentTypes.BeanstalkEnvironment }; var result = await deployedApplicationQueryer.GetExistingDeployedApplications(deploymentTypes); Assert.Empty(result); } [Fact] public async Task GetPreviousSettings_BeanstalkEnvironment() { var application = new CloudApplication("name", "Id", CloudApplicationResourceType.BeanstalkEnvironment, "recipe"); var configurationSettings = new List<ConfigurationOptionSetting> { new ConfigurationOptionSetting { Namespace = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionNameSpace, OptionName = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionName, Value = "enhanced" }, new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.HealthCheckURLOptionName, Namespace = Constants.ElasticBeanstalk.HealthCheckURLOptionNameSpace, Value = "/" }, new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.ProxyOptionName, Namespace = Constants.ElasticBeanstalk.ProxyOptionNameSpace, Value = "nginx" }, new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.XRayTracingOptionName, Namespace = Constants.ElasticBeanstalk.XRayTracingOptionNameSpace, Value = "false" } }; _mockAWSResourceQueryer .Setup(x => x.GetBeanstalkEnvironmentConfigurationSettings(It.IsAny<string>())) .Returns(Task.FromResult(configurationSettings)); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); var projectDefinition = new ProjectDefinition(null, "testPath", "", "net6.0"); var recipeDefinitiion = new RecipeDefinition("AspNetAppExistingBeanstalkEnvironment", "", "", DeploymentTypes.BeanstalkEnvironment, DeploymentBundleTypes.DotnetPublishZipFile, "", "", "", "", ""); var recommendation = new Recommendation(recipeDefinitiion, projectDefinition, 100, new Dictionary<string, object>()); var optionSettings = await deployedApplicationQueryer.GetPreviousSettings(application, recommendation); Assert.Equal("enhanced", optionSettings[Constants.ElasticBeanstalk.EnhancedHealthReportingOptionId]); Assert.Equal("/", optionSettings[Constants.ElasticBeanstalk.HealthCheckURLOptionId]); Assert.Equal("nginx", optionSettings[Constants.ElasticBeanstalk.ProxyOptionId]); Assert.Equal("false", optionSettings[Constants.ElasticBeanstalk.XRayTracingOptionId]); } [Theory] [InlineData(@"{ ""manifestVersion"": 1, ""deployments"": { ""aspNetCoreWeb"": [ { ""name"": ""app"", ""parameters"": { ""iisPath"": ""/path"", ""iisWebSite"": ""Default Web Site Custom"" } } ] } }")] [InlineData(@"{ ""manifestVersion"": 1, // comments ""deployments"": { ""aspNetCoreWeb"": [ { ""name"": ""app"", ""parameters"": { ""iisPath"": ""/path"", ""iisWebSite"": ""Default Web Site Custom"" } } ] } }")] public async Task GetPreviousSettings_BeanstalkWindowsEnvironment(string manifestJson) { var application = new CloudApplication("name", "Id", CloudApplicationResourceType.BeanstalkEnvironment, "recipe"); var configurationSettings = new List<ConfigurationOptionSetting> { new ConfigurationOptionSetting { Namespace = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionNameSpace, OptionName = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionName, Value = "enhanced" }, new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.HealthCheckURLOptionName, Namespace = Constants.ElasticBeanstalk.HealthCheckURLOptionNameSpace, Value = "/" }, new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.XRayTracingOptionName, Namespace = Constants.ElasticBeanstalk.XRayTracingOptionNameSpace, Value = "false" } }; _mockAWSResourceQueryer .Setup(x => x.GetBeanstalkEnvironmentConfigurationSettings(It.IsAny<string>())) .Returns(Task.FromResult(configurationSettings)); var deployedApplicationQueryer = new DeployedApplicationQueryer( _mockAWSResourceQueryer.Object, _mockLocalUserSettingsEngine.Object, _mockOrchestratorInteractiveService.Object, _fileManager); _fileManager.InMemoryStore.Add(Path.Combine("testPath", "aws-windows-deployment-manifest.json"), manifestJson); var projectDefinition = new ProjectDefinition(null, Path.Combine("testPath", "project.csproj"), "", "net6.0"); var recipeDefinitiion = new RecipeDefinition("AspNetAppExistingBeanstalkWindowsEnvironment", "", "", DeploymentTypes.BeanstalkEnvironment, DeploymentBundleTypes.DotnetPublishZipFile, "", "", "", "", ""); var recommendation = new Recommendation(recipeDefinitiion, projectDefinition, 100, new Dictionary<string, object>()); var optionSettings = await deployedApplicationQueryer.GetPreviousSettings(application, recommendation); Assert.Equal("enhanced", optionSettings[Constants.ElasticBeanstalk.EnhancedHealthReportingOptionId]); Assert.Equal("/", optionSettings[Constants.ElasticBeanstalk.HealthCheckURLOptionId]); Assert.Equal("false", optionSettings[Constants.ElasticBeanstalk.XRayTracingOptionId]); Assert.Equal("false", optionSettings[Constants.ElasticBeanstalk.XRayTracingOptionId]); Assert.Equal("/path", optionSettings[Constants.ElasticBeanstalk.IISAppPathOptionId]); Assert.Equal("Default Web Site Custom", optionSettings[Constants.ElasticBeanstalk.IISWebSiteOptionId]); } } }
556
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.DeploymentCommands; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests { public class DeploymentCommandFactoryTests { [Theory] [InlineData(DeploymentTypes.CdkProject, typeof(CdkDeploymentCommand))] [InlineData(DeploymentTypes.BeanstalkEnvironment, typeof(BeanstalkEnvironmentDeploymentCommand))] public void BuildsValidDeploymentCommand(DeploymentTypes deploymentType, Type expectedDeploymentCommandType) { var command = DeploymentCommandFactory.BuildDeploymentCommand(deploymentType); Assert.True(command.GetType() == expectedDeploymentCommandType); } } }
25
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Text; using AWS.Deploy.Orchestration.Utilities; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests { public class DeployToolWorkspaceTests { [Theory] [InlineData("C:/Users/Bob")] [InlineData("C:/Users/Bob/Alice")] public void WithoutOverride_UserProfile_WithoutSpaces(string userProfile) { // ARRANGE var directoryManager = new TestDirectoryManager(); var environmentVariableManager = new TestEnvironmentVariableManager(); // ACT var actualWorkspace = Helpers.GetDeployToolWorkspaceDirectoryRoot(userProfile, directoryManager, environmentVariableManager); // ASSERT var expectedWorkspace = Path.Combine(userProfile, ".aws-dotnet-deploy"); Assert.Equal(expectedWorkspace, actualWorkspace); Assert.Null(environmentVariableManager.GetEnvironmentVariable(Constants.CLI.WORKSPACE_ENV_VARIABLE)); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TMP")); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TEMP")); } [Theory] [InlineData("C:/Users/Bob Mike")] [InlineData("C:/My users/Bob/Alice")] [InlineData("C:/Users/Bob Mike/Alice")] public void WithoutOverride_UserProfile_WithSpaces_ThrowsException(string userProfile) { // ARRANGE var directoryManager = new TestDirectoryManager(); var environmentVariableManager = new TestEnvironmentVariableManager(); // ACT and ASSERT Assert.Throws<InvalidDeployToolWorkspaceException>(() => Helpers.GetDeployToolWorkspaceDirectoryRoot(userProfile, directoryManager, environmentVariableManager)); Assert.Null(environmentVariableManager.GetEnvironmentVariable(Constants.CLI.WORKSPACE_ENV_VARIABLE)); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TMP")); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TEMP")); } [Theory] [InlineData("C:/workspace/deploy-tool-workspace", "C:/Users/Bob")] [InlineData("C:/workspace/deploy-tool-workspace", "C:/Users/Admin/Bob Alice")] [InlineData("C:/aws-workspaces/deploy-tool-workspace", "C:/Users/Admin/Bob Alice")] public void WithOverride_ValidWorkspace(string workspaceOverride, string userProfile) { // ARRANGE var directoryManager = new TestDirectoryManager(); var environmentVariableManager = new TestEnvironmentVariableManager(); environmentVariableManager.store["AWS_DOTNET_DEPLOYTOOL_WORKSPACE"] = workspaceOverride; directoryManager.CreateDirectory(workspaceOverride); // ACT var actualWorkspace = Helpers.GetDeployToolWorkspaceDirectoryRoot(userProfile, directoryManager, environmentVariableManager); // ASSERT var expectedWorkspace = workspaceOverride; var expectedTempDir = Path.Combine(workspaceOverride, "temp"); Assert.True(directoryManager.Exists(expectedWorkspace)); Assert.True(directoryManager.Exists(expectedTempDir)); Assert.Equal(expectedWorkspace, actualWorkspace); Assert.Equal(expectedWorkspace, environmentVariableManager.GetEnvironmentVariable(Constants.CLI.WORKSPACE_ENV_VARIABLE)); Assert.Equal(expectedTempDir, environmentVariableManager.GetEnvironmentVariable("TEMP")); Assert.Equal(expectedTempDir, environmentVariableManager.GetEnvironmentVariable("TMP")); } [Theory] [InlineData("C:/workspace/deploy-tool-workspace", "C:/Users/Bob")] [InlineData("C:/workspace/deploy-tool-workspace", "C:/Users/Admin/Bob Alice")] [InlineData("C:/aws-workspaces/deploy-tool-workspace", "C:/Users/Admin/Bob Alice")] public void WithOverride_DirectoryDoesNotExist_ThrowsException(string workspaceOverride, string userProfile) { // ARRANGE var directoryManager = new TestDirectoryManager(); var environmentVariableManager = new TestEnvironmentVariableManager(); environmentVariableManager.store[Constants.CLI.WORKSPACE_ENV_VARIABLE] = workspaceOverride; // ACT and ASSERT Assert.Throws<InvalidDeployToolWorkspaceException>(() => Helpers.GetDeployToolWorkspaceDirectoryRoot(userProfile, directoryManager, environmentVariableManager)); Assert.False(directoryManager.Exists(workspaceOverride)); Assert.Equal(workspaceOverride, environmentVariableManager.GetEnvironmentVariable(Constants.CLI.WORKSPACE_ENV_VARIABLE)); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TMP")); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TEMP")); } [Theory] [InlineData("C:/workspace/deploy tool workspace", "C:/Users/Bob")] [InlineData("C:/workspace/deploy tool workspace", "C:/Users/Admin/Bob Alice")] [InlineData("C:/aws workspaces/deploy-tool-workspace", "C:/Users/Admin/Bob Alice")] public void WithOverride_DirectoryContainsSpaces_ThrowsException(string workspaceOverride, string userProfile) { // ARRANGE var directoryManager = new TestDirectoryManager(); var environmentVariableManager = new TestEnvironmentVariableManager(); environmentVariableManager.store["AWS_DOTNET_DEPLOYTOOL_WORKSPACE"] = workspaceOverride; directoryManager.CreateDirectory(workspaceOverride); // ACT and ASSERT Assert.Throws<InvalidDeployToolWorkspaceException>(() => Helpers.GetDeployToolWorkspaceDirectoryRoot(userProfile, directoryManager, environmentVariableManager)); Assert.True(directoryManager.Exists(workspaceOverride)); Assert.False(directoryManager.Exists(Path.Combine(workspaceOverride, "temp"))); Assert.Equal(workspaceOverride, environmentVariableManager.GetEnvironmentVariable(Constants.CLI.WORKSPACE_ENV_VARIABLE)); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TMP")); Assert.Null(environmentVariableManager.GetEnvironmentVariable("TEMP")); } } public class TestEnvironmentVariableManager : IEnvironmentVariableManager { public readonly Dictionary<string, string> store = new(); public string GetEnvironmentVariable(string variable) { return store.ContainsKey(variable) ? store[variable] : null; } public void SetEnvironmentVariable(string variable, string value) { store[variable] = value; } } }
134
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation.Model; using Amazon.ElasticBeanstalk.Model; using Amazon.Runtime; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.DisplayedResources; using AWS.Deploy.Orchestration.UnitTests.Utilities; using AWS.Deploy.Recipes; using Moq; using Xunit; using LoadBalancer = Amazon.ElasticLoadBalancingV2.Model.LoadBalancer; namespace AWS.Deploy.Orchestration.UnitTests { public class DisplayedResourcesHandlerTests { private readonly Mock<IAWSResourceQueryer> _mockAWSResourceQueryer; private readonly CloudApplication _cloudApplication; private readonly DisplayedResourceCommandFactory _displayedResourcesFactory; private readonly StackResource _stackResource; private readonly List<StackResource> _stackResources; private readonly EnvironmentDescription _environmentDescription; private readonly LoadBalancer _loadBalancer; private OrchestratorSession _session; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly Mock<IOrchestratorInteractiveService> _orchestratorInteractiveService; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IRecipeHandler _recipeHandler; public DisplayedResourcesHandlerTests() { _directoryManager = new DirectoryManager(); _fileManager = new FileManager(); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new Mock<IOrchestratorInteractiveService>(); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService.Object, _directoryManager, _fileManager, optionSettingHandler, validatorFactory); _mockAWSResourceQueryer = new Mock<IAWSResourceQueryer>(); _cloudApplication = new CloudApplication("StackName", "UniqueId", CloudApplicationResourceType.CloudFormationStack, "RecipeId"); _displayedResourcesFactory = new DisplayedResourceCommandFactory(_mockAWSResourceQueryer.Object); _stackResource = new StackResource(); _stackResources = new List<StackResource>() { _stackResource }; _environmentDescription = new EnvironmentDescription(); _loadBalancer = new LoadBalancer(); } private async Task<RecommendationEngine.RecommendationEngine> BuildRecommendationEngine(string testProjectName) { var fullPath = SystemIOUtilities.ResolvePath(testProjectName); var parser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var awsCredentials = new Mock<AWSCredentials>(); _session = new OrchestratorSession( await parser.Parse(fullPath), awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; return new RecommendationEngine.RecommendationEngine(_session, _recipeHandler); } [Fact] public async Task GetDeploymentOutputs_ElasticBeanstalkEnvironment() { var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals("AspNetAppElasticBeanstalkLinux")); _stackResource.LogicalResourceId = "RecipeBeanstalkEnvironment83CC12DE"; _stackResource.PhysicalResourceId = "PhysicalResourceId"; _stackResource.ResourceType = "AWS::ElasticBeanstalk::Environment"; _environmentDescription.CNAME = "www.website.com"; _mockAWSResourceQueryer.Setup(x => x.DescribeCloudFormationResources(It.IsAny<string>())).Returns(Task.FromResult(_stackResources)); _mockAWSResourceQueryer.Setup(x => x.DescribeElasticBeanstalkEnvironment(It.IsAny<string>())).Returns(Task.FromResult(_environmentDescription)); var disaplayedResourcesHandler = new DisplayedResourcesHandler(_mockAWSResourceQueryer.Object, _displayedResourcesFactory); var outputs = await disaplayedResourcesHandler.GetDeploymentOutputs(_cloudApplication, recommendation); Assert.Single(outputs); var resource = outputs.First(); Assert.Equal("PhysicalResourceId", resource.Id); Assert.Equal("AWS::ElasticBeanstalk::Environment", resource.Type); Assert.Single(resource.Data); Assert.True(resource.Data.ContainsKey("Endpoint")); Assert.Equal("http://www.website.com/", resource.Data["Endpoint"]); } [Fact] public async Task GetDeploymentOutputs_ElasticLoadBalancer() { var engine = await BuildRecommendationEngine("WebAppWithDockerFile"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals("AspNetAppEcsFargate")); _stackResource.LogicalResourceId = "RecipeServiceLoadBalancer68534AEF"; _stackResource.PhysicalResourceId = "PhysicalResourceId"; _stackResource.ResourceType = "AWS::ElasticLoadBalancingV2::LoadBalancer"; _loadBalancer.DNSName = "www.website.com"; _mockAWSResourceQueryer.Setup(x => x.DescribeCloudFormationResources(It.IsAny<string>())).Returns(Task.FromResult(_stackResources)); _mockAWSResourceQueryer.Setup(x => x.DescribeElasticLoadBalancer(It.IsAny<string>())).Returns(Task.FromResult(_loadBalancer)); _mockAWSResourceQueryer.Setup(x => x.DescribeElasticLoadBalancerListeners(It.IsAny<string>())).Returns(Task.FromResult(new List<Amazon.ElasticLoadBalancingV2.Model.Listener>())); var disaplayedResourcesHandler = new DisplayedResourcesHandler(_mockAWSResourceQueryer.Object, _displayedResourcesFactory); var outputs = await disaplayedResourcesHandler.GetDeploymentOutputs(_cloudApplication, recommendation); Assert.Single(outputs); var resource = outputs.First(); Assert.Equal("PhysicalResourceId", resource.Id); Assert.Equal("AWS::ElasticLoadBalancingV2::LoadBalancer", resource.Type); Assert.Single(resource.Data); Assert.True(resource.Data.ContainsKey("Endpoint")); Assert.Equal("http://www.website.com/", resource.Data["Endpoint"]); } [Fact] public async Task GetDeploymentOutputs_S3BucketWithWebSiteConfig() { var engine = await BuildRecommendationEngine("BlazorWasm60"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals("BlazorWasm")); _stackResource.LogicalResourceId = "RecipeContentS3BucketE74B8362"; _stackResource.PhysicalResourceId = "PhysicalResourceId"; _stackResource.ResourceType = "AWS::S3::Bucket"; _mockAWSResourceQueryer.Setup(x => x.DescribeCloudFormationResources(It.IsAny<string>())).Returns(Task.FromResult(_stackResources)); _mockAWSResourceQueryer.Setup(x => x.GetS3BucketLocation(It.IsAny<string>())).Returns(Task.FromResult("us-west-2")); _mockAWSResourceQueryer.Setup(x => x.GetS3BucketWebSiteConfiguration(It.IsAny<string>())).Returns(Task.FromResult(new Amazon.S3.Model.WebsiteConfiguration { IndexDocumentSuffix = "index.html" })); var disaplayedResourcesHandler = new DisplayedResourcesHandler(_mockAWSResourceQueryer.Object, _displayedResourcesFactory); var outputs = await disaplayedResourcesHandler.GetDeploymentOutputs(_cloudApplication, recommendation); var resource = outputs.First(); Assert.Equal("PhysicalResourceId", resource.Id); Assert.Equal("AWS::S3::Bucket", resource.Type); Assert.Equal(2, resource.Data.Count); Assert.True(resource.Data.ContainsKey("Endpoint")); Assert.True(resource.Data.ContainsKey("Bucket Name")); Assert.Equal("http://PhysicalResourceId.s3-website-us-west-2.amazonaws.com/", resource.Data["Endpoint"]); Assert.Equal("PhysicalResourceId", resource.Data["Bucket Name"]); } [Fact] public async Task GetDeploymentOutputs_S3BucketWithoutWebSiteConfig() { var engine = await BuildRecommendationEngine("BlazorWasm60"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals("BlazorWasm")); _stackResource.LogicalResourceId = "RecipeContentS3BucketE74B8362"; _stackResource.PhysicalResourceId = "PhysicalResourceId"; _stackResource.ResourceType = "AWS::S3::Bucket"; _mockAWSResourceQueryer.Setup(x => x.DescribeCloudFormationResources(It.IsAny<string>())).Returns(Task.FromResult(_stackResources)); _mockAWSResourceQueryer.Setup(x => x.GetS3BucketLocation(It.IsAny<string>())).Returns(Task.FromResult("us-west-2")); var disaplayedResourcesHandler = new DisplayedResourcesHandler(_mockAWSResourceQueryer.Object, _displayedResourcesFactory); var outputs = await disaplayedResourcesHandler.GetDeploymentOutputs(_cloudApplication, recommendation); var resource = outputs.First(); Assert.Equal("PhysicalResourceId", resource.Id); Assert.Equal("AWS::S3::Bucket", resource.Type); Assert.Single(resource.Data); Assert.True(resource.Data.ContainsKey("Bucket Name")); Assert.Equal("PhysicalResourceId", resource.Data["Bucket Name"]); } [Fact] public async Task GetDeploymentOutputs_CloudFrontDistribution() { var engine = await BuildRecommendationEngine("BlazorWasm60"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals("BlazorWasm")); _stackResource.LogicalResourceId = "RecipeCloudFrontDistribution2BE25932"; _stackResource.PhysicalResourceId = "PhysicalResourceId"; _stackResource.ResourceType = "AWS::CloudFront::Distribution"; _mockAWSResourceQueryer.Setup(x => x.DescribeCloudFormationResources(It.IsAny<string>())).Returns(Task.FromResult(_stackResources)); _mockAWSResourceQueryer.Setup(x => x.GetCloudFrontDistribution(It.IsAny<string>())).Returns(Task.FromResult(new Amazon.CloudFront.Model.Distribution { Id = "PhysicalResourceId", DomainName = "id.cloudfront.net" })); var disaplayedResourcesHandler = new DisplayedResourcesHandler(_mockAWSResourceQueryer.Object, _displayedResourcesFactory); var outputs = await disaplayedResourcesHandler.GetDeploymentOutputs(_cloudApplication, recommendation); var resource = outputs.First(); Assert.Equal("PhysicalResourceId", resource.Id); Assert.Equal("AWS::CloudFront::Distribution", resource.Type); Assert.Single(resource.Data); Assert.True(resource.Data.ContainsKey("Endpoint")); Assert.Equal("https://id.cloudfront.net/", resource.Data["Endpoint"]); } [Fact] public async Task GetDeploymentOutputs_UnknownType() { var engine = await BuildRecommendationEngine("ConsoleAppService"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals("ConsoleAppEcsFargateService")); _stackResource.LogicalResourceId = "RecipeEcsClusterB4EDBB7E"; _stackResource.PhysicalResourceId = "PhysicalResourceId"; _stackResource.ResourceType = "UnknownType"; _mockAWSResourceQueryer.Setup(x => x.DescribeCloudFormationResources(It.IsAny<string>())).Returns(Task.FromResult(_stackResources)); var disaplayedResourcesHandler = new DisplayedResourcesHandler(_mockAWSResourceQueryer.Object, _displayedResourcesFactory); var outputs = await disaplayedResourcesHandler.GetDeploymentOutputs(_cloudApplication, recommendation); Assert.Single(outputs); var resource = outputs.First(); Assert.Equal("PhysicalResourceId", resource.Id); Assert.Equal("UnknownType", resource.Type); Assert.Empty(resource.Data); } } }
237
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO.Compression; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.ElasticBeanstalk.Model; using Amazon.Runtime; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration.ServiceHandlers; using AWS.Deploy.Orchestration.UnitTests.Utilities; using AWS.Deploy.Recipes; using Moq; using Xunit; using System.Text.Json; namespace AWS.Deploy.Orchestration.UnitTests { public class ElasticBeanstalkHandlerTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<IServiceProvider> _serviceProvider; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly Mock<IOrchestratorInteractiveService> _orchestratorInteractiveService; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IRecipeHandler _recipeHandler; public ElasticBeanstalkHandlerTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); _directoryManager = new DirectoryManager(); _fileManager = new FileManager(); _deploymentManifestEngine = new DeploymentManifestEngine(_directoryManager, _fileManager); _orchestratorInteractiveService = new Mock<IOrchestratorInteractiveService>(); var serviceProvider = new Mock<IServiceProvider>(); var validatorFactory = new ValidatorFactory(serviceProvider.Object); var optionSettingHandler = new OptionSettingHandler(validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine, _orchestratorInteractiveService.Object, _directoryManager, _fileManager, optionSettingHandler, validatorFactory); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); } [Fact] public async Task GetAdditionSettingsTest_DefaultValues() { // ARRANGE var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals(Constants.RecipeIdentifier.EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID)); var elasticBeanstalkHandler = new AWSElasticBeanstalkHandler(new Mock<IAWSClientFactory>().Object, new Mock<IOrchestratorInteractiveService>().Object, new Mock<IFileManager>().Object, _optionSettingHandler); // ACT var optionSettings = elasticBeanstalkHandler.GetEnvironmentConfigurationSettings(recommendation); // ASSERT Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionName, Namespace = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionNameSpace, Value = "enhanced" }, x)); Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.HealthCheckURLOptionName, Namespace = Constants.ElasticBeanstalk.HealthCheckURLOptionNameSpace, Value = "/" }, x)); Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.ProxyOptionName, Namespace = Constants.ElasticBeanstalk.ProxyOptionNameSpace, Value = "nginx" }, x)); Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.XRayTracingOptionName, Namespace = Constants.ElasticBeanstalk.XRayTracingOptionNameSpace, Value = "false" }, x)); } [Fact] public async Task GetAdditionSettingsTest_CustomValues() { // ARRANGE var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals(Constants.RecipeIdentifier.EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID)); var elasticBeanstalkHandler = new AWSElasticBeanstalkHandler(new Mock<IAWSClientFactory>().Object, new Mock<IOrchestratorInteractiveService>().Object, new Mock<IFileManager>().Object, _optionSettingHandler); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.EnhancedHealthReportingOptionId), "basic"); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.HealthCheckURLOptionId), "/url"); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.ProxyOptionId), "none"); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.XRayTracingOptionId), "true"); // ACT var optionSettings = elasticBeanstalkHandler.GetEnvironmentConfigurationSettings(recommendation); // ASSERT Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionName, Namespace = Constants.ElasticBeanstalk.EnhancedHealthReportingOptionNameSpace, Value = "basic" }, x)); Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.HealthCheckURLOptionName, Namespace = Constants.ElasticBeanstalk.HealthCheckURLOptionNameSpace, Value = "/url" }, x)); Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.ProxyOptionName, Namespace = Constants.ElasticBeanstalk.ProxyOptionNameSpace, Value = "none" }, x)); Assert.Contains(optionSettings, x => IsEqual(new ConfigurationOptionSetting { OptionName = Constants.ElasticBeanstalk.XRayTracingOptionName, Namespace = Constants.ElasticBeanstalk.XRayTracingOptionNameSpace, Value = "true" }, x)); } private async Task<RecommendationEngine.RecommendationEngine> BuildRecommendationEngine(string testProjectName) { var fullPath = SystemIOUtilities.ResolvePath(testProjectName); var parser = new ProjectDefinitionParser(new FileManager(), new DirectoryManager()); var awsCredentials = new Mock<AWSCredentials>(); var session = new OrchestratorSession( await parser.Parse(fullPath), awsCredentials.Object, "us-west-2", "123456789012") { AWSProfileName = "default" }; return new RecommendationEngine.RecommendationEngine(session, _recipeHandler); } private bool IsEqual(ConfigurationOptionSetting expected, ConfigurationOptionSetting actual) { return string.Equals(expected.OptionName, actual.OptionName) && string.Equals(expected.Namespace, actual.Namespace) && string.Equals(expected.Value, actual.Value); } /// <summary> /// This method tests in the case of an existing windows beanstalk recipe, if there is no windows manifest file, then one is created and it contains the correct values. /// </summary> [Fact] public async Task SetupWindowsDeploymentManifestTest() { // ARRANGE var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals(Constants.RecipeIdentifier.EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID)); var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); var zipPath = Path.Combine(tempDirectory, "testZip.zip"); ZipFile.CreateFromDirectory(recommendation.GetProjectDirectory(), zipPath); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.IISWebSiteOptionId), "website"); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.IISAppPathOptionId), "apppath"); var elasticBeanstalkHandler = new AWSElasticBeanstalkHandler(new Mock<IAWSClientFactory>().Object, new Mock<IOrchestratorInteractiveService>().Object, new Mock<IFileManager>().Object, _optionSettingHandler); elasticBeanstalkHandler.SetupWindowsDeploymentManifest(recommendation, zipPath); using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) { ZipArchiveEntry readmeEntry = archive.GetEntry("aws-windows-deployment-manifest.json"); var manifestFile = JsonSerializer.Deserialize<ElasticBeanstalkWindowsManifest>(readmeEntry.Open()); Assert.NotNull(manifestFile); var aspNetCoreWebEntry = Assert.Single(manifestFile.Deployments.AspNetCoreWeb); Assert.Equal("website", aspNetCoreWebEntry.Parameters.IISWebSite); Assert.Equal("apppath", aspNetCoreWebEntry.Parameters.IISPath); } } } /// <summary> /// This method tests in the case of an existing windows beanstalk recipe, if there is a windows manifest file, then one is updated correctly. /// The manifest file is generated from <see cref="ElasticBeanstalkWindowsManifest"/> and updated to contain the IIS Website and IIS App path. /// </summary> [Fact] public async Task SetupWindowsDeploymentManifestTest_ExistingFile() { // ARRANGE var engine = await BuildRecommendationEngine("WebAppNoDockerFile"); var recommendations = await engine.ComputeRecommendations(); var recommendation = recommendations.First(r => r.Recipe.Id.Equals(Constants.RecipeIdentifier.EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID)); var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); var manifest = new ElasticBeanstalkWindowsManifest(); var deployment = new ElasticBeanstalkWindowsManifest.ManifestDeployments.AspNetCoreWebDeployments(); manifest.Deployments.AspNetCoreWeb.Add(deployment); var zipPath = Path.Combine(tempDirectory, "testZip.zip"); ZipFile.CreateFromDirectory(recommendation.GetProjectDirectory(), zipPath); using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update)) { using (var jsonStream = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(manifest))) { var zipEntry = zipArchive.CreateEntry(Constants.ElasticBeanstalk.WindowsManifestName); using var zipEntryStream = zipEntry.Open(); jsonStream.Position = 0; jsonStream.CopyTo(zipEntryStream); } } await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.IISWebSiteOptionId), "website"); await _optionSettingHandler.SetOptionSettingValue(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.IISAppPathOptionId), "apppath"); var elasticBeanstalkHandler = new AWSElasticBeanstalkHandler(new Mock<IAWSClientFactory>().Object, new Mock<IOrchestratorInteractiveService>().Object, new Mock<IFileManager>().Object, _optionSettingHandler); elasticBeanstalkHandler.SetupWindowsDeploymentManifest(recommendation, zipPath); using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read)) { ZipArchiveEntry readmeEntry = archive.GetEntry("aws-windows-deployment-manifest.json"); var manifestFileJson = readmeEntry.Open(); var manifestFile = JsonSerializer.Deserialize<ElasticBeanstalkWindowsManifest>(manifestFileJson); Assert.NotNull(manifestFile); var aspNetCoreWebEntry = Assert.Single(manifestFile.Deployments.AspNetCoreWeb); Assert.Equal("website", aspNetCoreWebEntry.Parameters.IISWebSite); Assert.Equal("apppath", aspNetCoreWebEntry.Parameters.IISPath); } } } } }
276
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.Orchestration.Utilities; using AWS.Deploy.Common; using Moq; using Xunit; using System.IO; using AWS.Deploy.Common.IO; namespace AWS.Deploy.Orchestration.UnitTests { public class GetSaveSettingsConfigurationTests { [Fact] public void GetSaveSettingsConfiguration_InvalidConfiguration_ThrowsException() { // ARRANGE var saveSettingsPath = "Path/To/JSONFile/1"; var saveAllSettingsPath = "Path/To/JSONFile/2"; var projectDirectory = "Path/To/ProjectDirectory"; var fileManager = new Mock<IFileManager>(); fileManager.Setup(x => x.IsFileValidPath(It.IsAny<string>())).Returns(true); //ACT and ASSERT // Its throws an exception because saveSettings and saveSettingsAll both hold a non-null value Assert.Throws<FailedToSaveDeploymentSettingsException>(() => Helpers.GetSaveSettingsConfiguration(saveSettingsPath, saveAllSettingsPath, projectDirectory, fileManager.Object)); } [Fact] public void GetSaveSettingsConfiguration_ModifiedSettings() { // ARRANGE var temp = Path.GetTempPath(); var saveSettingsPath = Path.Combine(temp, "Path", "To", "JSONFile"); var projectDirectory = Path.Combine(temp, "Path", "To", "ProjectDirectory"); var fileManager = new Mock<IFileManager>(); fileManager.Setup(x => x.IsFileValidPath(It.IsAny<string>())).Returns(true); // ACT var saveSettingsConfiguration = Helpers.GetSaveSettingsConfiguration(saveSettingsPath, null, projectDirectory, fileManager.Object); // ASSERT Assert.Equal(SaveSettingsType.Modified, saveSettingsConfiguration.SettingsType); Assert.Equal(saveSettingsPath, saveSettingsConfiguration.FilePath); } [Fact] public void GetSaveSettingsConfiguration_AllSettings() { // ARRANGE var temp = Path.GetTempPath(); var saveAllSettingsPath = Path.Combine(temp, "Path", "To", "JSONFile"); var projectDirectory = Path.Combine(temp, "Path", "To", "ProjectDirectory"); var fileManager = new Mock<IFileManager>(); fileManager.Setup(x => x.IsFileValidPath(It.IsAny<string>())).Returns(true); // ACT var saveSettingsConfiguration = Helpers.GetSaveSettingsConfiguration(null, saveAllSettingsPath, projectDirectory, fileManager.Object); // ASSERT Assert.Equal(SaveSettingsType.All, saveSettingsConfiguration.SettingsType); Assert.Equal(saveAllSettingsPath, saveSettingsConfiguration.FilePath); } [Fact] public void GetSaveSettingsConfiguration_None() { // ARRANGE var temp = Path.GetTempPath(); var projectDirectory = Path.Combine(temp, "Path", "To", "ProjectDirectory"); var fileManager = new Mock<IFileManager>(); fileManager.Setup(x => x.IsFileValidPath(It.IsAny<string>())).Returns(true); // ACT var saveSettingsConfiguration = Helpers.GetSaveSettingsConfiguration(null, null, projectDirectory, fileManager.Object); // ASSERT Assert.Equal(SaveSettingsType.None, saveSettingsConfiguration.SettingsType); Assert.Equal(string.Empty, saveSettingsConfiguration.FilePath); } } }
84
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration.UnitTests.Utilities; using AWS.Deploy.Recipes; using Moq; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests { public class RecipeHandlerTests { private readonly Mock<IDeploymentManifestEngine> _deploymentManifestEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly TestDirectoryManager _directoryManager; private readonly TestFileManager _fileManager; private readonly Mock<IServiceProvider> _serviceProvider; private readonly IValidatorFactory _validatorFactory; private readonly IOptionSettingHandler _optionSettingHandler; private readonly IRecipeHandler _recipeHandler; public RecipeHandlerTests() { _deploymentManifestEngine = new Mock<IDeploymentManifestEngine>(); _orchestratorInteractiveService = new TestToolOrchestratorInteractiveService(); _directoryManager = new TestDirectoryManager(); _fileManager = new TestFileManager(); _serviceProvider = new Mock<IServiceProvider>(); _validatorFactory = new ValidatorFactory(_serviceProvider.Object); _optionSettingHandler = new OptionSettingHandler(_validatorFactory); _recipeHandler = new RecipeHandler(_deploymentManifestEngine.Object, _orchestratorInteractiveService, _directoryManager, _fileManager, _optionSettingHandler, _validatorFactory); } [Fact] public async Task DependencyTree_HappyPath() { _directoryManager.AddedFiles.Add(RecipeLocator.FindRecipeDefinitionsPath(), new HashSet<string> { "path1" }); _fileManager.InMemoryStore.Add("path1", File.ReadAllText("./Recipes/OptionSettingCyclicDependency.recipe")); var recipeDefinitions = await _recipeHandler.GetRecipeDefinitions(null); var recipe = Assert.Single(recipeDefinitions); Assert.Equal("AspNetAppEcsFargate", recipe.Id); var ecsCluster = recipe.OptionSettings.First(x => x.Id.Equals("ECSCluster")); Assert.NotNull(ecsCluster); Assert.Empty(ecsCluster.Dependents); var ecsClusterCreateNew = ecsCluster.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.NotNull(ecsClusterCreateNew); Assert.Equal(2, ecsClusterCreateNew.Dependents.Count); Assert.NotNull(ecsClusterCreateNew.Dependents.First(x => x.Equals("ECSCluster.ClusterArn"))); Assert.NotNull(ecsClusterCreateNew.Dependents.First(x => x.Equals("ECSCluster.NewClusterName"))); } [Fact] public async Task DependencyTree_CyclicDependency() { _directoryManager.AddedFiles.Add(RecipeLocator.FindRecipeDefinitionsPath(), new HashSet<string> { "path1" }); _fileManager.InMemoryStore.Add("path1", File.ReadAllText("./Recipes/OptionSettingCyclicDependency.recipe")); var recipeDefinitions = await _recipeHandler.GetRecipeDefinitions(null); var recipe = Assert.Single(recipeDefinitions); Assert.Equal("AspNetAppEcsFargate", recipe.Id); var iamRole = recipe.OptionSettings.First(x => x.Id.Equals("ApplicationIAMRole")); Assert.NotNull(iamRole); Assert.Empty(iamRole.Dependents); var iamRoleCreateNew = iamRole.ChildOptionSettings.First(x => x.Id.Equals("CreateNew")); Assert.NotNull(iamRoleCreateNew); Assert.Single(iamRoleCreateNew.Dependents); Assert.NotNull(iamRoleCreateNew.Dependents.First(x => x.Equals("ApplicationIAMRole.RoleArn"))); var iamRoleRoleArn = iamRole.ChildOptionSettings.First(x => x.Id.Equals("RoleArn")); Assert.NotNull(iamRoleRoleArn); Assert.Single(iamRoleRoleArn.Dependents); Assert.NotNull(iamRoleRoleArn.Dependents.First(x => x.Equals("ApplicationIAMRole.CreateNew"))); } } }
84