Ejemplo n.º 1
0
        public void Constructor_DetectsExcessiveDepth()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                const int MaxDepth = 50;
                var copy = new Dictionary<string, string>();
                copy[$"variable{MaxDepth + 1}"] = "Final value"; // Variable 51.
                for (int i = 1 ; i <= MaxDepth ; i++)
                {
                    copy[$"variable{i}"] = $"$(variable{i + 1})"; // Variables 1-50.
                }

                // Act.
                List<string> warnings;
                var variables = new Variables(hc, copy, new List<MaskHint>(), out warnings);

                // Assert.
                Assert.Equal(1, warnings.Count);
                Assert.Equal(warnings[0], StringUtil.Loc("Variable0ExceedsMaxDepth1", "variable1", MaxDepth));
                Assert.Equal("$(variable2)", variables.Get("variable1")); // Variable 1.
                for (int i = 2; i <= MaxDepth + 1; i++)
                {
                    Assert.Equal("Final value", variables.Get($"variable{i}")); // Variables 2-51.
                }
            }
        }
Ejemplo n.º 2
0
        public void ReturnsCorrectHashKey()
        {
            using (TestHostContext tc = new TestHostContext(this))
            {
                // Arrange.
                var executionContext = new Mock<IExecutionContext>();
                List<string> warnings;
                executionContext
                    .Setup(x => x.Variables)
                    .Returns(new Variables(tc, copy: new Dictionary<string, string>(), maskHints: new List<MaskHint>(), warnings: out warnings));
                executionContext.Object.Variables.Set(Constants.Variables.System.CollectionId, "7aee6dde-6381-4098-93e7-50a8264cf066");
                executionContext.Object.Variables.Set(Constants.Variables.System.DefinitionId, "7");
                var endpoint = new ServiceEndpoint
                {
                    Url = new Uri("http://contoso:8080/tfs/DefaultCollection/gitTest/_git/gitTest"),
                };
                var sourceProvider = new ConcreteSourceProvider();
                sourceProvider.Initialize(tc);

                // Act.
                string hashKey = sourceProvider.GetBuildDirectoryHashKey(executionContext.Object, endpoint);

                // Assert.
                Assert.Equal("5c5c3d7ac33cca6604736eb3af977f23f1cf1146", hashKey);
            }
        }
Ejemplo n.º 3
0
        public void Constructor_AppliesMaskHints()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                var copy = new Dictionary<string, string>
                {
                    { "MySecretName", "My secret value" },
                    { "MyPublicVariable", "My public value" },
                };
                var maskHints = new List<MaskHint>
                {
                    new MaskHint() { Type = MaskType.Variable, Value = "MySecretName" },
                };
                List<string> warnings;
                var variables = new Variables(hc, copy, maskHints, out warnings);

                // Act.
                KeyValuePair<string, string>[] publicVariables = variables.Public.ToArray();

                // Assert.
                Assert.Equal(0, warnings.Count);
                Assert.Equal(1, publicVariables.Length);
                Assert.Equal("MyPublicVariable", publicVariables[0].Key);
                Assert.Equal("My public value", publicVariables[0].Value);
                Assert.Equal("My secret value", variables.Get("MySecretName"));
            }
        }
Ejemplo n.º 4
0
        public void VerifyUserAgentIsVstsAgent()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Act.
                var connect = ApiUtil.CreateConnection(new Uri("https://github.com/Microsoft/vsts-agent"), new VssCredentials());

                // Trace
                foreach (var ua in connect.Settings.UserAgent ?? new List<ProductInfoHeaderValue>())
                {
                    if (ua.Product != null)
                    {
                        trace.Info(ua.Product.Name);
                        trace.Info(ua.Product.Version);
                    }

                    if (!string.IsNullOrEmpty(ua.Comment))
                    {
                        trace.Info(ua.Comment);
                    }
                }

                // Assert.
                Assert.True(connect.Settings.UserAgent?.Exists(u => u.Product.Name.IndexOf("vstsagentcore", StringComparison.OrdinalIgnoreCase) >= 0));
            }
        }
Ejemplo n.º 5
0
        public void Delete_DeletesFile()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a file.
                string directory = Path.Combine(IOUtil.GetBinPath(), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act.
                    IOUtil.Delete(file, CancellationToken.None);

                    // Assert.
                    Assert.False(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public void FormatAlwaysCallsFormat()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange.
                var variableSets = new[]
                {
                    new { Format = null as string, Args = null as object[], Expected = string.Empty },
                    new { Format = null as string, Args = new object[0], Expected = string.Empty },
                    new { Format = null as string, Args = new object[] { 123 }, Expected = string.Empty },
                    new { Format = "Some message", Args = null as object[], Expected = "Some message" },
                    new { Format = "Some message", Args = new object[0], Expected = "Some message" },
                    new { Format = "Some message", Args = new object[] { 123 }, Expected = "Some message" },
                    new { Format = "Some format '{0}'", Args = null as object[], Expected = "Some format ''" },
                    new { Format = "Some format '{0}'", Args = new object[0], Expected = "Some format ''" },
                    new { Format = "Some format '{0}'", Args = new object[] { 123 }, Expected = "Some format '123'" },
                };
                foreach (var variableSet in variableSets)
                {
                    trace.Info($"{nameof(variableSet)}:");
                    trace.Info(variableSet);

                    // Act.
                    string actual = StringUtil.Format(variableSet.Format, variableSet.Args);

                    // Assert.
                    Assert.Equal(variableSet.Expected, actual);
                }
            }
        }
Ejemplo n.º 7
0
        public void DeleteDirectory_DeletesDirectoriesRecursively()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a grandchild directory.
                string directory = Path.Combine(IOUtil.GetBinPath(), Path.GetRandomFileName());
                try
                {
                    Directory.CreateDirectory(Path.Combine(directory, "some child directory", "some grandchild directory"));

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // Assert.
                    Assert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void FormatHandlesFormatException()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange.
                var variableSets = new[]
                {
                    new { Format = "Bad format { 0}", Args = null as object[], Expected = "Bad format { 0}" },
                    new { Format = "Bad format { 0}", Args = new object[0], Expected = "Bad format { 0} " },
                    new { Format = "Bad format { 0}", Args = new object[] { null }, Expected = "Bad format { 0} " },
                    new { Format = "Bad format { 0}", Args = new object[] { 123, 456 }, Expected = "Bad format { 0} 123, 456" },
                };
                foreach (var variableSet in variableSets)
                {
                    trace.Info($"{nameof(variableSet)}:");
                    trace.Info(variableSet);

                    // Act.
                    string actual = StringUtil.Format(variableSet.Format, variableSet.Args);

                    // Assert.
                    Assert.Equal(variableSet.Expected, actual);
                }
            }
        }
Ejemplo n.º 9
0
        public async Task TestCancel()
        {
            const int SecondsToRun = 20;
            using (TestHostContext hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                Tracing trace = hc.GetTrace();
                var processInvoker = new ProcessInvoker();
                processInvoker.Initialize(hc);
                Stopwatch watch = Stopwatch.StartNew();
#if OS_WINDOWS
                Task execTask = processInvoker.ExecuteAsync("", "cmd.exe", $"/c \"choice /T {SecondsToRun} /D y\"", null, tokenSource.Token);
#endif
#if (OS_OSX || OS_LINUX)
                Task execTask = processInvoker.ExecuteAsync("", "bash", $"-c \"sleep {SecondsToRun}s\"", null, tokenSource.Token);
#endif
                await Task.Delay(500);
                tokenSource.Cancel();
                await Task.WhenAny(execTask);
                Assert.True(execTask.IsCompleted);
                Assert.True(!execTask.IsFaulted);
                Assert.True(execTask.IsCanceled);
                watch.Stop();
                var elapsedSeconds = watch.ElapsedMilliseconds / 1000;
                //if cancellation fails, then execution time is more than 10 seconds
                Assert.True(elapsedSeconds < SecondsToRun / 2, $"cancellation failed, because task took too long to run. {elapsedSeconds}");
            }
        }
Ejemplo n.º 10
0
        public void Constructor_DetectsAdjacentCyclicalReference()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                var copy = new Dictionary<string, string>
                {
                    { "variable1", "1_$(variable2)" },
                    { "variable2", "2_$(variable3)" },
                    { "variable3", "3_$(variable2)" },
                };

                // Act.
                List<string> warnings;
                var variables = new Variables(hc, copy, new List<MaskHint>(), out warnings);

                // Assert.
                Assert.Equal(3, warnings.Count);
                Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable1"))));
                Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable2"))));
                Assert.True(warnings.Any(x => string.Equals(x, StringUtil.Loc("Variable0ContainsCyclicalReference", "variable3"))));
                Assert.Equal("1_$(variable2)", variables.Get("variable1"));
                Assert.Equal("2_$(variable3)", variables.Get("variable2"));
                Assert.Equal("3_$(variable2)", variables.Get("variable3"));
            }
        }
 public void NonEmptyValidator()
 {
     using (TestHostContext hc = new TestHostContext(this))
     {
         Assert.True(Validators.NonEmptyValidator("test"));
         Assert.False(Validators.NonEmptyValidator(string.Empty));
     }
 }
 public void WindowsLogonAccountValidator()
 {
     using (TestHostContext hc = new TestHostContext(this))
     {
         Assert.False(Validators.NTAccountValidator(string.Empty));
         Assert.True(Validators.NTAccountValidator("NT AUTHORITY\\LOCAL SERVICE"));
     }
 }
 private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
 {
     TestHostContext tc = new TestHostContext(this, testName);
     tc.SetSingleton<IProcessInvoker>(_processInvoker.Object);
     tc.SetSingleton<IPromptManager>(_promptManager.Object);
     tc.SetSingleton<INativeWindowsServiceHelper>(_windowsServiceHelper.Object);
     return tc;
 }
 public void AuthSchemeValidator()
 {
     using (TestHostContext hc = new TestHostContext(this))
     {
         Assert.True(Validators.AuthSchemeValidator("pat"));
         Assert.False(Validators.AuthSchemeValidator("Fail"));
     }
 }
Ejemplo n.º 15
0
 private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
 {
     TestHostContext tc = new TestHostContext(this, testName);
     tc.SetSingleton<IConfigurationManager>(_config.Object);
     tc.SetSingleton<IAgentServer>(_agentServer.Object);
     tc.SetSingleton<ICredentialManager>(_credMgr.Object);
     tc.SetSingleton<ICapabilitiesManager>(_capabilitiesManager.Object);
     return tc;
 }
 public void ServerUrlValidator()
 {
     using (TestHostContext hc = new TestHostContext(this))
     {
         Assert.True(Validators.ServerUrlValidator("http://servername"));
         Assert.False(Validators.ServerUrlValidator("Fail"));
         Assert.False(Validators.ServerUrlValidator("ftp://servername"));
     }
 }
Ejemplo n.º 17
0
        public void WriteAndShipLog()
        {
            CleanLogFolder();

            try
            {
                //Arrange
                using (var hc = new TestHostContext(this))
                {
                    var pagingLogger = new PagingLogger();
                    hc.SetSingleton<IJobServerQueue>(_jobServerQueue.Object);
                    pagingLogger.Initialize(hc);
                    Guid timeLineId = Guid.NewGuid();
                    Guid timeLineRecordId = Guid.NewGuid();
                    int totalBytes = PagesToWrite * PagingLogger.PageSize;
                    int bytesWritten = 0;
                    int logDataSize = System.Text.Encoding.UTF8.GetByteCount(LogData);
                    _jobServerQueue.Setup(x => x.QueueFileUpload(timeLineId, timeLineRecordId, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true))
                        .Callback((Guid timelineId, Guid timelineRecordId, string type, string name, string path, bool deleteSource) =>
                        {
                            bool fileExists = File.Exists(path);
                            Assert.True(fileExists);

                            using (var freader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read), System.Text.Encoding.UTF8))
                            {
                                string line;
                                while ((line = freader.ReadLine()) != null)
                                {
                                    Assert.True(line.EndsWith(LogData));
                                    bytesWritten += logDataSize;
                                }
                            }
                            File.Delete(path);
                        });

                    //Act
                    int bytesSent = 0;
                    pagingLogger.Setup(timeLineId, timeLineRecordId);
                    while (bytesSent < totalBytes)
                    {
                        pagingLogger.Write(LogData);
                        bytesSent += logDataSize;
                    }
                    pagingLogger.End();

                    //Assert
                    _jobServerQueue.Verify(x => x.QueueFileUpload(timeLineId, timeLineRecordId, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true), Times.AtLeast(PagesToWrite));
                    Assert.Equal(bytesSent, bytesWritten);
                }
            }
            finally
            {
                //cleanup
                CleanLogFolder();
            }
        }
Ejemplo n.º 18
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            TestHostContext tc = new TestHostContext(this, testName);
            tc.SetSingleton<ICredentialManager>(_credMgr.Object);
            tc.SetSingleton<IPromptManager>(_promptManager.Object);
            tc.SetSingleton<IConfigurationStore>(_store.Object);
            tc.EnqueueInstance<IAgentServer>(_agentServer.Object);

            return tc;
        }
Ejemplo n.º 19
0
        public void Equal_MatchesObjectEquality()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange.
                string expected = "Some string".ToLower();  // ToLower is required to avoid reference equality
                string actual = "Some string".ToLower();    // due to compile-time string interning.

                // Act/Assert.
                ArgUtil.Equal(expected: expected, actual: actual, name: "Some parameter");
            }
        }
Ejemplo n.º 20
0
        public void Equal_MatchesStructEquality()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange.
                int expected = 123;
                int actual = expected;

                // Act/Assert.
                ArgUtil.Equal(expected: expected, actual: actual, name: "Some parameter");
            }
        }
Ejemplo n.º 21
0
        public async void DispatchRunNewJob()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                var worker = new Microsoft.VisualStudio.Services.Agent.Worker.Worker();
                hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
                hc.SetSingleton<IJobRunner>(_jobRunner.Object);
                worker.Initialize(hc);
                var jobMessage = CreateJobRequestMessage("job1");
                var arWorkerMessages = new WorkerMessage[]
                    {
                        new WorkerMessage
                        {
                            Body = JsonUtility.ToString(jobMessage),
                            MessageType = MessageType.NewJobRequest
                        }
                    };
                var workerMessages = new Queue<WorkerMessage>(arWorkerMessages);

                _processChannel
                    .Setup(x => x.ReceiveAsync(It.IsAny<CancellationToken>()))
                    .Returns(async () =>
                    {
                        // Return the job message.
                        if (workerMessages.Count > 0)
                        {
                            return workerMessages.Dequeue();
                        }

                        // Wait for the text to run
                        await Task.Delay(-1, tokenSource.Token);
                        return default(WorkerMessage);
                    });
                _jobRunner.Setup(x => x.RunAsync(It.IsAny<JobRequestMessage>(), It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<TaskResult>(TaskResult.Succeeded));

                //Act
                await worker.RunAsync(pipeIn: "1", pipeOut: "2");

                //Assert
                _processChannel.Verify(x => x.StartClient("1", "2"), Times.Once());
                _jobRunner.Verify(x => x.RunAsync(
                    It.Is<JobRequestMessage>(y => JsonUtility.ToString(y) == arWorkerMessages[0].Body), It.IsAny<CancellationToken>()));
                tokenSource.Cancel();
            }
        }
Ejemplo n.º 22
0
 private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
 {
     var hc = new TestHostContext(this, testName);
     List<string> warnings;
     _variables = new Variables(
         hostContext: hc,
         copy: new Dictionary<string, string>(),
         maskHints: new List<MaskHint>(),
         warnings: out warnings);
     _ec = new Mock<IExecutionContext>();
     _ec.SetupAllProperties();
     _ec.Setup(x => x.Variables).Returns(_variables);
     _stepsRunner = new StepsRunner();
     _stepsRunner.Initialize(hc);
     return hc;
 }
Ejemplo n.º 23
0
        public void VerifyUserAgentHasPlatformInfo()
        {
            Regex _serverSideAgentPlatformMatchingRegex = new Regex("vstsagentcore-(.+)(?=/)", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Act.
                var connect = ApiUtil.CreateConnection(new Uri("https://github.com/Microsoft/vsts-agent"), new VssCredentials());

                string platformInfo = null;
                // Trace
                foreach (var ua in connect.Settings.UserAgent ?? new List<ProductInfoHeaderValue>())
                {
                    if (ua.Product != null)
                    {
                        trace.Info(ua.Product.Name);
                        trace.Info(ua.Product.Version);

                        if (ua.Product.Name.IndexOf("vstsagentcore", StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            platformInfo = ua.Product.Name + '/' + ua.Product.Version;
                        }
                    }

                    if (!string.IsNullOrEmpty(ua.Comment))
                    {
                        trace.Info(ua.Comment);
                    }
                }

                // Assert.
                var regMatch = _serverSideAgentPlatformMatchingRegex.Match(platformInfo);
                Assert.True(regMatch.Success && regMatch.Groups != null && regMatch.Groups.Count == 2);
                string platform = regMatch.Groups[1].Value;
                List<string> validPackageNames = new List<string>()
                {
                    "win7-x64",
                    "ubuntu.14.04-x64",
                    "centos.7-x64",
                    "rhel.7.2-x64",
                    "osx.10.11-x64"
                };
                Assert.True(validPackageNames.Contains(platform));
            }
        }
Ejemplo n.º 24
0
        public void TaskResultReturnCodeTranslate()
        {
            // Arrange.
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Act.
                TaskResult abandon = TaskResultUtil.TranslateFromReturnCode(TaskResultUtil.TranslateToReturnCode(TaskResult.Abandoned));
                // Actual
                Assert.Equal(TaskResult.Abandoned, abandon);

                // Act.
                TaskResult canceled = TaskResultUtil.TranslateFromReturnCode(TaskResultUtil.TranslateToReturnCode(TaskResult.Canceled));
                // Actual
                Assert.Equal(TaskResult.Canceled, canceled);

                // Act.
                TaskResult failed = TaskResultUtil.TranslateFromReturnCode(TaskResultUtil.TranslateToReturnCode(TaskResult.Failed));
                // Actual
                Assert.Equal(TaskResult.Failed, failed);

                // Act.
                TaskResult skipped = TaskResultUtil.TranslateFromReturnCode(TaskResultUtil.TranslateToReturnCode(TaskResult.Skipped));
                // Actual
                Assert.Equal(TaskResult.Skipped, skipped);

                // Act.
                TaskResult succeeded = TaskResultUtil.TranslateFromReturnCode(TaskResultUtil.TranslateToReturnCode(TaskResult.Succeeded));
                // Actual
                Assert.Equal(TaskResult.Succeeded, succeeded);

                // Act.
                TaskResult succeededWithIssues = TaskResultUtil.TranslateFromReturnCode(TaskResultUtil.TranslateToReturnCode(TaskResult.SucceededWithIssues));
                // Actual
                Assert.Equal(TaskResult.SucceededWithIssues, succeededWithIssues);

                // Act.
                TaskResult unknowReturnCode1 = TaskResultUtil.TranslateFromReturnCode(0);
                // Actual
                Assert.Equal(TaskResult.Failed, unknowReturnCode1);

                // Act.
                TaskResult unknowReturnCode2 = TaskResultUtil.TranslateFromReturnCode(1);
                // Actual
                Assert.Equal(TaskResult.Failed, unknowReturnCode2);
            }
        }
Ejemplo n.º 25
0
        public void Equal_ThrowsWhenActualObjectIsNull()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange.
                object expected = new object();
                object actual = null;

                // Act/Assert.
                Assert.Throws<ArgumentOutOfRangeException>(() =>
                {
                    ArgUtil.Equal(expected: expected, actual: actual, name: "Some parameter");
                });
            }
        }
Ejemplo n.º 26
0
        public void UseWhichFindGit()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                //Arrange
                Tracing trace = hc.GetTrace();
                var whichTool = new WhichUtil();
                whichTool.Initialize(hc);

                // Act.
                string gitPath = whichTool.Which("git");

                trace.Info($"Which(\"git\") returns: {gitPath ?? string.Empty}");

                // Assert.
                Assert.True(!string.IsNullOrEmpty(gitPath) && File.Exists(gitPath), $"Unable to find Git through: {nameof(WhichUtil.Which)}");
            }
        }
Ejemplo n.º 27
0
        public async void DispatchesJobRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            { 
                var jobDispatcher = new JobDispatcher();
                hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);
                hc.SetSingleton<IAgentServer>(_agentServer.Object);

                hc.EnqueueInstance<IProcessChannel>(_processChannel.Object);
                hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);

                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings() { PoolId = 1 });
                jobDispatcher.Initialize(hc);

                var ts = new CancellationTokenSource();
                JobRequestMessage message = CreateJobRequestMessage();
                string strMessage = JsonUtility.ToString(message);

                _processInvoker.Setup(x => x.ExecuteAsync(It.IsAny<String>(), It.IsAny<String>(), "spawnclient 1 2", null, It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult<int>(56));

                _processChannel.Setup(x => x.StartServer(It.IsAny<StartProcessDelegate>()))
                    .Callback((StartProcessDelegate startDel) => { startDel("1","2"); });
                _processChannel.Setup(x => x.SendAsync(MessageType.NewJobRequest, It.Is<string>(s => s.Equals(strMessage)), It.IsAny<CancellationToken>()))
                    .Returns(Task.CompletedTask);

                var request = new TaskAgentJobRequest();
                PropertyInfo sessionIdProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(sessionIdProperty);
                sessionIdProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(request));

                _agentServer.Setup(x => x.FinishAgentRequestAsync(It.IsAny<int>(), It.IsAny<long>(), It.IsAny<Guid>(), It.IsAny<DateTime>(), It.IsAny<TaskResult>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<TaskAgentJobRequest>(new TaskAgentJobRequest()));


                //Actt
                jobDispatcher.Run(message);

                //Assert
                await jobDispatcher.WaitAsync(CancellationToken.None);
            }
        }
        public async void TestGetCapabilities()
        {
            using (var hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                // Arrange
                var provider = new AgentCapabilitiesProvider();
                provider.Initialize(hc);
                var settings = new AgentSettings() { AgentName = "IAmAgent007" };

                // Act
                List<Capability> capabilities = await provider.GetCapabilitiesAsync(settings, tokenSource.Token);

                // Assert
                Assert.NotNull(capabilities);
                Capability agentNameCapability = capabilities.SingleOrDefault(x => string.Equals(x.Name, "Agent.Name", StringComparison.Ordinal));
                Assert.NotNull(agentNameCapability);
                Assert.Equal("IAmAgent007", agentNameCapability.Value);
            }
        }
Ejemplo n.º 29
0
        public async Task SuccessExitsWithCodeZero()
        {
            using (TestHostContext hc = new TestHostContext(this))
            using (var tokenSource = new CancellationTokenSource())
            {
                Tracing trace = hc.GetTrace();

                Int32 exitCode = -1;
                var processInvoker = new ProcessInvoker();
                processInvoker.Initialize(hc);
#if OS_WINDOWS
                exitCode = await processInvoker.ExecuteAsync("", "cmd.exe", "/c \"dir >nul\"", null, tokenSource.Token);
#endif
#if (OS_OSX || OS_LINUX)
                exitCode = await processInvoker.ExecuteAsync("", "bash", "-c echo .", null, tokenSource.Token);
#endif

                trace.Info("Exit Code: {0}", exitCode);
                Assert.Equal(0, exitCode);
            }
        }
Ejemplo n.º 30
0
        public void FallsBackToDefaultWhenTrimmed()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                _terminal
                    .Setup(x => x.ReadLine())
                    .Returns(" ");
                _terminal
                    .Setup(x => x.ReadSecret())
                    .Throws<InvalidOperationException>();
                hc.SetSingleton(_terminal.Object);
                _promptManager.Initialize(hc);

                // Act.
                string actual = ReadValue(defaultValue: "Some default value");

                // Assert.
                Assert.Equal("Some default value", actual);
            }
        }
Ejemplo n.º 31
0
        public void AddIssue_CountWarningsErrors()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                // Arrange: Create a job request message.
                TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
                TimelineReference timeline          = new TimelineReference();
                Guid   jobId      = Guid.NewGuid();
                string jobName    = "some job name";
                var    jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary <string, VariableValue>(), new List <MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List <Pipelines.ActionStep>(), null, null);
                jobRequest.Resources.Repositories.Add(new Pipelines.RepositoryResource()
                {
                    Alias   = Pipelines.PipelineConstants.SelfAlias,
                    Id      = "github",
                    Version = "sha1"
                });
                jobRequest.ContextData["github"] = new Pipelines.ContextData.DictionaryContextData();

                // Arrange: Setup the paging logger.
                var pagingLogger   = new Mock <IPagingLogger>();
                var jobServerQueue = new Mock <IJobServerQueue>();
                jobServerQueue.Setup(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.IsAny <TimelineRecord>()));

                hc.EnqueueInstance(pagingLogger.Object);
                hc.SetSingleton(jobServerQueue.Object);

                var ec = new Runner.Worker.ExecutionContext();
                ec.Initialize(hc);

                // Act.
                ec.InitializeJob(jobRequest, CancellationToken.None);

                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Error, Message = "error"
                });

                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });
                ec.AddIssue(new Issue()
                {
                    Type = IssueType.Warning, Message = "warning"
                });

                ec.Complete();

                // Assert.
                jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.ErrorCount == 15)), Times.AtLeastOnce);
                jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.WarningCount == 14)), Times.AtLeastOnce);
                jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.Issues.Where(i => i.Type == IssueType.Error).Count() == 10)), Times.AtLeastOnce);
                jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.Issues.Where(i => i.Type == IssueType.Warning).Count() == 10)), Times.AtLeastOnce);
            }
        }
        public void CommandParserTest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                string  vso;
                Command test;
                Command verify;
                //##vso[area.event k1=v1;]msg
                vso  = "##vso[area.event k1=v1;]msg";
                test = new Command("area", "event")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Assert.True(Command.TryParse(vso, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //##vso[area.event]
                vso  = "##vso[area.event]";
                test = new Command("area", "event");
                Assert.True(Command.TryParse(vso, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //##vso[area.event k1=%3B=%0D=%0A=%5D;]%3B-%0D-%0A-%5D
                vso  = "##vso[area.event k1=%3B=%0D=%0A=%5D;]%3B-%0D-%0A-%5D";
                test = new Command("area", "event")
                {
                    Data = ";-\r-\n-]",
                };
                test.Properties.Add("k1", ";=\r=\n=]");
                Assert.True(Command.TryParse(vso, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //##vso[area.event k1=;k2=;]
                vso  = "##vso[area.event k1=;k2=;]";
                test = new Command("area", "event");
                test.Properties.Add("k1", "");
                test.Properties.Add("k2", null);
                Assert.True(Command.TryParse(vso, out verify));
                test = new Command("area", "event");
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //>>>   ##vso[area.event k1=;k2=;]
                vso  = ">>>   ##vso[area.event k1=v1;]msg";
                test = new Command("area", "event")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Assert.True(Command.TryParse(vso, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));
            }
        }
Ejemplo n.º 33
0
        public void CommandParserV2Test()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                string           message;
                ActionCommand    test;
                ActionCommand    verify;
                HashSet <string> commands = new HashSet <string>()
                {
                    "do-something"
                };
                //::do-something k1=v1;]msg
                message = "::do-something k1=v1,::msg";
                test    = new ActionCommand("do-something")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Assert.True(ActionCommand.TryParseV2(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //::do-something::
                message = "::do-something::";
                test    = new ActionCommand("do-something");
                Assert.True(ActionCommand.TryParseV2(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //::do-something k1=%3B=%0D=%0A=%5D;::%3B-%0D-%0A-%5D
                message = "::do-something k1=;=%2C=%0D=%0A=]=%3A,::;-%0D-%0A-]-:-,";
                test    = new ActionCommand("do-something")
                {
                    Data = ";-\r-\n-]-:-,",
                };
                test.Properties.Add("k1", ";=,=\r=\n=]=:");
                Assert.True(ActionCommand.TryParseV2(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //::do-something k1=,k2=,::
                message = "::do-something k1=,k2=,::";
                test    = new ActionCommand("do-something");
                Assert.True(ActionCommand.TryParseV2(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //::do-something k1=v1::
                message = "::do-something k1=v1::";
                test    = new ActionCommand("do-something");
                test.Properties.Add("k1", "v1");
                Assert.True(ActionCommand.TryParseV2(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //   ::do-something k1=v1,::
                message = "   ::do-something k1=v1,::msg";
                test    = new ActionCommand("do-something")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Assert.True(ActionCommand.TryParseV2(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                verify  = null;
                //   >>>   ::do-something k1=v1,::
                message = "   >>>   ::do-something k1=v1,::msg";
                Assert.False(ActionCommand.TryParseV2(message, commands, out verify));
            }
        }
Ejemplo n.º 34
0
 public TestTrace(TestHostContext testHostContext)
 {
     _trace = testHostContext.GetTrace();
 }
        private Tuple <Mock <ArgUtilInstanced>, MockAgentTaskPluginExecutionContext> setupMocksForGitLfsFetchTests(TestHostContext hostContext)
        {
            Mock <ArgUtilInstanced> argUtilInstanced = new Mock <ArgUtilInstanced>();

            argUtilInstanced.CallBase = true;
            argUtilInstanced.Setup(x => x.File(Path.Combine("agenthomedirectory", "externals", "git", "cmd", $"git.exe"), "gitPath")).Callback(() => { });
            argUtilInstanced.Setup(x => x.Directory("agentworkfolder", "agent.workfolder")).Callback(() => { });
            var context = new MockAgentTaskPluginExecutionContext(hostContext.GetTrace());

            context.Variables.Add("agent.homedirectory", "agenthomedirectory");
            context.Variables.Add("agent.workfolder", "agentworkfolder");

            return(Tuple.Create(argUtilInstanced, context));
        }
Ejemplo n.º 36
0
        public void CommandParserTest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                string           message;
                ActionCommand    test;
                ActionCommand    verify;
                HashSet <string> commands = new HashSet <string>()
                {
                    "do-something"
                };
                //##[do-something k1=v1;]msg
                message = "##[do-something k1=v1;]msg";
                test    = new ActionCommand("do-something")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Assert.True(ActionCommand.TryParse(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //##[do-something]
                message = "##[do-something]";
                test    = new ActionCommand("do-something");
                Assert.True(ActionCommand.TryParse(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //##[do-something k1=%3B=%0D=%0A=%5D;]%3B-%0D-%0A-%5D
                message = "##[do-something k1=%3B=%0D=%0A=%5D;]%3B-%0D-%0A-%5D";
                test    = new ActionCommand("do-something")
                {
                    Data = ";-\r-\n-]",
                };
                test.Properties.Add("k1", ";=\r=\n=]");
                Assert.True(ActionCommand.TryParse(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //##[do-something k1=;k2=;]
                message = "##[do-something k1=;k2=;]";
                test    = new ActionCommand("do-something");
                Assert.True(ActionCommand.TryParse(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));

                message = "";
                test    = null;
                verify  = null;
                //>>>   ##[do-something k1=;k2=;]
                message = ">>>   ##[do-something k1=v1;]msg";
                test    = new ActionCommand("do-something")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Assert.True(ActionCommand.TryParse(message, commands, out verify));
                Assert.True(IsEqualCommand(hc, test, verify));
            }
        }
Ejemplo n.º 37
0
        public async Task SetsJobResultCorrectly()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                // Arrange.
                var variableSets = new[]
                {
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Abandoned) },
                        Expected = TaskResult.Succeeded
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Canceled) },
                        Expected = TaskResult.Succeeded
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded) },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, condition: "succeededOrFailed()") },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, isFinally: true) },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Failed) },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Succeeded) },
                        Expected = TaskResult.SucceededWithIssues
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Failed, continueOnError: true, critical: true), CreateStep(TaskResult.Succeeded) },
                        Expected = TaskResult.SucceededWithIssues
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Skipped) },
                        Expected = TaskResult.Succeeded
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Succeeded) },
                        Expected = TaskResult.Succeeded
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Succeeded), CreateStep(TaskResult.Failed) },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.Succeeded), CreateStep(TaskResult.SucceededWithIssues) },
                        Expected = TaskResult.SucceededWithIssues
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.SucceededWithIssues), CreateStep(TaskResult.Succeeded) },
                        Expected = TaskResult.SucceededWithIssues
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(TaskResult.SucceededWithIssues), CreateStep(TaskResult.Failed) },
                        Expected = TaskResult.Failed
                    },
                    //  Abandoned
                    //  Canceled
                    //  Failed
                    //  Skipped
                    //  Succeeded
                    //  SucceededWithIssues
                };
                foreach (var variableSet in variableSets)
                {
                    _ec.Object.Result = null;

                    // Act.
                    await _stepsRunner.RunAsync(
                        jobContext : _ec.Object,
                        steps : variableSet.Steps.Select(x => x.Object).ToList());

                    // Assert.
                    Assert.True(
                        variableSet.Expected == (_ec.Object.Result ?? TaskResult.Succeeded),
                        $"Expected '{variableSet.Expected}'. Actual '{_ec.Object.Result}'. Steps: {FormatSteps(variableSet.Steps)}");
                }
            }
        }
Ejemplo n.º 38
0
        public void TaskResultsMerge()
        {
            // Arrange.
            using (TestHostContext hc = new TestHostContext(this))
            {
                TaskResult merged;

                //
                // No current result merge.
                //
                // Act.
                merged = TaskResultUtil.MergeTaskResults(null, TaskResult.Succeeded);
                // Actual
                Assert.Equal(TaskResult.Succeeded, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(null, TaskResult.SucceededWithIssues);
                // Actual
                Assert.Equal(TaskResult.SucceededWithIssues, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(null, TaskResult.Abandoned);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(null, TaskResult.Canceled);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(null, TaskResult.Failed);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(null, TaskResult.Skipped);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);

                //
                // Same result merge.
                //
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Succeeded, TaskResult.Succeeded);
                // Actual
                Assert.Equal(TaskResult.Succeeded, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.SucceededWithIssues, TaskResult.SucceededWithIssues);
                // Actual
                Assert.Equal(TaskResult.SucceededWithIssues, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Abandoned, TaskResult.Abandoned);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Canceled, TaskResult.Canceled);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Failed, TaskResult.Failed);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Skipped, TaskResult.Skipped);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);

                //
                // Forward result merge
                //
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Succeeded, TaskResult.SucceededWithIssues);
                // Actual
                Assert.Equal(TaskResult.SucceededWithIssues, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Succeeded, TaskResult.Abandoned);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Succeeded, TaskResult.Canceled);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Succeeded, TaskResult.Failed);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Succeeded, TaskResult.Skipped);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.SucceededWithIssues, TaskResult.Abandoned);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.SucceededWithIssues, TaskResult.Canceled);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.SucceededWithIssues, TaskResult.Failed);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.SucceededWithIssues, TaskResult.Skipped);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);

                //
                // No backward merge
                //
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Abandoned, TaskResult.SucceededWithIssues);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Abandoned, TaskResult.Succeeded);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Canceled, TaskResult.SucceededWithIssues);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Canceled, TaskResult.Succeeded);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Failed, TaskResult.SucceededWithIssues);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Failed, TaskResult.Succeeded);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Skipped, TaskResult.SucceededWithIssues);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Skipped, TaskResult.Succeeded);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.SucceededWithIssues, TaskResult.Succeeded);
                // Actual
                Assert.Equal(TaskResult.SucceededWithIssues, merged);

                //
                // Worst result no change
                //
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Abandoned, TaskResult.Canceled);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Abandoned, TaskResult.Failed);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Abandoned, TaskResult.Skipped);
                // Actual
                Assert.Equal(TaskResult.Abandoned, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Canceled, TaskResult.Abandoned);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Canceled, TaskResult.Failed);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Canceled, TaskResult.Skipped);
                // Actual
                Assert.Equal(TaskResult.Canceled, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Failed, TaskResult.Abandoned);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Failed, TaskResult.Canceled);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Failed, TaskResult.Skipped);
                // Actual
                Assert.Equal(TaskResult.Failed, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Skipped, TaskResult.Abandoned);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Skipped, TaskResult.Canceled);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);
                // Act.
                merged = TaskResultUtil.MergeTaskResults(TaskResult.Skipped, TaskResult.Failed);
                // Actual
                Assert.Equal(TaskResult.Skipped, merged);
            }
        }
        private void SetupTestEnv(TestHostContext hc, string securityId)
        {
            _powerCfgCalledForACOption = _powerCfgCalledForDCOption = false;
            _autoLogonSettings         = null;

            _windowsServiceHelper = new Mock <INativeWindowsServiceHelper>();
            hc.SetSingleton <INativeWindowsServiceHelper>(_windowsServiceHelper.Object);

            _promptManager = new Mock <IPromptManager>();
            hc.SetSingleton <IPromptManager>(_promptManager.Object);

            hc.SetSingleton <IWhichUtil>(new WhichUtil());

            _promptManager
            .Setup(x => x.ReadValue(
                       Constants.Agent.CommandLine.Args.WindowsLogonAccount, // argName
                       It.IsAny <string>(),                                  // description
                       It.IsAny <bool>(),                                    // secret
                       It.IsAny <string>(),                                  // defaultValue
                       Validators.NTAccountValidator,                        // validator
                       It.IsAny <bool>()))                                   // unattended
            .Returns(string.Format(@"{0}\{1}", _domainName, _userName));

            _windowsServiceHelper.Setup(x => x.IsValidAutoLogonCredential(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(true);
            _windowsServiceHelper.Setup(x => x.SetAutoLogonPassword(It.IsAny <string>()));
            _windowsServiceHelper.Setup(x => x.GetSecurityId(It.IsAny <string>(), It.IsAny <string>())).Returns(() => securityId);
            _windowsServiceHelper.Setup(x => x.IsRunningInElevatedMode()).Returns(true);

            _processInvoker = new Mock <IProcessInvoker>();
            hc.EnqueueInstance <IProcessInvoker>(_processInvoker.Object);
            hc.EnqueueInstance <IProcessInvoker>(_processInvoker.Object);

            _processInvoker.Setup(x => x.ExecuteAsync(
                                      It.IsAny <String>(),
                                      "powercfg.exe",
                                      "/Change monitor-timeout-ac 0",
                                      null,
                                      It.IsAny <CancellationToken>())).Returns(Task.FromResult <int>(SetPowerCfgFlags(true)));

            _processInvoker.Setup(x => x.ExecuteAsync(
                                      It.IsAny <String>(),
                                      "powercfg.exe",
                                      "/Change monitor-timeout-dc 0",
                                      null,
                                      It.IsAny <CancellationToken>())).Returns(Task.FromResult <int>(SetPowerCfgFlags(false)));

            _mockRegManager = new MockRegistryManager();
            hc.SetSingleton <IWindowsRegistryManager>(_mockRegManager);

            _command = new CommandSettings(
                hc,
                new[]
            {
                "--windowslogonaccount", "wont be honored",
                "--windowslogonpassword", "sssh",
                "--norestart"
            });

            _store = new Mock <IConfigurationStore>();
            _store.Setup(x => x.SaveAutoLogonSettings(It.IsAny <AutoLogonSettings>()))
            .Callback((AutoLogonSettings settings) =>
            {
                _autoLogonSettings = settings;
            });

            _store.Setup(x => x.IsAutoLogonConfigured()).Returns(() => _autoLogonSettings != null);
            _store.Setup(x => x.GetAutoLogonSettings()).Returns(() => _autoLogonSettings);



            hc.SetSingleton <IConfigurationStore>(_store.Object);

            hc.SetSingleton <IAutoLogonRegistryManager>(new AutoLogonRegistryManager());
        }
        public void AddIssue_CountWarningsErrors()
        {
            using (TestHostContext hc = CreateTestContext())
                using (var ec = new Agent.Worker.ExecutionContext())
                {
                    // Arrange: Create a job request message.
                    TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
                    TimelineReference timeline          = new TimelineReference();
                    JobEnvironment    environment       = new JobEnvironment();
                    environment.SystemConnection = new ServiceEndpoint();
                    List <TaskInstance> tasks = new List <TaskInstance>();
                    Guid   JobId      = Guid.NewGuid();
                    string jobName    = "some job name";
                    var    jobRequest = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, environment, tasks));

                    // Arrange: Setup the paging logger.
                    var pagingLogger   = new Mock <IPagingLogger>();
                    var jobServerQueue = new Mock <IJobServerQueue>();
                    jobServerQueue.Setup(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.IsAny <TimelineRecord>()));

                    hc.EnqueueInstance(pagingLogger.Object);
                    hc.SetSingleton(jobServerQueue.Object);

                    ec.Initialize(hc);

                    // Act.
                    ec.InitializeJob(jobRequest, CancellationToken.None);

                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Error, Message = "error"
                    });

                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });
                    ec.AddIssue(new Issue()
                    {
                        Type = IssueType.Warning, Message = "warning"
                    });

                    ec.Complete();

                    // Assert.
                    jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.ErrorCount == 15)), Times.AtLeastOnce);
                    jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.WarningCount == 14)), Times.AtLeastOnce);
                    jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.Issues.Where(i => i.Type == IssueType.Error).Count() == 10)), Times.AtLeastOnce);
                    jobServerQueue.Verify(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.Is <TimelineRecord>(t => t.Issues.Where(i => i.Type == IssueType.Warning).Count() == 10)), Times.AtLeastOnce);
                }
        }
        public async Task CanEnsureMachineGroupAgentConfigureVSTSScenarioWithTags()
        {
            string receivedProjectName   = string.Empty;
            string expectedProcessedTags = string.Empty;
            string tags         = "Tag3, ,, Tag4  , , ,  Tag1,  , tag3 ";
            string expectedTags = "Tag3,Tag4,Tag1";

            _machineGroupServer.Setup(x =>
                                      x.UpdateDeploymentMachinesAsync(It.IsAny <string>(), It.IsAny <int>(),
                                                                      It.IsAny <List <DeploymentMachine> >())).Callback((string project, int machineGroupId, List <DeploymentMachine> deploymentMachine) =>
            {
                receivedProjectName   = project;
                expectedProcessedTags = string.Join(",", deploymentMachine.FirstOrDefault().Tags.ToArray());
            }
                                                                                                                        );

            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating config manager");
                IConfigurationManager configManager = new ConfigurationManager();
                configManager.Initialize(tc);

                trace.Info("Preparing command line arguments for vsts scenario");
                var command = new CommandSettings(
                    tc,
                    new[]
                {
                    "configure",
#if !OS_WINDOWS
                    "--acceptteeeula",
#endif
                    "--machinegroup",
                    "--addmachinegrouptags",
                    "--url", _expectedVSTSServerUrl,
                    "--agent", _expectedAgentName,
                    "--projectname", _expectedProjectName,
                    "--machinegroupname", _expectedMachineGroupName,
                    "--work", _expectedWorkFolder,
                    "--auth", _expectedAuthType,
                    "--token", _expectedToken,
                    "--machinegrouptags", tags
                });
                trace.Info("Constructed.");

                _store.Setup(x => x.IsConfigured()).Returns(false);
                _configMgrAgentSettings = null;

                _extnMgr.Setup(x => x.GetExtensions <IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));

                var expectedMachineGroups = new List <DeploymentGroup>()
                {
                    new DeploymentGroup()
                    {
                        Pool = new TaskAgentPoolReference(new Guid(), 3), Name = "Test-MachineGroup"
                    }
                };
                _machineGroupServer.Setup(x => x.GetDeploymentGroupsAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(expectedMachineGroups));

                trace.Info("Ensuring all the required parameters are available in the command line parameter");
                await configManager.ConfigureAsync(command);

                _store.Setup(x => x.IsConfigured()).Returns(true);

                trace.Info("Configured, verifying all the parameter value");
                var s = configManager.LoadSettings();
                Assert.NotNull(s);
                Assert.True(s.ServerUrl.Equals(_expectedVSTSServerUrl, StringComparison.CurrentCultureIgnoreCase));
                Assert.True(s.AgentName.Equals(_expectedAgentName));
                Assert.True(s.PoolId.Equals(3));
                Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
                Assert.True(s.MachineGroupId.Equals(0));
                Assert.True(s.ProjectName.Equals(_expectedProjectName));

                Assert.True(receivedProjectName.Equals(_expectedProjectName), "UpdateDeploymentMachineGroupAsync should get call with correct project name");
                Assert.True(expectedTags.Equals(expectedProcessedTags), "Before applying the tags, should get processed ( Trim, Remove duplicate)");
                // Tags logic should get trigger
                _machineGroupServer.Verify(x =>
                                           x.UpdateDeploymentMachinesAsync(It.IsAny <string>(), It.IsAny <int>(),
                                                                           It.IsAny <List <DeploymentMachine> >()), Times.Once);
            }
        }
Ejemplo n.º 42
0
        private void SetupMocks([CallerMemberName] string name = "")
        {
            _hc = new TestHostContext(this, name);
            _codeCoverageStatistics = new List <CodeCoverageStatistics> {
                new CodeCoverageStatistics {
                    Label = "label", Covered = 10, Total = 10, Position = 1
                }
            };
            _mocksummaryReader = new Mock <ICodeCoverageSummaryReader>();
            if (String.Equals(name, "Publish_CoberturaNewIndexFile"))
            {
                _mocksummaryReader.Setup(x => x.Name).Returns("cobertura");
            }
            else
            {
                _mocksummaryReader.Setup(x => x.Name).Returns("mockCCTool");
            }
            _mocksummaryReader.Setup(x => x.GetCodeCoverageSummary(It.IsAny <IExecutionContext>(), It.IsAny <string>()))
            .Returns(_codeCoverageStatistics);
            _hc.SetSingleton(_mocksummaryReader.Object);

            _mockExtensionManager = new Mock <IExtensionManager>();
            _mockExtensionManager.Setup(x => x.GetExtensions <ICodeCoverageSummaryReader>()).Returns(new List <ICodeCoverageSummaryReader> {
                _mocksummaryReader.Object
            });
            _hc.SetSingleton(_mockExtensionManager.Object);

            _mockCodeCoveragePublisher = new Mock <ICodeCoveragePublisher>();
            _hc.SetSingleton(_mockCodeCoveragePublisher.Object);

            _mockCommandContext = new Mock <IAsyncCommandContext>();
            _hc.EnqueueInstance(_mockCommandContext.Object);

            var endpointAuthorization = new EndpointAuthorization()
            {
                Scheme = EndpointAuthorizationSchemes.OAuth
            };
            List <string> warnings;

            _variables = new Variables(_hc, new Dictionary <string, VariableValue>(), out warnings);
            _variables.Set("build.buildId", "1");
            _variables.Set("build.containerId", "1");
            _variables.Set("system.teamProjectId", "46075F24-A6B9-447E-BEF0-E1D5592D9E39");
            _variables.Set("system.hostType", "build");
            endpointAuthorization.Parameters[EndpointAuthorizationParameters.AccessToken] = "accesstoken";

            _ec = new Mock <IExecutionContext>();
            _ec.Setup(x => x.Endpoints).Returns(new List <ServiceEndpoint> {
                new ServiceEndpoint {
                    Url = new Uri("http://dummyurl"), Name = WellKnownServiceEndpointNames.SystemVssConnection, Authorization = endpointAuthorization
                }
            });
            _ec.Setup(x => x.Variables).Returns(_variables);
            _ec.Setup(x => x.TranslateToHostPath(It.IsAny <string>())).Returns((string x) => x);
            var asyncCommands = new List <IAsyncCommandContext>();

            _ec.Setup(x => x.AsyncCommands).Returns(asyncCommands);
            _ec.Setup(x => x.GetHostContext()).Returns(_hc);
            _ec.Setup(x => x.AddIssue(It.IsAny <Issue>()))
            .Callback <Issue>
                ((issue) =>
            {
                if (issue.Type == IssueType.Warning)
                {
                    _warnings.Add(issue.Message);
                }
                else if (issue.Type == IssueType.Error)
                {
                    _errors.Add(issue.Message);
                }
            });
        }
Ejemplo n.º 43
0
        public void CommandParserTest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                String  vso;
                Command test;
                Command verify;
                //##vso[area.event k1=v1;]msg
                vso  = "##vso[area.event k1=v1;]msg";
                test = new Command("area", "event")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Assert.True(String.Equals(vso, test.ToString(), StringComparison.OrdinalIgnoreCase));
                Command.TryParse(vso, out verify);
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //##vso[area.event]
                vso  = "##vso[area.event]";
                test = new Command("area", "event");
                Assert.True(String.Equals(vso, test.ToString(), StringComparison.OrdinalIgnoreCase),
                            String.Format("Expect:{0}\nActual:{1}", vso, test.ToString()));
                Command.TryParse(vso, out verify);
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //##vso[area.event k1=%3B=%0D=%0A;]%3B-%0D-%0A
                vso  = "##vso[area.event k1=%3B=%0D=%0A;]%3B-%0D-%0A";
                test = new Command("area", "event")
                {
                    Data = ";-\r-\n",
                };
                test.Properties.Add("k1", ";=\r=\n");
                Assert.True(String.Equals(vso, test.ToString(), StringComparison.OrdinalIgnoreCase));
                Command.TryParse(vso, out verify);
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //##vso[area.event k1=;k2=;]
                vso  = "##vso[area.event k1=;k2=;]";
                test = new Command("area", "event");
                test.Properties.Add("k1", "");
                test.Properties.Add("k2", null);
                Assert.True(String.Equals("##vso[area.event]", test.ToString(), StringComparison.OrdinalIgnoreCase));
                Command.TryParse(vso, out verify);
                test = new Command("area", "event");
                Assert.True(IsEqualCommand(hc, test, verify));

                vso    = "";
                test   = null;
                verify = null;
                //>>>   ##vso[area.event k1=;k2=;]
                vso  = ">>>   ##vso[area.event k1=v1;]msg";
                test = new Command("area", "event")
                {
                    Data = "msg",
                };
                test.Properties.Add("k1", "v1");
                Command.TryParse(vso, out verify);
                Assert.True(IsEqualCommand(hc, test, verify));
            }
        }
Ejemplo n.º 44
0
        private TestHostContext CreateTestContext(CancellationTokenSource _tokenSource, [CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);

            _jobEc             = new Agent.Worker.ExecutionContext();
            _taskManager       = new Mock <ITaskManager>();
            _jobServerQueue    = new Mock <IJobServerQueue>();
            _config            = new Mock <IConfigurationStore>();
            _logger            = new Mock <IPagingLogger>();
            _proxy             = new Mock <IVstsAgentWebProxy>();
            _cert              = new Mock <IAgentCertificateManager>();
            _express           = new Mock <IExpressionManager>();
            _containerProvider = new Mock <IContainerOperationProvider>();
            _logPlugin         = new Mock <IAgentLogPlugin>();

            TaskRunner step1  = new TaskRunner();
            TaskRunner step2  = new TaskRunner();
            TaskRunner step3  = new TaskRunner();
            TaskRunner step4  = new TaskRunner();
            TaskRunner step5  = new TaskRunner();
            TaskRunner step6  = new TaskRunner();
            TaskRunner step7  = new TaskRunner();
            TaskRunner step8  = new TaskRunner();
            TaskRunner step9  = new TaskRunner();
            TaskRunner step10 = new TaskRunner();
            TaskRunner step11 = new TaskRunner();
            TaskRunner step12 = new TaskRunner();

            _logger.Setup(x => x.Setup(It.IsAny <Guid>(), It.IsAny <Guid>()));
            var settings = new AgentSettings
            {
                AgentId    = 1,
                AgentName  = "agent1",
                ServerUrl  = "https://test.visualstudio.com",
                WorkFolder = "_work",
            };

            _config.Setup(x => x.GetSettings())
            .Returns(settings);

            _config.Setup(x => x.GetSetupInfo())
            .Returns(new List <SetupInfo>());

            _proxy.Setup(x => x.ProxyAddress)
            .Returns(string.Empty);

            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline          = new Timeline(Guid.NewGuid());
            JobEnvironment    environment       = new JobEnvironment();

            environment.Variables[Constants.Variables.System.Culture] = "en-US";
            environment.SystemConnection = new ServiceEndpoint()
            {
                Name          = WellKnownServiceEndpointNames.SystemVssConnection,
                Url           = new Uri("https://test.visualstudio.com"),
                Authorization = new EndpointAuthorization()
                {
                    Scheme = "Test",
                }
            };
            environment.SystemConnection.Authorization.Parameters["AccessToken"] = "token";

            List <TaskInstance> tasks = new List <TaskInstance>()
            {
                new TaskInstance()
                {
                    InstanceId  = Guid.NewGuid(),
                    DisplayName = "task1",
                },
                new TaskInstance()
                {
                    InstanceId  = Guid.NewGuid(),
                    DisplayName = "task2",
                },
                new TaskInstance()
                {
                    InstanceId  = Guid.NewGuid(),
                    DisplayName = "task3",
                },
                new TaskInstance()
                {
                    InstanceId  = Guid.NewGuid(),
                    DisplayName = "task4",
                },
                new TaskInstance()
                {
                    InstanceId  = Guid.NewGuid(),
                    DisplayName = "task5",
                },
                new TaskInstance()
                {
                    InstanceId  = Guid.NewGuid(),
                    DisplayName = "task6",
                },
                new TaskInstance()
                {
                    InstanceId  = Guid.NewGuid(),
                    DisplayName = "task7",
                },
            };

            Guid JobId = Guid.NewGuid();

            _message = Pipelines.AgentJobRequestMessageUtil.Convert(new AgentJobRequestMessage(plan, timeline, JobId, testName, testName, environment, tasks));

            _taskManager.Setup(x => x.DownloadAsync(It.IsAny <IExecutionContext>(), It.IsAny <IEnumerable <Pipelines.TaskStep> >()))
            .Returns(Task.CompletedTask);

            _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task1")))
            .Returns(new Definition()
            {
                Data = new DefinitionData()
                {
                    PreJobExecution  = null,
                    Execution        = new ExecutionData(),
                    PostJobExecution = null,
                },
            });
            _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task2")))
            .Returns(new Definition()
            {
                Data = new DefinitionData()
                {
                    PreJobExecution  = new ExecutionData(),
                    Execution        = new ExecutionData(),
                    PostJobExecution = new ExecutionData(),
                },
            });
            _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task3")))
            .Returns(new Definition()
            {
                Data = new DefinitionData()
                {
                    PreJobExecution  = new ExecutionData(),
                    Execution        = null,
                    PostJobExecution = new ExecutionData(),
                },
            });
            _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task4")))
            .Returns(new Definition()
            {
                Data = new DefinitionData()
                {
                    PreJobExecution  = new ExecutionData(),
                    Execution        = null,
                    PostJobExecution = null,
                },
            });
            _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task5")))
            .Returns(new Definition()
            {
                Data = new DefinitionData()
                {
                    PreJobExecution  = null,
                    Execution        = null,
                    PostJobExecution = new ExecutionData(),
                },
            });
            _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task6")))
            .Returns(new Definition()
            {
                Data = new DefinitionData()
                {
                    PreJobExecution  = new ExecutionData(),
                    Execution        = new ExecutionData(),
                    PostJobExecution = null,
                },
            });
            _taskManager.Setup(x => x.Load(It.Is <Pipelines.TaskStep>(t => t.DisplayName == "task7")))
            .Returns(new Definition()
            {
                Data = new DefinitionData()
                {
                    PreJobExecution  = null,
                    Execution        = new ExecutionData(),
                    PostJobExecution = new ExecutionData(),
                },
            });

            hc.SetSingleton(_taskManager.Object);
            hc.SetSingleton(_config.Object);
            hc.SetSingleton(_jobServerQueue.Object);
            hc.SetSingleton(_proxy.Object);
            hc.SetSingleton(_cert.Object);
            hc.SetSingleton(_express.Object);
            hc.SetSingleton(_containerProvider.Object);
            hc.SetSingleton(_logPlugin.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // jobcontext logger
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // init step logger
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step 1
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object); // step 12

            hc.EnqueueInstance <ITaskRunner>(step1);
            hc.EnqueueInstance <ITaskRunner>(step2);
            hc.EnqueueInstance <ITaskRunner>(step3);
            hc.EnqueueInstance <ITaskRunner>(step4);
            hc.EnqueueInstance <ITaskRunner>(step5);
            hc.EnqueueInstance <ITaskRunner>(step6);
            hc.EnqueueInstance <ITaskRunner>(step7);
            hc.EnqueueInstance <ITaskRunner>(step8);
            hc.EnqueueInstance <ITaskRunner>(step9);
            hc.EnqueueInstance <ITaskRunner>(step10);
            hc.EnqueueInstance <ITaskRunner>(step11);
            hc.EnqueueInstance <ITaskRunner>(step12);

            _jobEc.Initialize(hc);
            _jobEc.InitializeJob(_message, _tokenSource.Token);
            return(hc);
        }
        // TODO: Updates legacy config.

        private TestHostContext Setup(
            [CallerMemberName] string name        = "",
            BuildCleanOption?cleanOption          = null,
            ExistingConfigKind existingConfigKind = ExistingConfigKind.None)
        {
            // Setup the host context.
            TestHostContext hc = new TestHostContext(this, name);

            // Create a random work path.
            var configStore = new Mock <IConfigurationStore>();

            _workFolder = hc.GetDirectory(WellKnownDirectory.Work);
            var settings = new AgentSettings()
            {
                WorkFolder = _workFolder
            };

            configStore.Setup(x => x.GetSettings()).Returns(settings);
            hc.SetSingleton <IConfigurationStore>(configStore.Object);

            // Setup the execution context.
            _ec = new Mock <IExecutionContext>();
            List <string> warnings;

            _variables = new Variables(hc, new Dictionary <string, VariableValue>(), out warnings);
            _variables.Set(Constants.Variables.System.CollectionId, CollectionId);
            _variables.Set(Constants.Variables.System.DefinitionId, DefinitionId);
            _variables.Set(Constants.Variables.Build.Clean, $"{cleanOption}");
            _ec.Setup(x => x.Variables).Returns(_variables);

            // Store the expected tracking file path.
            _trackingFile = Path.Combine(
                _workFolder,
                Constants.Build.Path.SourceRootMappingDirectory,
                _ec.Object.Variables.System_CollectionId,
                _ec.Object.Variables.System_DefinitionId,
                Constants.Build.Path.TrackingConfigFile);

            // Setup the endpoint.
            _repository = new Pipelines.RepositoryResource()
            {
                Alias = "self",
                Type  = Pipelines.RepositoryTypes.Git,
                Url   = new Uri("http://contoso.visualstudio.com"),
            };
            _repository.Properties.Set <String>(Pipelines.RepositoryPropertyNames.Name, "Some endpoint name");
            _repositories = new[] { _repository };

            _workspaceOptions = new Pipelines.WorkspaceOptions();
            // // Setup the source provider.
            // _sourceProvider = new Mock<ISourceProvider>();
            // _sourceProvider
            //     .Setup(x => x.GetBuildDirectoryHashKey(_ec.Object, _repository))
            //     .Returns(HashKey);
            // hc.SetSingleton<ISourceProvider>(_sourceProvider.Object);

            // Store the existing config object.
            switch (existingConfigKind)
            {
            case ExistingConfigKind.Matching:
                _existingConfig = new TrackingConfig(_ec.Object, _repositories, 1);
                Assert.Equal("1", _existingConfig.BuildDirectory);
                break;

            case ExistingConfigKind.Nonmatching:
                _existingConfig = new TrackingConfig(_ec.Object, _repositories, 2);
                Assert.Equal("2", _existingConfig.BuildDirectory);
                break;

            case ExistingConfigKind.None:
                break;

            default:
                throw new NotSupportedException();
            }

            // Store the new config object.
            if (existingConfigKind == ExistingConfigKind.Matching)
            {
                _newConfig = _existingConfig;
            }
            else
            {
                _newConfig = new TrackingConfig(_ec.Object, _repositories, 3);
                Assert.Equal("3", _newConfig.BuildDirectory);
            }

            // Setup the tracking manager.
            _trackingManager = new Mock <ITrackingManager>();
            _trackingManager
            .Setup(x => x.LoadExistingTrackingConfig(_ec.Object))
            .Returns(_existingConfig);

            _trackingManager
            .Setup(x => x.Create(_ec.Object, _repositories, false))
            .Returns(_newConfig);
            if (existingConfigKind == ExistingConfigKind.Nonmatching)
            {
                _trackingManager
                .Setup(x => x.MarkForGarbageCollection(_ec.Object, _existingConfig));
            }
            else if (existingConfigKind == ExistingConfigKind.Matching)
            {
                _trackingManager
                .Setup(x => x.UpdateTrackingConfig(_ec.Object, _existingConfig));
            }
            else if (existingConfigKind != ExistingConfigKind.None)
            {
                throw new NotSupportedException();
            }

            hc.SetSingleton <ITrackingManager>(_trackingManager.Object);

            // Setup the build directory manager.
            _buildDirectoryManager = new BuildDirectoryManager();
            _buildDirectoryManager.Initialize(hc);
            return(hc);
        }
Ejemplo n.º 46
0
        public void CalculateServiceNameL0()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating service control manager");
                ServiceControlManager scm = new ServiceControlManager();
                scm.Initialize(tc);
                ServiceNameTest[] tests = new ServiceNameTest[] {
                    new ServiceNameTest {
                        TestName                   = "SystemD Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = "foo",
                        PoolName                   = "pool1",
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.pool1.foo.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.pool1.foo)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Long Agent/Pool Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = new string('X', 40),
                        PoolName                   = new string('Y', 40),
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.YYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Pool With Unicode Dash Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = "foo",
                        PoolName                   = "pool" + "\u002D" + "1",
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar.pool-1.foo.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar.pool-1.foo)"
                    },
                    new ServiceNameTest {
                        TestName                   = "Agent For Environment Test",
                        ServiceNamePattern         = "vsts.agent.{0}.{1}.{2}.service",
                        ServiceDisplayPattern      = "Azure Pipelines Agent ({0}.{1}.{2})",
                        AgentName                  = new string('X', 80),
                        ServerUrl                  = "https://dev.azure.com/bar",
                        ExpectedServiceName        = "vsts.agent.bar..XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.service",
                        ExpectedServiceDisplayName = "Azure Pipelines Agent (bar..XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX)"
                    },
                };
                foreach (var test in tests)
                {
                    AgentSettings settings = new AgentSettings();
                    settings.ServerUrl = test.ServerUrl;
                    settings.AgentName = test.AgentName;
                    settings.PoolName  = test.PoolName;

                    string serviceName;
                    string serviceDisplayName;

                    scm.CalculateServiceName(settings, test.ServiceNamePattern, test.ServiceDisplayPattern, out serviceName, out serviceDisplayName);

                    Assert.True(string.Equals(serviceName, test.ExpectedServiceName), $"{test.TestName} Service Name Expected: {test.ExpectedServiceName}, Got: {serviceName}");
                    Assert.True(serviceName.Length <= 80, $"{test.TestName} Service Name is <= 80");
                    Assert.True(string.Equals(serviceDisplayName, test.ExpectedServiceDisplayName), $"{test.TestName} Service Display Name Expected: {test.ExpectedServiceDisplayName}, Got: {serviceDisplayName}");
                }
            }
        }
Ejemplo n.º 47
0
        public async void GetNextMessage()
        {
            using (TestHostContext tc = CreateTestContext())
                using (var tokenSource = new CancellationTokenSource())
                {
                    Tracing trace = tc.GetTrace();

                    // Arrange.
                    var          expectedSession   = new TaskAgentSession();
                    PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    Assert.NotNull(sessionIdProperty);
                    sessionIdProperty.SetValue(expectedSession, Guid.NewGuid());

                    _agentServer
                    .Setup(x => x.CreateAgentSessionAsync(
                               _settings.PoolId,
                               It.Is <TaskAgentSession>(y => y != null),
                               tokenSource.Token))
                    .Returns(Task.FromResult(expectedSession));

                    _capabilitiesManager.Setup(x => x.GetCapabilitiesAsync(_settings, It.IsAny <CancellationToken>())).Returns(Task.FromResult(new Dictionary <string, string>()));

                    _credMgr.Setup(x => x.LoadCredentials()).Returns(new Common.VssCredentials());

                    // Act.
                    MessageListener listener = new MessageListener();
                    listener.Initialize(tc);

                    bool result = await listener.CreateSessionAsync(tokenSource.Token);

                    Assert.True(result);

                    var arMessages = new TaskAgentMessage[]
                    {
                        new TaskAgentMessage
                        {
                            Body        = "somebody1",
                            MessageId   = 4234,
                            MessageType = JobRequestMessageTypes.AgentJobRequest
                        },
                        new TaskAgentMessage
                        {
                            Body        = "somebody2",
                            MessageId   = 4235,
                            MessageType = JobCancelMessage.MessageType
                        },
                        null,  //should be skipped by GetNextMessageAsync implementation
                        null,
                        new TaskAgentMessage
                        {
                            Body        = "somebody3",
                            MessageId   = 4236,
                            MessageType = JobRequestMessageTypes.AgentJobRequest
                        }
                    };
                    var messages = new Queue <TaskAgentMessage>(arMessages);

                    _agentServer
                    .Setup(x => x.GetAgentMessageAsync(
                               _settings.PoolId, expectedSession.SessionId, It.IsAny <long?>(), tokenSource.Token))
                    .Returns(async(Int32 poolId, Guid sessionId, Int64? lastMessageId, CancellationToken cancellationToken) =>
                    {
                        await Task.Yield();
                        return(messages.Dequeue());
                    });
                    TaskAgentMessage message1 = await listener.GetNextMessageAsync(tokenSource.Token);

                    TaskAgentMessage message2 = await listener.GetNextMessageAsync(tokenSource.Token);

                    TaskAgentMessage message3 = await listener.GetNextMessageAsync(tokenSource.Token);

                    Assert.Equal(arMessages[0], message1);
                    Assert.Equal(arMessages[1], message2);
                    Assert.Equal(arMessages[4], message3);

                    //Assert
                    _agentServer
                    .Verify(x => x.GetAgentMessageAsync(
                                _settings.PoolId, expectedSession.SessionId, It.IsAny <long?>(), tokenSource.Token), Times.Exactly(arMessages.Length));
                }
        }
Ejemplo n.º 48
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            TestHostContext tc = new TestHostContext(this, testName);

            return(tc);
        }
        private void SetupMocks([CallerMemberName] string name = "", bool includePipelineVariables = false)
        {
            _hc = new TestHostContext(this, name);

            _hc.SetSingleton(_mockTestRunDataPublisher.Object);
            _hc.SetSingleton(_mockParser.Object);

            _hc.SetSingleton(_mockCustomerIntelligenceServer.Object);
            _hc.SetSingleton(_mockFeatureFlagService.Object);

            _mockExtensionManager = new Mock <IExtensionManager>();
            _mockExtensionManager.Setup(x => x.GetExtensions <IParser>()).Returns(new List <IParser> {
                _mockParser.Object, new JUnitParser(), new NUnitParser()
            });
            _hc.SetSingleton(_mockExtensionManager.Object);

            _mockCommandContext = new Mock <IAsyncCommandContext>();
            _hc.EnqueueInstance(_mockCommandContext.Object);

            var endpointAuthorization = new EndpointAuthorization()
            {
                Scheme = EndpointAuthorizationSchemes.OAuth
            };
            List <string> warnings;

            _variables = new Variables(_hc, new Dictionary <string, VariableValue>(), out warnings);
            _variables.Set("build.buildId", "1");
            if (includePipelineVariables)
            {
                _variables.Set("system.jobName", "job1");
                _variables.Set("system.phaseName", "phase1");
                _variables.Set("system.stageName", "stage1");
                _variables.Set("system.jobAttempt", "1");
                _variables.Set("system.phaseAttempt", "1");
                _variables.Set("system.stageAttempt", "1");
            }
            endpointAuthorization.Parameters[EndpointAuthorizationParameters.AccessToken] = "accesstoken";

            _ec = new Mock <IExecutionContext>();
            _ec.Setup(x => x.Endpoints).Returns(new List <ServiceEndpoint> {
                new ServiceEndpoint {
                    Url = new Uri("http://dummyurl"), Name = WellKnownServiceEndpointNames.SystemVssConnection, Authorization = endpointAuthorization
                }
            });
            _ec.Setup(x => x.Variables).Returns(_variables);
            var asyncCommands = new List <IAsyncCommandContext>();

            _ec.Setup(x => x.AsyncCommands).Returns(asyncCommands);
            _ec.Setup(x => x.AddIssue(It.IsAny <Issue>()))
            .Callback <Issue>
                ((issue) =>
            {
                if (issue.Type == IssueType.Warning)
                {
                    _warnings.Add(issue.Message);
                }
                else if (issue.Type == IssueType.Error)
                {
                    _errors.Add(issue.Message);
                }
            });
            _ec.Setup(x => x.GetHostContext()).Returns(_hc);
        }
Ejemplo n.º 50
0
        public async void TestRunOnceHandleUpdateMessage()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var agent = new Agent.Listener.Agent();
                hc.SetSingleton <IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton <IJobNotification>(_jobNotification.Object);
                hc.SetSingleton <IMessageListener>(_messageListener.Object);
                hc.SetSingleton <IPromptManager>(_promptManager.Object);
                hc.SetSingleton <IAgentServer>(_agentServer.Object);
                hc.SetSingleton <IVstsAgentWebProxy>(_proxy.Object);
                hc.SetSingleton <IAgentCertificateManager>(_cert.Object);
                hc.SetSingleton <IConfigurationStore>(_configStore.Object);
                hc.SetSingleton <ISelfUpdater>(_updater.Object);

                agent.Initialize(hc);
                var settings = new AgentSettings
                {
                    PoolId  = 43242,
                    AgentId = 5678
                };

                var message1 = new TaskAgentMessage()
                {
                    Body        = JsonUtility.ToString(new AgentRefreshMessage(settings.AgentId, "2.123.0")),
                    MessageId   = 4234,
                    MessageType = AgentRefreshMessage.MessageType
                };

                var messages = new Queue <TaskAgentMessage>();
                messages.Enqueue(message1);
                _updater.Setup(x => x.SelfUpdate(It.IsAny <AgentRefreshMessage>(), It.IsAny <IJobDispatcher>(), It.IsAny <bool>(), It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(true));
                _configurationManager.Setup(x => x.LoadSettings())
                .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult <bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny <CancellationToken>()))
                .Returns(async() =>
                {
                    if (0 == messages.Count)
                    {
                        await Task.Delay(2000);
                    }

                    return(messages.Dequeue());
                });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny <TaskAgentMessage>()))
                .Returns(Task.CompletedTask);
                _jobNotification.Setup(x => x.StartClient(It.IsAny <String>(), It.IsAny <String>(), It.IsAny <CancellationToken>()))
                .Callback(() =>
                {
                });
                _jobNotification.Setup(x => x.StartClient(It.IsAny <String>(), It.IsAny <String>()))
                .Callback(() =>
                {
                });

                hc.EnqueueInstance <IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var        command   = new CommandSettings(hc, new string[] { "run", "--once" });
                Task <int> agentTask = agent.ExecuteCommand(command);

                //Assert
                //wait for the agent to exit with right return code
                await Task.WhenAny(agentTask, Task.Delay(30000));

                Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out.");
                Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString());
                Assert.True(agentTask.Result == Constants.Agent.ReturnCode.RunOnceAgentUpdating);

                _updater.Verify(x => x.SelfUpdate(It.IsAny <AgentRefreshMessage>(), It.IsAny <IJobDispatcher>(), false, It.IsAny <CancellationToken>()), Times.Once);
                _jobDispatcher.Verify(x => x.Run(It.IsAny <Pipelines.AgentJobRequestMessage>(), true), Times.Never());
                _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny <CancellationToken>()), Times.AtLeastOnce());
                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny <CancellationToken>()), Times.Once());
                _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny <TaskAgentMessage>()), Times.Once());
            }
        }
Ejemplo n.º 51
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);

            _jobEc          = new Agent.Worker.ExecutionContext();
            _config         = new Mock <IConfigurationStore>();
            _extensions     = new Mock <IExtensionManager>();
            _jobExtension   = new Mock <IJobExtension>();
            _jobServer      = new Mock <IJobServer>();
            _jobServerQueue = new Mock <IJobServerQueue>();
            _proxyConfig    = new Mock <IVstsAgentWebProxy>();
            _cert           = new Mock <IAgentCertificateManager>();
            _taskServer     = new Mock <ITaskServer>();
            _stepRunner     = new Mock <IStepsRunner>();
            _logger         = new Mock <IPagingLogger>();
            _temp           = new Mock <ITempDirectoryManager>();

            if (_tokenSource != null)
            {
                _tokenSource.Dispose();
                _tokenSource = null;
            }

            _tokenSource = new CancellationTokenSource();
            var expressionManager = new ExpressionManager();

            expressionManager.Initialize(hc);
            hc.SetSingleton <IExpressionManager>(expressionManager);

            _jobRunner = new JobRunner();
            _jobRunner.Initialize(hc);

            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline          = new Timeline(Guid.NewGuid());
            JobEnvironment    environment       = new JobEnvironment();

            environment.Variables[Constants.Variables.System.Culture] = "en-US";
            environment.SystemConnection = new ServiceEndpoint()
            {
                Url           = new Uri("https://test.visualstudio.com"),
                Authorization = new EndpointAuthorization()
                {
                    Scheme = "Test",
                }
            };
            environment.SystemConnection.Authorization.Parameters["AccessToken"] = "token";

            List <TaskInstance> tasks = new List <TaskInstance>();
            Guid JobId = Guid.NewGuid();

            _message = new AgentJobRequestMessage(plan, timeline, JobId, testName, testName, environment, tasks);

            _extensions.Setup(x => x.GetExtensions <IJobExtension>()).
            Returns(new[] { _jobExtension.Object }.ToList());

            _initResult.PreJobSteps.Clear();
            _initResult.JobSteps.Clear();
            _initResult.PostJobStep.Clear();

            _jobExtension.Setup(x => x.InitializeJob(It.IsAny <IExecutionContext>(), It.IsAny <AgentJobRequestMessage>())).
            Returns(Task.FromResult(_initResult));
            _jobExtension.Setup(x => x.HostType)
            .Returns <string>(null);

            _proxyConfig.Setup(x => x.ProxyAddress)
            .Returns(string.Empty);

            var settings = new AgentSettings
            {
                AgentId    = 1,
                AgentName  = "agent1",
                ServerUrl  = "https://test.visualstudio.com",
                WorkFolder = "_work",
            };

            _config.Setup(x => x.GetSettings())
            .Returns(settings);

            _logger.Setup(x => x.Setup(It.IsAny <Guid>(), It.IsAny <Guid>()));

            hc.SetSingleton(_config.Object);
            hc.SetSingleton(_jobServer.Object);
            hc.SetSingleton(_jobServerQueue.Object);
            hc.SetSingleton(_proxyConfig.Object);
            hc.SetSingleton(_cert.Object);
            hc.SetSingleton(_taskServer.Object);
            hc.SetSingleton(_stepRunner.Object);
            hc.SetSingleton(_extensions.Object);
            hc.SetSingleton(_temp.Object);
            hc.EnqueueInstance <IExecutionContext>(_jobEc);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            return(hc);
        }
Ejemplo n.º 52
0
        //process 2 new job messages, and one cancel message
        public async void TestRunAsync()
        {
            using (var hc = new TestHostContext(this))
            {
                //Arrange
                var agent = new Agent.Listener.Agent();
                hc.SetSingleton <IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton <IJobNotification>(_jobNotification.Object);
                hc.SetSingleton <IMessageListener>(_messageListener.Object);
                hc.SetSingleton <IPromptManager>(_promptManager.Object);
                hc.SetSingleton <IAgentServer>(_agentServer.Object);
                hc.SetSingleton <IVstsAgentWebProxy>(_proxy.Object);
                hc.SetSingleton <IAgentCertificateManager>(_cert.Object);
                hc.SetSingleton <IConfigurationStore>(_configStore.Object);
                agent.Initialize(hc);
                var settings = new AgentSettings
                {
                    PoolId = 43242
                };

                var message = new TaskAgentMessage()
                {
                    Body        = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                    MessageId   = 4234,
                    MessageType = JobRequestMessageTypes.AgentJobRequest
                };

                var messages = new Queue <TaskAgentMessage>();
                messages.Enqueue(message);
                var signalWorkerComplete = new SemaphoreSlim(0, 1);
                _configurationManager.Setup(x => x.LoadSettings())
                .Returns(settings);
                _configurationManager.Setup(x => x.IsConfigured())
                .Returns(true);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult <bool>(true));
                _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny <CancellationToken>()))
                .Returns(async() =>
                {
                    if (0 == messages.Count)
                    {
                        signalWorkerComplete.Release();
                        await Task.Delay(2000, hc.AgentShutdownToken);
                    }

                    return(messages.Dequeue());
                });
                _messageListener.Setup(x => x.DeleteSessionAsync())
                .Returns(Task.CompletedTask);
                _messageListener.Setup(x => x.DeleteMessageAsync(It.IsAny <TaskAgentMessage>()))
                .Returns(Task.CompletedTask);
                _jobDispatcher.Setup(x => x.Run(It.IsAny <Pipelines.AgentJobRequestMessage>(), It.IsAny <bool>()))
                .Callback(() =>
                {
                });
                _jobNotification.Setup(x => x.StartClient(It.IsAny <String>(), It.IsAny <String>(), It.IsAny <CancellationToken>()))
                .Callback(() =>
                {
                });
                _jobNotification.Setup(x => x.StartClient(It.IsAny <String>(), It.IsAny <String>()))
                .Callback(() =>
                {
                });

                hc.EnqueueInstance <IJobDispatcher>(_jobDispatcher.Object);

                _configStore.Setup(x => x.IsServiceConfigured()).Returns(false);
                //Act
                var  command   = new CommandSettings(hc, new string[] { "run" });
                Task agentTask = agent.ExecuteCommand(command);

                //Assert
                //wait for the agent to run one job
                if (!await signalWorkerComplete.WaitAsync(2000))
                {
                    Assert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked.");
                }
                else
                {
                    //Act
                    hc.ShutdownAgent(ShutdownReason.UserCancelled); //stop Agent

                    //Assert
                    Task[] taskToWait2 = { agentTask, Task.Delay(2000) };
                    //wait for the Agent to exit
                    await Task.WhenAny(taskToWait2);

                    Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out.");
                    Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString());
                    Assert.True(agentTask.IsCanceled);

                    _jobDispatcher.Verify(x => x.Run(It.IsAny <Pipelines.AgentJobRequestMessage>(), It.IsAny <bool>()), Times.Once(),
                                          $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                    _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny <CancellationToken>()), Times.AtLeastOnce());
                    _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny <CancellationToken>()), Times.Once());
                    _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                    _messageListener.Verify(x => x.DeleteMessageAsync(It.IsAny <TaskAgentMessage>()), Times.AtLeastOnce());
                }
            }
        }
Ejemplo n.º 53
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);

            _jobEc                = new Runner.Worker.ExecutionContext();
            _config               = new Mock <IConfigurationStore>();
            _extensions           = new Mock <IExtensionManager>();
            _jobExtension         = new Mock <IJobExtension>();
            _jobServer            = new Mock <IJobServer>();
            _jobServerQueue       = new Mock <IJobServerQueue>();
            _stepRunner           = new Mock <IStepsRunner>();
            _logger               = new Mock <IPagingLogger>();
            _temp                 = new Mock <ITempDirectoryManager>();
            _diagnosticLogManager = new Mock <IDiagnosticLogManager>();

            if (_tokenSource != null)
            {
                _tokenSource.Dispose();
                _tokenSource = null;
            }

            _tokenSource = new CancellationTokenSource();
            var expressionManager = new ExpressionManager();

            expressionManager.Initialize(hc);
            hc.SetSingleton <IExpressionManager>(expressionManager);

            _jobRunner = new JobRunner();
            _jobRunner.Initialize(hc);

            TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
            TimelineReference timeline          = new Timeline(Guid.NewGuid());
            Guid jobId = Guid.NewGuid();

            _message = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, testName, testName, null, null, null, new Dictionary <string, VariableValue>(), new List <MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List <Pipelines.ActionStep>(), null);
            _message.Variables[Constants.Variables.System.Culture] = "en-US";
            _message.Resources.Endpoints.Add(new ServiceEndpoint()
            {
                Name          = WellKnownServiceEndpointNames.SystemVssConnection,
                Url           = new Uri("https://pipelines.actions.githubusercontent.com"),
                Authorization = new EndpointAuthorization()
                {
                    Scheme     = "Test",
                    Parameters =
                    {
                        { "AccessToken", "token" }
                    }
                },
            });

            _message.Resources.Repositories.Add(new Pipelines.RepositoryResource()
            {
                Alias   = Pipelines.PipelineConstants.SelfAlias,
                Id      = "github",
                Version = "sha1"
            });
            _message.ContextData.Add("github", new Pipelines.ContextData.DictionaryContextData());

            _initResult.Clear();

            _jobExtension.Setup(x => x.InitializeJob(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.AgentJobRequestMessage>())).
            Returns(Task.FromResult(_initResult));

            var settings = new RunnerSettings
            {
                AgentId    = 1,
                AgentName  = "agent1",
                ServerUrl  = "https://pipelines.actions.githubusercontent.com",
                WorkFolder = "_work",
            };

            _config.Setup(x => x.GetSettings())
            .Returns(settings);

            _logger.Setup(x => x.Setup(It.IsAny <Guid>(), It.IsAny <Guid>()));

            hc.SetSingleton(_config.Object);
            hc.SetSingleton(_jobServer.Object);
            hc.SetSingleton(_jobServerQueue.Object);
            hc.SetSingleton(_stepRunner.Object);
            hc.SetSingleton(_extensions.Object);
            hc.SetSingleton(_temp.Object);
            hc.SetSingleton(_diagnosticLogManager.Object);
            hc.EnqueueInstance <IExecutionContext>(_jobEc);
            hc.EnqueueInstance <IPagingLogger>(_logger.Object);
            hc.EnqueueInstance <IJobExtension>(_jobExtension.Object);
            return(hc);
        }
Ejemplo n.º 54
0
        private void Setup([CallerMemberName] string name = "")
        {
            _ecTokenSource?.Dispose();
            _ecTokenSource = new CancellationTokenSource();

            // Test host context.
            _hc = new TestHostContext(this, name);

            var actionInputs = new MappingToken(null, null, null);

            actionInputs.Add(new StringToken(null, null, null, "input1"), new StringToken(null, null, null, "input1"));
            actionInputs.Add(new StringToken(null, null, null, "input2"), new StringToken(null, null, null, ""));
            actionInputs.Add(new StringToken(null, null, null, "input3"), new StringToken(null, null, null, "github"));
            var actionDefinition = new Definition()
            {
                Directory = _hc.GetDirectory(WellKnownDirectory.Work),
                Data      = new ActionDefinitionData()
                {
                    Name        = name,
                    Description = name,
                    Inputs      = actionInputs,
                    Execution   = new ScriptActionExecutionData()
                }
            };

            // Mocks.
            _actionManager = new Mock <IActionManager>();
            _actionManager.Setup(x => x.LoadAction(It.IsAny <IExecutionContext>(), It.IsAny <ActionStep>())).Returns(actionDefinition);

            _handlerFactory        = new Mock <IHandlerFactory>();
            _defaultStepHost       = new Mock <IDefaultStepHost>();
            _actionManifestManager = new ActionManifestManager();
            _actionManifestManager.Initialize(_hc);

            var githubContext = new GitHubContext();

            githubContext.Add("event", JToken.Parse("{\"foo\":\"bar\"}").ToPipelineContextData());
            _context.Add("github", githubContext);

#if OS_WINDOWS
            _context["env"] = new DictionaryContextData();
#else
            _context["env"] = new CaseSensitiveDictionaryContextData();
#endif

            _ec = new Mock <IExecutionContext>();
            _ec.Setup(x => x.ExpressionValues).Returns(_context);
            _ec.Setup(x => x.ExpressionFunctions).Returns(new List <IFunctionInfo>());
            _ec.Setup(x => x.IntraActionState).Returns(new Dictionary <string, string>());
            _ec.Setup(x => x.EnvironmentVariables).Returns(new Dictionary <string, string>());
            _ec.Setup(x => x.SetGitHubContext(It.IsAny <string>(), It.IsAny <string>()));
            _ec.Setup(x => x.GetGitHubContext(It.IsAny <string>())).Returns("{\"foo\":\"bar\"}");
            _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);
            _ec.Setup(x => x.Variables).Returns(new Variables(_hc, new Dictionary <string, VariableValue>()));
            _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>())).Callback((string tag, string message) => { _hc.GetTrace().Info($"[{tag}]{message}"); });
            _ec.Setup(x => x.AddIssue(It.IsAny <Issue>(), It.IsAny <string>())).Callback((Issue issue, string message) => { _hc.GetTrace().Info($"[{issue.Type}]{issue.Message ?? message}"); });

            _hc.SetSingleton <IActionManager>(_actionManager.Object);
            _hc.SetSingleton <IHandlerFactory>(_handlerFactory.Object);
            _hc.SetSingleton <IActionManifestManager>(_actionManifestManager);

            _hc.EnqueueInstance <IDefaultStepHost>(_defaultStepHost.Object);

            // Instance to test.
            _actionRunner = new ActionRunner();
            _actionRunner.Initialize(_hc);
            _actionRunner.ExecutionContext = _ec.Object;
        }
Ejemplo n.º 55
0
        public async void DispatcherRenewJobRequestStopOnExpiredRequest()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                int   poolId    = 1;
                Int64 requestId = 1000;
                int   count     = 0;

                var trace = hc.GetTrace(nameof(DispatcherRenewJobRequestStopOnExpiredRequest));
                TaskCompletionSource <int> firstJobRequestRenewed  = new TaskCompletionSource <int>();
                CancellationTokenSource    cancellationTokenSource = new CancellationTokenSource();

                TaskAgentJobRequest request           = new TaskAgentJobRequest();
                PropertyInfo        lockUntilProperty = request.GetType().GetProperty("LockedUntil", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                Assert.NotNull(lockUntilProperty);
                lockUntilProperty.SetValue(request, DateTime.UtcNow.AddMinutes(5));

                hc.SetSingleton <IAgentServer>(_agentServer.Object);
                hc.SetSingleton <IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new AgentSettings()
                {
                    PoolId = 1
                });
                _agentServer.Setup(x => x.RenewAgentRequestAsync(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <Guid>(), It.IsAny <CancellationToken>()))
                .Returns(() =>
                {
                    count++;
                    if (!firstJobRequestRenewed.Task.IsCompletedSuccessfully)
                    {
                        trace.Info("First renew happens.");
                    }

                    if (count == 1)
                    {
                        return(Task.FromResult <TaskAgentJobRequest>(request));
                    }
                    else if (count < 5)
                    {
                        throw new TimeoutException("");
                    }
                    else if (count == 5)
                    {
                        lockUntilProperty.SetValue(request, DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(11)));
                        throw new TimeoutException("");
                    }
                    else
                    {
                        cancellationTokenSource.CancelAfter(10000);
                        throw new InvalidOperationException("Should not reach here.");
                    }
                });

                var jobDispatcher = new JobDispatcher();
                jobDispatcher.Initialize(hc);

                await jobDispatcher.RenewJobRequestAsync(poolId, requestId, Guid.Empty, firstJobRequestRenewed, cancellationTokenSource.Token);

                Assert.True(firstJobRequestRenewed.Task.IsCompletedSuccessfully, "First renew should succeed.");
                Assert.False(cancellationTokenSource.IsCancellationRequested);
                _agentServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <Guid>(), It.IsAny <CancellationToken>()), Times.Exactly(5));
                _agentServer.Verify(x => x.RefreshConnectionAsync(AgentConnectionType.JobRequest, It.IsAny <TimeSpan>()), Times.Exactly(3));
                _agentServer.Verify(x => x.SetConnectionTimeout(AgentConnectionType.JobRequest, It.IsAny <TimeSpan>()), Times.Never);
            }
        }
Ejemplo n.º 56
0
        public void GetRelativePathWindows()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                string relativePath;
                /// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src") -> @"project\foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project\foo.cpp", @"d:\src");
                // Assert.
                Assert.True(string.Equals(relativePath, @"project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\", @"d:\specs") -> @"d:\"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\", @"d:\specs");
                // Assert.
                Assert.True(string.Equals(relativePath, @"d:\", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\proj") -> @"d:\src\project\foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\proj");
                // Assert.
                Assert.True(string.Equals(relativePath, @"d:\src\project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\src\project\foo", @"d:\src") -> @"project\foo"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project\foo", @"d:\src");
                // Assert.
                Assert.True(string.Equals(relativePath, @"project\foo", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\project\foo.cpp") -> @""
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project", @"d:\src\project");
                // Assert.
                Assert.True(string.Equals(relativePath, string.Empty, StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:/src/project/foo.cpp", @"d:/src") -> @"project/foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:/src/project/foo.cpp", @"d:/src");
                // Assert.
                Assert.True(string.Equals(relativePath, @"project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:/src/project/foo.cpp", @"d:\src") -> @"d:/src/project/foo.cpp"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:/src/project/foo.cpp", @"d:/src");
                // Assert.
                Assert.True(string.Equals(relativePath, @"project\foo.cpp", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d:/src/project/foo", @"d:/src") -> @"project/foo"
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:/src/project/foo", @"d:/src");
                // Assert.
                Assert.True(string.Equals(relativePath, @"project\foo", StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");

                /// MakeRelative(@"d\src\project", @"d:/src/project") -> @""
                // Act.
                relativePath = IOUtil.MakeRelative(@"d:\src\project", @"d:/src/project");
                // Assert.
                Assert.True(string.Equals(relativePath, string.Empty, StringComparison.OrdinalIgnoreCase), $"RelativePath does not expected: {relativePath}");
            }
        }
Ejemplo n.º 57
0
        //process 2 new job messages, and one cancel message
        public async void TestRunAsync()
        {
            using (var hc = new TestHostContext(this))
                using (var tokenSource = new CancellationTokenSource())
                {
                    //Arrange
                    var agent = new Agent.Listener.Agent();
                    agent.TokenSource = tokenSource;
                    hc.SetSingleton <IConfigurationManager>(_configurationManager.Object);
                    hc.SetSingleton <IMessageListener>(_messageListener.Object);
                    hc.SetSingleton <IPromptManager>(_promptManager.Object);
                    hc.SetSingleton <IAgentServer>(_agentServer.Object);
                    agent.Initialize(hc);
                    var settings = new AgentSettings
                    {
                        PoolId = 43242
                    };
                    var taskAgentSession = new TaskAgentSession();
                    //we use reflection to achieve this, because "set" is internal
                    PropertyInfo sessionIdProperty = taskAgentSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    Assert.NotNull(sessionIdProperty);
                    sessionIdProperty.SetValue(taskAgentSession, Guid.NewGuid());

                    var message = new TaskAgentMessage()
                    {
                        Body        = JsonUtility.ToString(CreateJobRequestMessage("job1")),
                        MessageId   = 4234,
                        MessageType = JobRequestMessage.MessageType
                    };

                    var messages = new Queue <TaskAgentMessage>();
                    messages.Enqueue(message);
                    var signalWorkerComplete = new SemaphoreSlim(0, 1);
                    _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(settings);
                    _configurationManager.Setup(x => x.IsConfigured())
                    .Returns(true);
                    _configurationManager.Setup(x => x.EnsureConfiguredAsync(It.IsAny <CommandSettings>()))
                    .Returns(Task.CompletedTask);
                    _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny <CancellationToken>()))
                    .Returns(Task.FromResult <bool>(true));
                    _messageListener.Setup(x => x.Session)
                    .Returns(taskAgentSession);
                    _messageListener.Setup(x => x.GetNextMessageAsync(It.IsAny <CancellationToken>()))
                    .Returns(async() =>
                    {
                        if (0 == messages.Count)
                        {
                            signalWorkerComplete.Release();
                            await Task.Delay(2000, tokenSource.Token);
                        }

                        return(messages.Dequeue());
                    });
                    _messageListener.Setup(x => x.DeleteSessionAsync())
                    .Returns(Task.CompletedTask);
                    _jobDispatcher.Setup(x => x.Run(It.IsAny <JobRequestMessage>()))
                    .Callback(() =>
                    {
                    });
                    _agentServer.Setup(x => x.DeleteAgentMessageAsync(settings.PoolId, message.MessageId, taskAgentSession.SessionId, It.IsAny <CancellationToken>()))
                    .Returns((Int32 poolId, Int64 messageId, Guid sessionId, CancellationToken cancellationToken) =>
                    {
                        return(Task.CompletedTask);
                    });

                    hc.EnqueueInstance <IJobDispatcher>(_jobDispatcher.Object);

                    //Act
                    var  command   = new CommandSettings(hc, new string[0]);
                    Task agentTask = agent.ExecuteCommand(command);

                    //Assert
                    //wait for the agent to run one job
                    if (!await signalWorkerComplete.WaitAsync(2000))
                    {
                        Assert.True(false, $"{nameof(_messageListener.Object.GetNextMessageAsync)} was not invoked.");
                    }
                    else
                    {
                        //Act
                        tokenSource.Cancel(); //stop Agent

                        //Assert
                        Task[] taskToWait2 = { agentTask, Task.Delay(2000) };
                        //wait for the Agent to exit
                        await Task.WhenAny(taskToWait2);

                        Assert.True(agentTask.IsCompleted, $"{nameof(agent.ExecuteCommand)} timed out.");
                        Assert.True(!agentTask.IsFaulted, agentTask.Exception?.ToString());
                        Assert.True(agentTask.IsCanceled);

                        _jobDispatcher.Verify(x => x.Run(It.IsAny <JobRequestMessage>()), Times.Once(),
                                              $"{nameof(_jobDispatcher.Object.Run)} was not invoked.");
                        _messageListener.Verify(x => x.GetNextMessageAsync(It.IsAny <CancellationToken>()), Times.AtLeastOnce());
                        _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny <CancellationToken>()), Times.Once());
                        _messageListener.Verify(x => x.DeleteSessionAsync(), Times.Once());
                        _agentServer.Verify(x => x.DeleteAgentMessageAsync(settings.PoolId, message.MessageId, taskAgentSession.SessionId, It.IsAny <CancellationToken>()), Times.AtLeastOnce());
                    }
                }
        }
Ejemplo n.º 58
0
        public async Task SetsJobResultCorrectly()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                // Arrange.
                var variableSets = new[]
                {
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Failed, "success()"), CreateStep(hc, TaskResult.Succeeded, "success()") },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Failed, "success()"), CreateStep(hc, TaskResult.Succeeded, "success() || failure()") },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Failed, "success()"), CreateStep(hc, TaskResult.Succeeded, "always()") },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Failed, "success()", continueOnError: true), CreateStep(hc, TaskResult.Failed, "success()") },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Failed, "success()", continueOnError: true), CreateStep(hc, TaskResult.Succeeded, "success()") },
                        Expected = TaskResult.Succeeded
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Failed, "success()", continueOnError: true), CreateStep(hc, TaskResult.Failed, "success()", continueOnError: true) },
                        Expected = TaskResult.Succeeded
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Succeeded, "success() || failure()") },
                        Expected = TaskResult.Succeeded
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Succeeded, "success()"), CreateStep(hc, TaskResult.Failed, "success()") },
                        Expected = TaskResult.Failed
                    },
                    new
                    {
                        Steps    = new[] { CreateStep(hc, TaskResult.Succeeded, "success()"), CreateStep(hc, TaskResult.Succeeded, "success()") },
                        Expected = TaskResult.Succeeded
                    },
                    //  Abandoned
                    //  Canceled
                    //  Failed
                    //  Skipped
                    //  Succeeded
                };
                foreach (var variableSet in variableSets)
                {
                    _ec.Object.Result = null;

                    _ec.Setup(x => x.JobSteps).Returns(new Queue <IStep>(variableSet.Steps.Select(x => x.Object).ToList()));

                    // Act.
                    await _stepsRunner.RunAsync(jobContext : _ec.Object);

                    // Assert.
                    Assert.True(
                        variableSet.Expected == (_ec.Object.Result ?? TaskResult.Succeeded),
                        $"Expected '{variableSet.Expected}'. Actual '{_ec.Object.Result}'. Steps: {FormatSteps(variableSet.Steps)}");
                }
            }
        }
Ejemplo n.º 59
0
        public void RegisterPostJobAction_ShareState()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                // Arrange: Create a job request message.
                TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
                TimelineReference timeline          = new TimelineReference();
                Guid   jobId      = Guid.NewGuid();
                string jobName    = "some job name";
                var    jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, jobId, jobName, jobName, null, null, null, new Dictionary <string, VariableValue>(), new List <MaskHint>(), new Pipelines.JobResources(), new Pipelines.ContextData.DictionaryContextData(), new Pipelines.WorkspaceOptions(), new List <Pipelines.ActionStep>(), null, null, null, null);
                jobRequest.Resources.Repositories.Add(new Pipelines.RepositoryResource()
                {
                    Alias   = Pipelines.PipelineConstants.SelfAlias,
                    Id      = "github",
                    Version = "sha1"
                });
                jobRequest.ContextData["github"]           = new Pipelines.ContextData.DictionaryContextData();
                jobRequest.Variables["ACTIONS_STEP_DEBUG"] = "true";

                // Arrange: Setup the paging logger.
                var pagingLogger1  = new Mock <IPagingLogger>();
                var pagingLogger2  = new Mock <IPagingLogger>();
                var pagingLogger3  = new Mock <IPagingLogger>();
                var pagingLogger4  = new Mock <IPagingLogger>();
                var pagingLogger5  = new Mock <IPagingLogger>();
                var jobServerQueue = new Mock <IJobServerQueue>();
                jobServerQueue.Setup(x => x.QueueTimelineRecordUpdate(It.IsAny <Guid>(), It.IsAny <TimelineRecord>()));
                jobServerQueue.Setup(x => x.QueueWebConsoleLine(It.IsAny <Guid>(), It.IsAny <string>())).Callback((Guid id, string msg) => { hc.GetTrace().Info(msg); });

                var actionRunner1 = new ActionRunner();
                actionRunner1.Initialize(hc);
                var actionRunner2 = new ActionRunner();
                actionRunner2.Initialize(hc);

                hc.EnqueueInstance(pagingLogger1.Object);
                hc.EnqueueInstance(pagingLogger2.Object);
                hc.EnqueueInstance(pagingLogger3.Object);
                hc.EnqueueInstance(pagingLogger4.Object);
                hc.EnqueueInstance(pagingLogger5.Object);
                hc.EnqueueInstance(actionRunner1 as IActionRunner);
                hc.EnqueueInstance(actionRunner2 as IActionRunner);
                hc.SetSingleton(jobServerQueue.Object);

                var jobContext = new Runner.Worker.ExecutionContext();
                jobContext.Initialize(hc);

                // Act.
                jobContext.InitializeJob(jobRequest, CancellationToken.None);

                var action1 = jobContext.CreateChild(Guid.NewGuid(), "action_1", "action_1", null, null);
                action1.IntraActionState["state"] = "1";
                var action2 = jobContext.CreateChild(Guid.NewGuid(), "action_2", "action_2", null, null);
                action2.IntraActionState["state"] = "2";


                var postRunner1 = hc.CreateService <IActionRunner>();
                postRunner1.Action = new Pipelines.ActionStep()
                {
                    Name = "post1", DisplayName = "Test 1", Reference = new Pipelines.RepositoryPathReference()
                    {
                        Name = "actions/action"
                    }
                };
                postRunner1.Stage       = ActionRunStage.Post;
                postRunner1.Condition   = "always()";
                postRunner1.DisplayName = "post1";


                var postRunner2 = hc.CreateService <IActionRunner>();
                postRunner2.Action = new Pipelines.ActionStep()
                {
                    Name = "post2", DisplayName = "Test 2", Reference = new Pipelines.RepositoryPathReference()
                    {
                        Name = "actions/action"
                    }
                };
                postRunner2.Stage       = ActionRunStage.Post;
                postRunner2.Condition   = "always()";
                postRunner2.DisplayName = "post2";

                action1.RegisterPostJobStep("post1", postRunner1);
                action2.RegisterPostJobStep("post2", postRunner2);

                Assert.NotNull(jobContext.JobSteps);
                Assert.NotNull(jobContext.PostJobSteps);
                Assert.Null(action1.JobSteps);
                Assert.Null(action2.JobSteps);
                Assert.Null(action1.PostJobSteps);
                Assert.Null(action2.PostJobSteps);

                var post1 = jobContext.PostJobSteps.Pop();
                var post2 = jobContext.PostJobSteps.Pop();

                Assert.Equal("post2", (post1 as IActionRunner).Action.Name);
                Assert.Equal("post1", (post2 as IActionRunner).Action.Name);

                Assert.Equal(ActionRunStage.Post, (post1 as IActionRunner).Stage);
                Assert.Equal(ActionRunStage.Post, (post2 as IActionRunner).Stage);

                Assert.Equal("always()", (post1 as IActionRunner).Condition);
                Assert.Equal("always()", (post2 as IActionRunner).Condition);

                Assert.Equal("2", (post1 as IActionRunner).ExecutionContext.IntraActionState["state"]);
                Assert.Equal("1", (post2 as IActionRunner).ExecutionContext.IntraActionState["state"]);
            }
        }
        public async Task CanEnsureMachineGroupAgentConfigureOnPremScenario()
        {
            using (TestHostContext tc = CreateTestContext())
            {
                Tracing trace = tc.GetTrace();

                trace.Info("Creating config manager");
                IConfigurationManager configManager = new ConfigurationManager();
                configManager.Initialize(tc);

                var onPremTfsUrl = "http://localtfs:8080/tfs";

                trace.Info("Preparing command line arguments for vsts scenario");
                var command = new CommandSettings(
                    tc,
                    new[]
                {
                    "configure",
#if !OS_WINDOWS
                    "--acceptteeeula",
#endif
                    "--machinegroup",
                    "--url", onPremTfsUrl,
                    "--agent", _expectedAgentName,
                    "--collectionname", _expectedCollectionName,
                    "--projectname", _expectedProjectName,
                    "--machinegroupname", _expectedMachineGroupName,
                    "--work", _expectedWorkFolder,
                    "--auth", _expectedAuthType,
                    "--token", _expectedToken
                });
                trace.Info("Constructed.");

                _store.Setup(x => x.IsConfigured()).Returns(false);
                _configMgrAgentSettings = null;

                _extnMgr.Setup(x => x.GetExtensions <IConfigurationProvider>()).Returns(GetConfigurationProviderList(tc));

                var expectedMachineGroups = new List <DeploymentGroup>()
                {
                    new DeploymentGroup()
                    {
                        Pool = new TaskAgentPoolReference(new Guid(), 7), Name = "Test-MachineGroup"
                    }
                };
                _machineGroupServer.Setup(x => x.GetDeploymentGroupsAsync(It.IsAny <string>(), It.IsAny <string>())).Returns(Task.FromResult(expectedMachineGroups));

                trace.Info("Ensuring all the required parameters are available in the command line parameter");
                await configManager.ConfigureAsync(command);

                _store.Setup(x => x.IsConfigured()).Returns(true);

                trace.Info("Configured, verifying all the parameter value");
                var s = configManager.LoadSettings();
                Assert.NotNull(s);
                Assert.True(s.ServerUrl.Equals(onPremTfsUrl));
                Assert.True(s.AgentName.Equals(_expectedAgentName));
                Assert.True(s.PoolId.Equals(7));
                Assert.True(s.WorkFolder.Equals(_expectedWorkFolder));
                Assert.True(s.MachineGroupId.Equals(0));
                Assert.True(s.ProjectName.Equals(_expectedProjectName));

                // Tags logic should not get trigger
                _machineGroupServer.Verify(x =>
                                           x.UpdateDeploymentMachinesAsync(It.IsAny <string>(), It.IsAny <int>(),
                                                                           It.IsAny <List <DeploymentMachine> >()), Times.Never);
            }
        }