Exemplo n.º 1
0
        public void OneTimeSetUp()
        {
            if (ExplicitExeVersion != null)
            {
                DownloadExplicitHelmExecutable();
                helmVersion = new SemanticVersion(ExplicitExeVersion).Major == 2 ? HelmVersion.V2 : HelmVersion.V3;
            }
            else
            {
                helmVersion = GetVersion();
            }

            void DownloadExplicitHelmExecutable()
            {
                explicitVersionTempDirectory = TemporaryDirectory.Create();
                var fileName = Path.GetFullPath(Path.Combine(explicitVersionTempDirectory.DirectoryPath, $"helm-v{ExplicitExeVersion}-{HelmOsPlatform}.tgz"));

                using (new TemporaryFile(fileName))
                {
                    DownloadHelmPackage(ExplicitExeVersion, fileName);

                    new TarGzipPackageExtractor(ConsoleLog.Instance).Extract(fileName, explicitVersionTempDirectory.DirectoryPath);
                }
            }
        }
            public async Task CanDeployWebAppZip_ToDeploymentSlot()
            {
                var slotName = "stage";

                greeting = "stage";

                (string packagePath, string packageName, string packageVersion)packageinfo;

                var slotTask = webMgmtClient.WebApps.BeginCreateOrUpdateSlotAsync(resourceGroupName, resourceGroupName,
                                                                                  site,
                                                                                  slotName);

                var tempPath = TemporaryDirectory.Create();

                new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage");
                File.WriteAllText(Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"),
                                  "Hello #{Greeting}");
                packageinfo.packagePath    = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.zip";
                packageinfo.packageVersion = "1.0.0";
                packageinfo.packageName    = "AzureZipDeployPackage";
                ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath);

                await slotTask;

                await CommandTestBuilder.CreateAsync <DeployAzureAppServiceCommand, Program>().WithArrange(context =>
                {
                    context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion);
                    AddVariables(context);
                    context.Variables.Add("Octopus.Action.Azure.DeploymentSlot", slotName);
                }).Execute();

                await AssertContent($"{site.Name}-{slotName}.azurewebsites.net", $"Hello {greeting}");
            }
        public void WithInstructions()
        {
            var instructions =
                InstructionBuilder
                .Create()
                .WithCalamariInstruction("test-calamari-instruction")
                .WithNodeInstruction()
                .AsString();

            using (var temporaryDirectory = TemporaryDirectory.Create())
            {
                var generatedApplicationPath = CodeGenerator.GenerateConsoleApplication("node", temporaryDirectory.DirectoryPath);
                var toolRoot        = Path.Combine(temporaryDirectory.DirectoryPath, "app");
                var destinationPath =
                    CalamariEnvironment.IsRunningOnWindows ? toolRoot : Path.Combine(toolRoot, "bin");

                DirectoryEx.Copy(generatedApplicationPath, destinationPath);

                var variables = new VariableDictionary
                {
                    { SpecialVariables.Execution.Manifest, instructions },
                    { nameof(NodeInstructions.BootstrapperPathVariable), "BootstrapperPathVariable_Value" },
                    { nameof(NodeInstructions.NodePathVariable), toolRoot },
                    { nameof(NodeInstructions.TargetEntryPoint), "TargetEntryPoint_Value" },
                    { nameof(NodeInstructions.TargetPathVariable), "TargetPathVariable_Value" },
                };

                var result = ExecuteCommand(variables, "Calamari.Tests");

                result.AssertSuccess();
                result.AssertOutput(string.Join(Environment.NewLine, "Hello from TestCommand", "Hello from my custom node!",
                                                Path.Combine("BootstrapperPathVariable_Value", "bootstrapper.js"),
                                                Path.Combine("TargetPathVariable_Value", "TargetEntryPoint")));
            }
        }
Exemplo n.º 4
0
        public async Task PackagedScriptDoesNotExecute()
        {
            using (var tempPath = TemporaryDirectory.Create())
            {
                foreach (var stage in defaultScriptStages)
                {
                    File.WriteAllText(Path.Combine(tempPath.DirectoryPath, $"{stage}.ps1"), $"echo 'Hello from {stage}'");
                }

                await CommandTestBuilder.CreateAsync <NoPackagedScriptCommand, MyProgram>()
                .WithArrange(context =>
                {
                    context.Variables.Add(KnownVariables.Package.RunPackageScripts, bool.TrueString);
                    context.WithFilesToCopy(tempPath.DirectoryPath);
                })
                .WithAssert(result =>
                {
                    result.WasSuccessful.Should().BeTrue();
                    foreach (var stage in defaultScriptStages)
                    {
                        result.FullLog.Should().NotContain($"Hello from {stage}");
                    }
                })
                .Execute(true);
            }
        }
Exemplo n.º 5
0
        public async Task AssertPackageScriptsAreRun(bool deleteScripts)
        {
            using (var tempPath = TemporaryDirectory.Create())
            {
                foreach (var stage in defaultScriptStages)
                {
                    File.WriteAllText(Path.Combine(tempPath.DirectoryPath, $"{stage}.ps1"), $"echo 'Hello from {stage}'");
                }

                await CommandTestBuilder.CreateAsync <MyCommand, MyProgram>()
                .WithArrange(context =>
                {
                    context.Variables.Add(KnownVariables.Package.RunPackageScripts, bool.TrueString);
                    context.Variables.Add(KnownVariables.DeleteScriptsOnCleanup, deleteScripts.ToString());
                    context.WithFilesToCopy(tempPath.DirectoryPath);
                })
                .WithAssert(result =>
                {
                    var currentIndex = 0;
                    foreach (var stage in defaultScriptStages)
                    {
                        var index = result.FullLog.IndexOf($"Hello from {stage}", StringComparison.Ordinal);
                        index.Should().BeGreaterThan(currentIndex);
                        currentIndex = index;

                        File.Exists(Path.Combine(tempPath.DirectoryPath, $"{stage}.ps1")).Should().Be(!deleteScripts);
                    }
                })
                .Execute();
            }
        }
Exemplo n.º 6
0
        public async Task AssertStructuredConfigurationVariablesRuns()
        {
            using (var tempPath = TemporaryDirectory.Create())
            {
                var expected   = @"{
  ""Environment"": ""Test""
}".Replace("\r", String.Empty);
                var targetPath = Path.Combine(tempPath.DirectoryPath, "myfile.json");
                File.WriteAllText(targetPath, @"{
  ""Environment"": ""Dev""
}");

                await CommandTestBuilder.CreateAsync <MyCommand, MyProgram>()
                .WithArrange(context =>
                {
                    context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables);
                    context.Variables.Add(ActionVariables.StructuredConfigurationVariablesTargets, "*.json");
                    context.Variables.Add("Environment", "Test");
                    context.WithFilesToCopy(tempPath.DirectoryPath);
                })
                .WithAssert(result =>
                {
                    File.ReadAllText(targetPath).Replace("\r", String.Empty).Should().Be(expected);
                })
                .Execute();
            }
        }
        public async Task Deploy_WebApp_Preserve_App_Data()
        {
            var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60);

            var webApp = await CreateWebApp(webAppName);

            using var tempPath = TemporaryDirectory.Create();

            Directory.CreateDirectory(Path.Combine(tempPath.DirectoryPath, "App_Data"));
            File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "App_Data", "newfile1.txt"), "Hello World");
            File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), "Hello World");

            await CommandTestBuilder.CreateAsync <DeployAzureWebCommand, Program>()
            .WithArrange(context =>
            {
                AddDefaults(context, webAppName);
                context.Variables.Add(SpecialVariables.Action.Azure.RemoveAdditionalFiles, bool.TrueString);
                context.WithFilesToCopy(tempPath.DirectoryPath);
            })
            .Execute();

            var packagePath = TestEnvironment.GetTestPath("Packages", "AppDataList");

            await CommandTestBuilder.CreateAsync <DeployAzureWebCommand, Program>()
            .WithArrange(context =>
            {
                AddDefaults(context, webAppName);
                context.Variables.Add(SpecialVariables.Action.Azure.RemoveAdditionalFiles, bool.TrueString);
                context.Variables.Add(SpecialVariables.Action.Azure.PreserveAppData, bool.TrueString);
                context.WithFilesToCopy(packagePath);
            })
            .Execute();

            await AssertContent(webApp.DefaultHostName, "newfile1.txt\r\nnewfile2.txt\r\n");
        }
Exemplo n.º 8
0
        public void CreateInParallel()
        {
            const int Iterations = 400;
            var       dirs       = new TemporaryDirectory[Iterations];

            Parallel.For(0, Iterations, new ParallelOptions {
                MaxDegreeOfParallelism = 50
            }, i =>
            {
                dirs[i] = TemporaryDirectory.Create();
                dirs[i].CreateEmptyFile("test.txt");
            });

            try
            {
                Assert.Equal(Iterations, dirs.DistinctBy(dir => dir.FullPath).Count());

                foreach (var dir in dirs)
                {
                    Assert.All(dirs, dir => Assert.True(Directory.Exists(dir.FullPath)));
                }
            }
            finally
            {
                foreach (var item in dirs)
                {
                    item?.Dispose();
                }
            }
        }
Exemplo n.º 9
0
        public async Task AssertConfigurationTransformsRuns()
        {
            using (var tempPath = TemporaryDirectory.Create())
            {
                var expected   = @"<configuration>
    <appSettings>
        <add key=""Environment"" value=""Test"" />
    </appSettings>
</configuration>".Replace("\r", String.Empty);
                var targetPath = Path.Combine(tempPath.DirectoryPath, "bar.config");
                File.WriteAllText(targetPath, @"<configuration>
    <appSettings>
        <add key=""Environment"" value=""Dev"" />
    </appSettings>
</configuration>");
                File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "bar.Release.config"), @"<configuration xmlns:xdt=""http://schemas.microsoft.com/XML-Document-Transform"">
    <appSettings>
        <add key=""Environment"" value=""Test"" xdt:Transform=""SetAttributes"" xdt:Locator=""Match(key)"" />
    </appSettings>
</configuration>");
                await CommandTestBuilder.CreateAsync <MyCommand, MyProgram>()
                .WithArrange(context =>
                {
                    context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationTransforms);
                    context.Variables.Add(KnownVariables.Package.AutomaticallyRunConfigurationTransformationFiles, bool.TrueString);
                    context.WithFilesToCopy(tempPath.DirectoryPath);
                })
                .WithAssert(result =>
                {
                    File.ReadAllText(targetPath).Replace("\r", String.Empty).Should().Be(expected);
                })
                .Execute();
            }
        }
Exemplo n.º 10
0
        public async Task LargeDirectory_NoScannerMatch()
        {
            var stopwatch = ValueStopwatch.StartNew();

            using var directory = TemporaryDirectory.Create();
            const int FileCount = 10_000;

            for (var i = 0; i < FileCount; i++)
            {
                await File.WriteAllTextAsync(directory.GetFullPath($"text{i.ToStringInvariant()}.txt"), "");
            }

            _testOutputHelper.WriteLine("File generated in " + stopwatch.GetElapsedTime());
            stopwatch = ValueStopwatch.StartNew();

            var items = new List <Dependency>(FileCount);

            await foreach (var item in DependencyScanner.ScanDirectoryAsync(directory.FullPath, new ScannerOptions {
                Scanners = new[] { new DummyScannerNeverMatch() }
            }))
            {
                items.Add(item);
            }

            _testOutputHelper.WriteLine("File scanned in " + stopwatch.GetElapsedTime());
            Assert.Empty(items);
        }
        public async Task Setup()
        {
            azureConfigPath = TemporaryDirectory.Create();
            Environment.SetEnvironmentVariable("AZURE_CONFIG_DIR", azureConfigPath.DirectoryPath);

            clientId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId);
            clientSecret   = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword);
            tenantId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId);
            subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId);
            var resourceGroupName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60);

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                                                      AzureEnvironment.AzureGlobalCloud);

            azure = Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithSubscription(subscriptionId);

            resourceGroup = await azure.ResourceGroups
                            .Define(resourceGroupName)
                            .WithRegion(Region.USWest)
                            .CreateAsync();

            appServicePlan = await azure.AppServices.AppServicePlans
                             .Define(SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60))
                             .WithRegion(resourceGroup.Region)
                             .WithExistingResourceGroup(resourceGroup)
                             .WithPricingTier(PricingTier.StandardS1)
                             .WithOperatingSystem(OperatingSystem.Windows)
                             .CreateAsync();
        }
        public async Task Deploy_WebApp_To_A_Slot()
        {
            var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60);
            var slotName   = "staging";

            var webApp = await CreateWebApp(webAppName);

            var deploymentSlot = await webApp.DeploymentSlots.Define(slotName)
                                 .WithConfigurationFromParent()
                                 .WithAutoSwapSlotName("production")
                                 .CreateAsync();

            using var tempPath = TemporaryDirectory.Create();
            const string actualText = "Hello World";

            File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "index.html"), actualText);

            await CommandTestBuilder.CreateAsync <DeployAzureWebCommand, Program>()
            .WithArrange(context =>
            {
                AddDefaults(context, webAppName);
                context.Variables.Add(SpecialVariables.Action.Azure.WebAppSlot, slotName);

                context.WithFilesToCopy(tempPath.DirectoryPath);
            })
            .Execute();

            await AssertContent(deploymentSlot.DefaultHostName, actualText);
        }
Exemplo n.º 13
0
        public async Task CalamariFlavourProgramAsync_PerformsReplacementCorrectlyWithoutCanonicalFileExtension(string configFileName, string variableName, string expectedReplacer)
        {
            const string newPort = "4444";

            using (var tempPath = TemporaryDirectory.Create())
            {
                var targetPath = Path.Combine(tempPath.DirectoryPath, configFileName);
                File.Copy(BuildConfigPath(configFileName), targetPath);

                await CommandTestBuilder.CreateAsync <NoOpPipelineCommand, AsyncFlavourProgram>()
                .WithArrange(context =>
                {
                    context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.StructuredConfigurationVariables);
                    context.Variables.Add(ActionVariables.StructuredConfigurationVariablesTargets, configFileName);
                    context.Variables.Add(variableName, newPort);
                    context.WithFilesToCopy(tempPath.DirectoryPath);
                })
                .WithAssert(result =>
                {
                    result.FullLog.Should().Contain($"Structured variable replacement succeeded on file {targetPath} with format {expectedReplacer}");
                    File.ReadAllText(targetPath).Should().Contain(newPort);
                })
                .Execute();
            }
        }
Exemplo n.º 14
0
        public async Task AssertConfigurationVariablesRuns()
        {
            using (var tempPath = TemporaryDirectory.Create())
            {
                var expected   = @"<configuration>
    <appSettings>
        <add key=""Environment"" value=""Test"" />
    </appSettings>
</configuration>".Replace("\r", String.Empty);
                var targetPath = Path.Combine(tempPath.DirectoryPath, "Web.config");
                File.WriteAllText(targetPath, @"<configuration>
    <appSettings>
        <add key=""Environment"" value=""Dev"" />
    </appSettings>
</configuration>");

                await CommandTestBuilder.CreateAsync <MyCommand, MyProgram>()
                .WithArrange(context =>
                {
                    context.Variables.Add(KnownVariables.Package.EnabledFeatures, KnownVariables.Features.ConfigurationTransforms + "," + KnownVariables.Features.ConfigurationVariables);
                    context.Variables.Add(KnownVariables.Package.AutomaticallyUpdateAppSettingsAndConnectionStrings, "true");
                    context.Variables.Add("Environment", "Test");
                    context.WithFilesToCopy(tempPath.DirectoryPath);
                })
                .WithAssert(result =>
                {
                    File.ReadAllText(targetPath).Replace("\r", String.Empty).Should().Be(expected);
                })
                .Execute();
            }
        }
Exemplo n.º 15
0
        public void EnumerateFolder2(GlobOptions options)
        {
            using var directory = TemporaryDirectory.Create();
            directory.CreateEmptyFile("d1/d2/f1.txt");
            directory.CreateEmptyFile("d1/d2/f2.txt");
            directory.CreateEmptyFile("d1/f3.txt");

            var glob = Glob.Parse("d1/*.txt", options);

            TestEvaluate(directory, glob, new[] { "d1/f3.txt" });
        }
Exemplo n.º 16
0
        public void DisposedDeletedDirectory()
        {
            FullPath path;

            using (var dir = TemporaryDirectory.Create())
            {
                path = dir.FullPath;
                File.WriteAllText(dir.GetFullPath("a.txt"), "content");
            }

            Assert.False(Directory.Exists(path));
        }
Exemplo n.º 17
0
        IEnumerable <string> ExecuteAndReturnLogOutput(Action <VariableDictionary> populateVariables, string folderName, params Type[] commandTypes)
        {
            void Copy(string sourcePath, string destinationPath)
            {
                foreach (var dirPath in Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
                }

                foreach (var newPath in Directory.EnumerateFiles(sourcePath, "*.*", SearchOption.AllDirectories))
                {
                    File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
                }
            }

            using (var currentDirectory = TemporaryDirectory.Create())
            {
                var variablesFile = Path.GetTempFileName();
                var variables     = new VariableDictionary();
                variables.Set(TerraformSpecialVariables.Calamari.TerraformCliPath, Path.GetDirectoryName(customTerraformExecutable));
                variables.Set(SpecialVariables.OriginalPackageDirectoryPath, currentDirectory.DirectoryPath);
                variables.Set(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable, customTerraformExecutable);

                populateVariables(variables);

                var terraformFiles = TestEnvironment.GetTestPath("Terraform", folderName);

                Copy(terraformFiles, currentDirectory.DirectoryPath);

                variables.Save(variablesFile);

                using (new TemporaryFile(variablesFile))
                {
                    foreach (var commandType in commandTypes)
                    {
                        var sb = new StringBuilder();
                        Log.StdOut = new IndentedTextWriter(new StringWriter(sb));

                        var command = (ICommand)Activator.CreateInstance(commandType);
                        var result  = command.Execute(new[] { "--variables", $"{variablesFile}" });

                        result.Should().Be(0);

                        var output = sb.ToString();

                        Console.WriteLine(output);

                        yield return(output);
                    }
                }
            }
        }
Exemplo n.º 18
0
        public Task ExecuteCommand()
        {
            // I can create content to be copied, this bypasses the extracting package
            using var tempPath = TemporaryDirectory.Create();
            File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "PreDeploy.ps1"), "echo \"Hello from PreDeploy\"");

            return(CommandTestBuilder.CreateAsync <MyCommand, Program>()
                   .WithArrange(context =>
            {
                context.Variables.Add("MyVariable", "MyValue");
                context.WithFilesToCopy(tempPath.DirectoryPath);
            })
                   .Execute());
        }
 public void ExecutionUsingPodServiceAccount_WithoutServerCert()
 {
     variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString());
     variables.Set(PowerShellVariables.Edition, "Desktop");
     using (var dir = TemporaryDirectory.Create())
         using (var podServiceAccountToken = new TemporaryFile(Path.Combine(dir.DirectoryPath, "podServiceAccountToken")))
         {
             File.WriteAllText(podServiceAccountToken.FilePath, "podServiceAccountToken");
             redactMap[podServiceAccountToken.FilePath] = "<podServiceAccountTokenPath>";
             variables.Set("Octopus.Action.Kubernetes.PodServiceAccountTokenPath", podServiceAccountToken.FilePath);
             var wrapper = CreateWrapper();
             TestScriptInReadOnlyMode(wrapper).AssertSuccess();
         }
 }
            private static (string packagePath, string packageName, string packageVersion) PrepareZipPackage()
            {
                (string packagePath, string packageName, string packageVersion)packageinfo;

                var tempPath = TemporaryDirectory.Create();

                new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage");
                File.WriteAllText(Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"),
                                  "Hello #{Greeting}");

                packageinfo.packagePath    = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.zip";
                packageinfo.packageVersion = "1.0.0";
                packageinfo.packageName    = "AzureZipDeployPackage";
                ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath);
                return(packageinfo);
            }
Exemplo n.º 21
0
        public void AuthorisingWithPodServiceAccountToken()
        {
            variables.Set(SpecialVariables.ClusterUrl, aksClusterHost);

            using (var dir = TemporaryDirectory.Create())
                using (var podServiceAccountToken = new TemporaryFile(Path.Combine(dir.DirectoryPath, "podServiceAccountToken")))
                    using (var certificateAuthority = new TemporaryFile(Path.Combine(dir.DirectoryPath, "certificateAuthority")))
                    {
                        File.WriteAllText(podServiceAccountToken.FilePath, aksPodServiceAccountToken);
                        File.WriteAllText(certificateAuthority.FilePath, aksClusterCaCertificate);
                        variables.Set("Octopus.Action.Kubernetes.PodServiceAccountTokenPath", podServiceAccountToken.FilePath);
                        variables.Set("Octopus.Action.Kubernetes.CertificateAuthorityPath", certificateAuthority.FilePath);
                        var wrapper = CreateWrapper();
                        TestScriptAndVerifyCluster(wrapper, "Test-Script");
                    }
        }
 public void ExecutionWithCustomKubectlExecutable_FileExists()
 {
     variables.Set(ScriptVariables.Syntax, ScriptSyntax.PowerShell.ToString());
     variables.Set(PowerShellVariables.Edition, "Desktop");
     variables.Set(Deployment.SpecialVariables.Account.AccountType, "Token");
     variables.Set(Deployment.SpecialVariables.Account.Token, ClusterToken);
     using (var dir = TemporaryDirectory.Create())
         using (var tempExe = new TemporaryFile(Path.Combine(dir.DirectoryPath, "mykubectl.exe")))
         {
             File.WriteAllText(tempExe.FilePath, string.Empty);
             variables.Set("Octopus.Action.Kubernetes.CustomKubectlExecutable", tempExe.FilePath);
             redactMap[tempExe.FilePath] = "<customkubectl>";
             var wrapper = CreateWrapper();
             TestScriptInReadOnlyMode(wrapper).AssertSuccess();
         }
 }
        protected void TestScript(IScriptWrapper wrapper, string scriptName)
        {
            using (var dir = TemporaryDirectory.Create())
            {
                var folderPath = Path.Combine(dir.DirectoryPath, "Folder with spaces");

                using (var temp = new TemporaryFile(Path.Combine(folderPath, $"{scriptName}.{(variables.Get(ScriptVariables.Syntax) == ScriptSyntax.Bash.ToString() ? "sh" : "ps1")}")))
                {
                    Directory.CreateDirectory(folderPath);
                    File.WriteAllText(temp.FilePath, $"echo running target script...");

                    var output = ExecuteScript(wrapper, temp.FilePath);
                    output.AssertSuccess();
                }
            }
        }
Exemplo n.º 24
0
        public void BundledCliIsTheCorrectVersion()
        {
            using var tempDir = TemporaryDirectory.Create();
            ZipFile.ExtractToDirectory("Octopus.Dependencies.TerraformCLI.nupkg", tempDir.DirectoryPath);

            var terraformExePath = Path.Combine(tempDir.DirectoryPath,
                                                "contentFiles",
                                                "any",
                                                "win",
                                                "terraform.exe");
            var log    = new InMemoryLog();
            var result = new CommandLineRunner(log, new CalamariVariables()).Execute(new CommandLineInvocation(terraformExePath, "--version"));

            result.ExitCode.Should().Be(0);

            log.StandardOut.Should().Contain($"Terraform v{TerraformVersion}");
        }
        public async Task Deploy_WebApp_Preserve_Files()
        {
            var webAppName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60);

            var webApp = await CreateWebApp(webAppName);

            using var tempPath = TemporaryDirectory.Create();
            const string actualText = "Hello World";

            Directory.CreateDirectory(Path.Combine(tempPath.DirectoryPath, "Keep"));
            Directory.CreateDirectory(Path.Combine(tempPath.DirectoryPath, "NotKeep"));
            File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "Keep", "index.html"), actualText);
            File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "NotKeep", "index.html"), actualText);

            await CommandTestBuilder.CreateAsync <DeployAzureWebCommand, Program>()
            .WithArrange(context =>
            {
                AddDefaults(context, webAppName);

                context.WithFilesToCopy(tempPath.DirectoryPath);
            })
            .Execute();

            using var tempPath2 = TemporaryDirectory.Create();

            File.WriteAllText(Path.Combine(tempPath2.DirectoryPath, "newfile.html"), actualText);

            await CommandTestBuilder.CreateAsync <DeployAzureWebCommand, Program>()
            .WithArrange(context =>
            {
                AddDefaults(context, webAppName);
                context.Variables.Add(SpecialVariables.Action.Azure.RemoveAdditionalFiles, bool.TrueString);
                context.Variables.Add(SpecialVariables.Action.Azure.PreservePaths, "\\\\Keep;\\\\Keep\\\\index.html");

                context.WithFilesToCopy(tempPath2.DirectoryPath);
            })
            .Execute();

            await AssertContent(webApp.DefaultHostName, actualText, "Keep");
            await AssertContent(webApp.DefaultHostName, actualText, "newfile.html");

            var response = await client.GetAsync($"https://{webApp.DefaultHostName}/NotKeep");

            response.IsSuccessStatusCode.Should().BeFalse();
            response.StatusCode.Should().Be(HttpStatusCode.NotFound);
        }
            public async Task CanDeployNugetPackage()
            {
                (string packagePath, string packageName, string packageVersion)packageinfo;
                greeting = "nuget";

                var tempPath = TemporaryDirectory.Create();

                new DirectoryInfo(tempPath.DirectoryPath).CreateSubdirectory("AzureZipDeployPackage");

                var doc = new XDocument(new XElement("package",
                                                     new XAttribute("xmlns", @"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"),
                                                     new XElement("metadata",
                                                                  new XElement("id", "AzureZipDeployPackage"),
                                                                  new XElement("version", "1.0.0"),
                                                                  new XElement("title", "AzureZipDeployPackage"),
                                                                  new XElement("authors", "Chris Thomas"),
                                                                  new XElement("description", "Test Package used to test nuget package deployments")
                                                                  )
                                                     ));

                await Task.Run(() => File.WriteAllText(
                                   Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "index.html"),
                                   "Hello #{Greeting}"));

                using (var writer = new XmlTextWriter(
                           Path.Combine($"{tempPath.DirectoryPath}/AzureZipDeployPackage", "AzureZipDeployPackage.nuspec"),
                           Encoding.UTF8))
                {
                    doc.Save(writer);
                }

                packageinfo.packagePath    = $"{tempPath.DirectoryPath}/AzureZipDeployPackage.1.0.0.nupkg";
                packageinfo.packageVersion = "1.0.0";
                packageinfo.packageName    = "AzureZipDeployPackage";
                ZipFile.CreateFromDirectory($"{tempPath.DirectoryPath}/AzureZipDeployPackage", packageinfo.packagePath);

                await CommandTestBuilder.CreateAsync <DeployAzureAppServiceCommand, Program>().WithArrange(context =>
                {
                    context.WithPackage(packageinfo.packagePath, packageinfo.packageName, packageinfo.packageVersion);
                    AddVariables(context);
                }).Execute();

                //await new AzureAppServiceBehaviour(new InMemoryLog()).Execute(runningContext);
                await AssertContent($"{site.Name}.azurewebsites.net", $"Hello {greeting}");
            }
Exemplo n.º 27
0
        public async Task AssertStagedPackageIsExtracted()
        {
            using (var tempPath = TemporaryDirectory.Create())
            {
                File.WriteAllText(Path.Combine(tempPath.DirectoryPath, "Hello.html"), "Hello World!");

                await CommandTestBuilder.CreateAsync <MyCommand, MyProgram>()
                .WithArrange(context =>
                {
                    context.WithNewNugetPackage(tempPath.DirectoryPath, "MyPackage", "1.0.0");
                })
                .WithAssert(result =>
                {
                    File.Exists(Path.Combine(tempPath.DirectoryPath, "Hello.html")).Should().BeTrue();
                })
                .Execute();
            }
        }
Exemplo n.º 28
0
        public async Task ResolveSymlink_DirectoryRelativePath()
        {
            await using var temp = TemporaryDirectory.Create();
            var path = temp.CreateDirectory("a");

            Assert.False(path.IsSymbolicLink());
            Assert.False(path.TryGetSymbolicLinkTarget(out _));

            // Create symlink
            var symlink = temp.GetFullPath("b");

            CreateSymlink(symlink, "a", SymbolicLink.Directory | SymbolicLink.AllowUnpriviledgedCreate);

            Assert.True(Directory.Exists(symlink), "Directory does not exist");
            Assert.True(symlink.IsSymbolicLink(), "IsSymbolicLink should be true");
            Assert.True(symlink.TryGetSymbolicLinkTarget(out var target), "TryGetSymbolicLinkTarget should be true");
            Assert.Equal(path, target);
        }
Exemplo n.º 29
0
        public async Task ResolveSymlink_FileAbsolutePath()
        {
            await using var temp = TemporaryDirectory.Create();
            var path = temp.CreateEmptyFile("a.txt");

            Assert.False(path.IsSymbolicLink());
            Assert.False(path.TryGetSymbolicLinkTarget(out _));

            // Create symlink
            var symlink = temp.GetFullPath("b.txt");

            CreateSymlink(symlink, path, SymbolicLink.File | SymbolicLink.AllowUnpriviledgedCreate);

            Assert.True(File.Exists(symlink), "File does not exist");
            Assert.True(symlink.IsSymbolicLink(), "IsSymbolicLink should be true");
            Assert.True(symlink.TryGetSymbolicLinkTarget(out var target), "TryGetSymbolicLinkTarget should be true");
            Assert.Equal(path, target);
        }
Exemplo n.º 30
0
        IEnumerable <string> ExecuteAndReturnLogOutput(Action <VariableDictionary> populateVariables, string folderName, params Type[] commandTypes)
        {
            void Copy(string sourcePath, string destinationPath)
            {
                foreach (var dirPath in Directory.EnumerateDirectories(sourcePath, "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
                }

                foreach (var newPath in Directory.EnumerateFiles(sourcePath, "*.*", SearchOption.AllDirectories))
                {
                    File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
                }
            }

            using (var currentDirectory = TemporaryDirectory.Create())
            {
                var variables = new CalamariVariables();
                variables.Set(TerraformSpecialVariables.Calamari.TerraformCliPath, Path.GetDirectoryName(customTerraformExecutable));
                variables.Set(KnownVariables.OriginalPackageDirectoryPath, currentDirectory.DirectoryPath);
                variables.Set(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable, customTerraformExecutable);

                populateVariables(variables);

                var terraformFiles = TestEnvironment.GetTestPath("Terraform", folderName);

                Copy(terraformFiles, currentDirectory.DirectoryPath);

                foreach (var commandType in commandTypes)
                {
                    var log     = new InMemoryLog();
                    var command = CreateInstance(commandType, variables, log);
                    var result  = command.Execute(new string[0]);

                    result.Should().Be(0);

                    var output = log.StandardOut.Join(Environment.NewLine);

                    Console.WriteLine(output);

                    yield return(output);
                }
            }
        }