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;
 }
Exemplo n.º 2
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;
 }
        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;
        }
Exemplo n.º 4
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);
            }
        }
Exemplo n.º 5
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();
            }
        }
Exemplo n.º 6
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();
            }
        }
Exemplo n.º 7
0
        private void SetupMocks([CallerMemberName] string name = "")
        {
            TestHostContext hc = new TestHostContext(this, name);

            _ec = new Mock <IExecutionContext>();
            List <string> warnings;
            var           variables = new Variables(hc, new Dictionary <string, string>(), new List <MaskHint>(), out warnings);

            _ec.Setup(x => x.Variables).Returns(variables);

            hc.SetSingleton <ITestResultsServer>(_testResultServer.Object);

            _publisher = new TestRunPublisher();
            _publisher.Initialize(hc);
            _publisher.InitializePublisher(_ec.Object, new Client.VssConnection(new Uri("http://dummyurl"), new Common.VssCredentials()), "Project1", _reader.Object);
        }
Exemplo n.º 8
0
        public void Debug_Multilines()
        {
            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);
                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 pagingLogger   = 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); });

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

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

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

                ec.Debug(null);
                ec.Debug("");
                ec.Debug("\n");
                ec.Debug("\r\n");
                ec.Debug("test");
                ec.Debug("te\nst");
                ec.Debug("te\r\nst");

                ec.Complete();

                jobServerQueue.Verify(x => x.QueueWebConsoleLine(It.IsAny <Guid>(), It.IsAny <string>()), Times.Exactly(10));
            }
        }
Exemplo n.º 9
0
        public void StepTarget_VerifySet()
        {
            using (TestHostContext hc = CreateTestContext())
                using (var ec = new Agent.Worker.ExecutionContext())
                {
                    ec.Initialize(hc);

                    var pipeContainer = new Pipelines.ContainerResource {
                        Alias = "container"
                    };
                    pipeContainer.Properties.Set <string>("image", "someimage");
                    // Arrange: Create a job request message.
                    TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference();
                    TimelineReference timeline          = new TimelineReference();
                    JobEnvironment    environment       = new JobEnvironment();
                    environment.SystemConnection = new ServiceEndpoint();
                    List <Pipelines.JobStep> steps = new List <Pipelines.JobStep>();
                    steps.Add(new Pipelines.TaskStep
                    {
                        Target = new Pipelines.StepTarget
                        {
                            Target = "container"
                        },
                        Reference = new Pipelines.TaskStepDefinitionReference()
                    });
                    var resources = new Pipelines.JobResources();
                    resources.Containers.Add(pipeContainer);
                    Guid   JobId      = Guid.NewGuid();
                    string jobName    = "some job name";
                    var    jobRequest = new Pipelines.AgentJobRequestMessage(plan, timeline, JobId, jobName, jobName, null, new Dictionary <string, string>(),
                                                                             new Dictionary <string, VariableValue>(), new List <MaskHint>(), resources, new Pipelines.WorkspaceOptions(), steps);

                    // Arrange: Setup command manager
                    var commandMock = new Mock <IWorkerCommandManager>();
                    hc.SetSingleton(commandMock.Object);
                    var pagingLogger = new Mock <IPagingLogger>();
                    hc.EnqueueInstance(pagingLogger.Object);

                    // Act.
                    ec.InitializeJob(jobRequest, CancellationToken.None);
                    ec.SetStepTarget(steps[0].Target);

                    // Assert.
                    Assert.IsType <ContainerInfo>(ec.StepTarget());
                    commandMock.Verify(x => x.SetCommandRestrictionPolicy(It.IsAny <UnrestricedWorkerCommandRestrictionPolicy>()));
                }
        }
Exemplo n.º 10
0
        public async void DispatchCancellation()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                var worker = new Microsoft.VisualStudio.Services.Agent.Worker.Worker();
                hc.EnqueueInstance <IProcessChannel>(_processChannel.Object);
                hc.EnqueueInstance <IJobRunner>(_jobRunner.Object);
                hc.SetSingleton <IProxyConfiguration>(_proxy.Object);
                worker.Initialize(hc);
                var jobMessage       = CreateJobRequestMessage("job1");
                var cancelMessage    = CreateJobCancelMessage(jobMessage.JobId);
                var arWorkerMessages = new WorkerMessage[]
                {
                    new WorkerMessage
                    {
                        Body        = JsonUtility.ToString(jobMessage),
                        MessageType = MessageType.NewJobRequest
                    },
                    new WorkerMessage
                    {
                        Body        = JsonUtility.ToString(cancelMessage),
                        MessageType = MessageType.CancelRequest
                    }
                };
                var workerMessages = new Queue <WorkerMessage>(arWorkerMessages);

                _processChannel.Setup(x => x.ReceiveAsync(It.IsAny <CancellationToken>()))
                .Returns(() => Task.FromResult(workerMessages.Dequeue()));
                _jobRunner.Setup(x => x.RunAsync(It.IsAny <AgentJobRequestMessage>(), It.IsAny <CancellationToken>()))
                .Returns(
                    async(JobRequestMessage jm, CancellationToken ct) =>
                {
                    await Task.Delay(-1, ct);
                    return(TaskResult.Canceled);
                });

                //Act
                await Assert.ThrowsAsync <TaskCanceledException>(
                    async() => await worker.RunAsync("1", "2"));

                //Assert
                _processChannel.Verify(x => x.StartClient("1", "2"), Times.Once());
                _jobRunner.Verify(x => x.RunAsync(
                                      It.Is <AgentJobRequestMessage>(y => JsonUtility.ToString(y) == arWorkerMessages[0].Body), It.IsAny <CancellationToken>()));
            }
        }
Exemplo n.º 11
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);

            _ec = new Mock <IExecutionContext>();
            _ec.SetupAllProperties();
            _ec.Setup(x => x.Global).Returns(new GlobalContext {
                WriteDebug = true
            });
            var trace = hc.GetTrace();

            _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>())).Callback((string tag, string message) => { trace.Info($"[{tag}]{message}"); });

            _dc = new Mock <IDockerCommandManager>();
            hc.SetSingleton(_dc.Object);
            return(hc);
        }
        private TestHostContext SetupMocks([CallerMemberName] string name = "")
        {
            var _hc = new TestHostContext(this, name);

            _mockCiService = new Mock <ICustomerIntelligenceServer>();
            _hc.SetSingleton(_mockCiService.Object);

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

            var endpointAuthorization = new EndpointAuthorization()
            {
                Scheme = EndpointAuthorizationSchemes.OAuth
            };
            List <string> warnings;
            var           variables = new Variables(_hc, new Dictionary <string, VariableValue>(), out warnings);

            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);

            return(_hc);
        }
Exemplo n.º 13
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.SetSingleton <IExtensionManager>(_extnMgr.Object);
            tc.SetSingleton <IAgentServer>(_agentServer.Object);
            tc.SetSingleton <ICapabilitiesManager>(_capabilitiesManager);

#if OS_WINDOWS
            tc.SetSingleton <IWindowsServiceControlManager>(_serviceControlManager.Object);
#endif

#if !OS_WINDOWS
            tc.SetSingleton <ILinuxServiceControlManager>(_serviceControlManager.Object);
#endif

            tc.SetSingleton <IRSAKeyManager>(_rsaKeyManager.Object);
            tc.EnqueueInstance <IAgentServer>(_agentServer.Object);

            return(tc);
        }
        public void VerifyTasksTests()
        {
            using (TestHostContext hc = CreateTestContext())
            {
                // Setup
                var taskRunner = new TaskRunner();
                Mock <IConfigurationStore> store = new Mock <IConfigurationStore>();
                AgentSettings settings           = new AgentSettings();
                settings.AlwaysExtractTask = true;
                store.Setup(x => x.GetSettings()).Returns(settings);
                hc.SetSingleton(store.Object);
                taskRunner.Initialize(hc);
                Definition definition = new Definition()
                {
                    ZipPath = "test"
                };
                Mock <ITaskManager> taskManager = new Mock <ITaskManager>();
                taskManager.Setup(x => x.Extract(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.TaskStep>()));

                // Each Verify call should Extract since the ZipPath is given and AlwaysExtract = True
                taskRunner.VerifyTask(taskManager.Object, definition);
                taskManager.Verify(x => x.Extract(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.TaskStep>()), Times.Exactly(1));
                taskRunner.VerifyTask(taskManager.Object, definition);
                taskManager.Verify(x => x.Extract(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.TaskStep>()), Times.Exactly(2));
                taskRunner.VerifyTask(taskManager.Object, definition);
                taskManager.Verify(x => x.Extract(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.TaskStep>()), Times.Exactly(3));

                // Verify call should not Extract since AlwaysExtract = False
                settings.AlwaysExtractTask = false;
                taskRunner.VerifyTask(taskManager.Object, definition);
                taskManager.Verify(x => x.Extract(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.TaskStep>()), Times.Exactly(3));

                // Setting back to AlwaysExtract = true causes Extract to be called
                settings.AlwaysExtractTask = true;
                taskRunner.VerifyTask(taskManager.Object, definition);
                taskManager.Verify(x => x.Extract(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.TaskStep>()), Times.Exactly(4));

                // Clearing the ZipPath should not Extract
                definition.ZipPath = null;
                taskRunner.VerifyTask(taskManager.Object, definition);
                taskManager.Verify(x => x.Extract(It.IsAny <IExecutionContext>(), It.IsAny <Pipelines.TaskStep>()), Times.Exactly(4));
            }
        }
Exemplo n.º 15
0
        public void EchoProcessCommand()
        {
            using (TestHostContext _hc = new TestHostContext(this))
            {
                var extensionManager = new Mock <IExtensionManager>();
                var echoCommand      = new EchoCommandExtension();
                echoCommand.Initialize(_hc);

                extensionManager.Setup(x => x.GetExtensions <IActionCommandExtension>())
                .Returns(new List <IActionCommandExtension>()
                {
                    echoCommand
                });
                _hc.SetSingleton <IExtensionManager>(extensionManager.Object);

                Mock <IExecutionContext> _ec = new Mock <IExecutionContext>();
                _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>()))
                .Returns((string tag, string line) =>
                {
                    _hc.GetTrace().Info($"{tag} {line}");
                    return(1);
                });

                _ec.SetupAllProperties();

                ActionCommandManager commandManager = new ActionCommandManager();
                commandManager.Initialize(_hc);

                Assert.False(_ec.Object.EchoOnActionCommand);

                Assert.True(commandManager.TryProcessCommand(_ec.Object, "::echo::on"));
                Assert.True(_ec.Object.EchoOnActionCommand);

                Assert.True(commandManager.TryProcessCommand(_ec.Object, "::echo::off"));
                Assert.False(_ec.Object.EchoOnActionCommand);

                Assert.True(commandManager.TryProcessCommand(_ec.Object, "::echo::ON"));
                Assert.True(_ec.Object.EchoOnActionCommand);

                Assert.True(commandManager.TryProcessCommand(_ec.Object, "::echo::Off   "));
                Assert.False(_ec.Object.EchoOnActionCommand);
            }
        }
Exemplo n.º 16
0
        public void StopProcessCommand()
        {
            using (TestHostContext _hc = new TestHostContext(this))
            {
                var extensionManger = new Mock <IExtensionManager>();
                var pluginCommand   = new InternalPluginSetRepoPathCommandExtension();
                pluginCommand.Initialize(_hc);

                var envCommand = new SetEnvCommandExtension();
                envCommand.Initialize(_hc);

                extensionManger.Setup(x => x.GetExtensions <IActionCommandExtension>())
                .Returns(new List <IActionCommandExtension>()
                {
                    pluginCommand, envCommand
                });
                _hc.SetSingleton <IExtensionManager>(extensionManger.Object);

                Mock <IExecutionContext> _ec = new Mock <IExecutionContext>();
                _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>()))
                .Returns((string tag, string line) =>
                {
                    _hc.GetTrace().Info($"{tag} {line}");
                    return(1);
                });

                _ec.Setup(x => x.AddIssue(It.IsAny <Issue>(), It.IsAny <string>()))
                .Callback((Issue issue, string message) =>
                {
                    _hc.GetTrace().Info($"{issue.Type} {issue.Message} {message ?? string.Empty}");
                });

                _ec.Setup(x => x.EnvironmentVariables).Returns(new Dictionary <string, string>());

                ActionCommandManager commandManager = new ActionCommandManager();
                commandManager.Initialize(_hc);

                Assert.True(commandManager.TryProcessCommand(_ec.Object, "##[stop-commands]stopToken"));
                Assert.False(commandManager.TryProcessCommand(_ec.Object, "##[set-env name=foo]bar"));
                Assert.True(commandManager.TryProcessCommand(_ec.Object, "##[stopToken]"));
                Assert.True(commandManager.TryProcessCommand(_ec.Object, "##[set-env name=foo]bar"));
            }
        }
Exemplo n.º 17
0
        public async void TestConfigureCLI(string arg, bool IsConfigured, int expected = Constants.Agent.ReturnCode.Success)
        {
            using (var hc = new TestHostContext(this))
            {
                hc.SetSingleton <IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton <IPromptManager>(_promptManager.Object);
                hc.SetSingleton <IMessageListener>(_messageListener.Object);
                hc.SetSingleton <IVstsAgentWebProxy>(_proxy.Object);
                hc.SetSingleton <IAgentCertificateManager>(_cert.Object);
                hc.SetSingleton <IConfigurationStore>(_configStore.Object);

                var command = new CommandSettings(hc, new[] { arg });

                _configurationManager.Setup(x => x.IsConfigured()).
                Returns(IsConfigured);

                _configurationManager.Setup(x => x.LoadSettings())
                .Returns(new AgentSettings {
                });
                _configurationManager.Setup(x => x.ConfigureAsync(It.IsAny <CommandSettings>()))
                .Returns(Task.CompletedTask);
                _configurationManager.Setup(x => x.UnconfigureAsync(It.IsAny <CommandSettings>()))
                .Returns(Task.CompletedTask);

                _configStore.Setup(x => x.IsServiceConfigured())
                .Returns(false);

                using (var agent = new Agent.Listener.Agent())
                {
                    agent.Initialize(hc);
                    var status = await agent.ExecuteCommand(command);

                    Assert.True(status == expected, $"Expected to return {expected} exit code after {arg}. Got: {status}");

                    // config/unconfig throw exceptions
                    _configurationManager.Setup(x => x.ConfigureAsync(It.IsAny <CommandSettings>()))
                    .Throws(new Exception("Test Exception During Configure"));
                    _configurationManager.Setup(x => x.UnconfigureAsync(It.IsAny <CommandSettings>()))
                    .Throws(new Exception("Test Exception During Unconfigure"));
                }

                using (var agent2 = new Agent.Listener.Agent())
                {
                    agent2.Initialize(hc);
                    var status2 = await agent2.ExecuteCommand(command);

                    Assert.True(status2 == Constants.Agent.ReturnCode.TerminatedError, $"Expected to return terminated exit code when handling exception after {arg}. Got: {status2}");
                }
            }
        }
Exemplo n.º 18
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);
            var expressionManager = new ExpressionManager();

            expressionManager.Initialize(hc);
            hc.SetSingleton <IExpressionManager>(expressionManager);
            Dictionary <string, VariableValue> variablesToCopy = new Dictionary <string, VariableValue>();

            _variables = new Variables(
                hostContext: hc,
                copy: variablesToCopy);
            _env = new Dictionary <string, string>()
            {
                { "env1", "1" },
                { "test", "github_actions" }
            };
            _ec = new Mock <IExecutionContext>();
            _ec.SetupAllProperties();
            _ec.Setup(x => x.Variables).Returns(_variables);

            _contexts           = new DictionaryContextData();
            _jobContext         = new JobContext();
            _contexts["github"] = new DictionaryContextData();
            _contexts["runner"] = new DictionaryContextData();
            _contexts["job"]    = _jobContext;
            _ec.Setup(x => x.ExpressionValues).Returns(_contexts);
            _ec.Setup(x => x.JobContext).Returns(_jobContext);

            _stepContext = new StepsContext();
            _ec.Setup(x => x.StepsContext).Returns(_stepContext);

            _ec.Setup(x => x.PostJobSteps).Returns(new Stack <IStep>());

            var trace = hc.GetTrace();

            _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>())).Callback((string tag, string message) => { trace.Info($"[{tag}]{message}"); });

            _stepsRunner = new StepsRunner();
            _stepsRunner.Initialize(hc);
            return(hc);
        }
Exemplo n.º 19
0
        public TestHostContext Setup([CallerMemberName] string name = "")
        {
            // Setup the host context.
            TestHostContext hc = new TestHostContext(this, name);

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

            _workFolder = Path.Combine(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                $"_work_{Path.GetRandomFileName()}");
            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(WellKnownDistributedTaskVariables.TFCollectionUrl, CollectionUrl);
            _variables.Set(Constants.Variables.System.DefinitionId, DefinitionId);
            _variables.Set(Constants.Variables.Build.DefinitionName, DefinitionName);
            _ec.Setup(x => x.Variables).Returns(_variables);

            // Setup the endpoint.
            _endpoint = new ServiceEndpoint()
            {
                Url = new Uri(EndpointUrl)
            };

            // Setup the tracking manager.
            _trackingManager = new TrackingManager();
            _trackingManager.Initialize(hc);

            return(hc);
        }
Exemplo n.º 20
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);
            var expressionManager = new ExpressionManager();

            expressionManager.Initialize(hc);
            hc.SetSingleton <IExpressionManager>(expressionManager);
            List <string> warnings;

            _variables = new Variables(
                hostContext: hc,
                copy: new Dictionary <string, VariableValue>(),
                warnings: out warnings);
            _ec = new Mock <IExecutionContext>();
            _ec.SetupAllProperties();
            _ec.Setup(x => x.Variables).Returns(_variables);
            _stepsRunner = new StepsRunner();
            _stepsRunner.Initialize(hc);
            return(hc);
        }
Exemplo n.º 21
0
        private void SetupMocks([CallerMemberName] string name = "")
        {
            TestHostContext hc = new TestHostContext(this, name);

            _ec = new Mock <IExecutionContext>();
            List <string> warnings;
            var           variables = new Variables(hc, new Dictionary <string, VariableValue>(), out warnings);

            _ec.Setup(x => x.Variables).Returns(variables);
            _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>()))
            .Callback <string, string>
                ((tag, message) =>
            {
                Console.Error.WriteLine(tag + ": " + message);
            });
            _mockFeatureFlagService = new Mock <IFeatureFlagService>();
            _mockFeatureFlagService.Setup(x => x.GetFeatureFlagState(It.IsAny <string>(), It.IsAny <Guid>())).Returns(true);
            _ec.Setup(x => x.GetHostContext()).Returns(hc);
            hc.SetSingleton(_mockFeatureFlagService.Object);
        }
Exemplo n.º 22
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);
            }
        }
        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);
            }
        }
Exemplo n.º 24
0
        public void EchoProcessCommandInvalid()
        {
            using (TestHostContext _hc = new TestHostContext(this))
            {
                var extensionManager = new Mock <IExtensionManager>();
                var echoCommand      = new EchoCommandExtension();
                echoCommand.Initialize(_hc);

                extensionManager.Setup(x => x.GetExtensions <IActionCommandExtension>())
                .Returns(new List <IActionCommandExtension>()
                {
                    echoCommand
                });
                _hc.SetSingleton <IExtensionManager>(extensionManager.Object);

                Mock <IExecutionContext> _ec = new Mock <IExecutionContext>();
                _ec.Setup(x => x.Write(It.IsAny <string>(), It.IsAny <string>()))
                .Returns((string tag, string line) =>
                {
                    _hc.GetTrace().Info($"{tag} {line}");
                    return(1);
                });

                _ec.SetupAllProperties();

                ActionCommandManager commandManager = new ActionCommandManager();
                commandManager.Initialize(_hc);

                // Echo commands below are considered "processed", but are invalid
                // 1. Invalid echo value
                Assert.True(commandManager.TryProcessCommand(_ec.Object, "::echo::invalid"));
                Assert.Equal(TaskResult.Failed, _ec.Object.CommandResult);
                Assert.False(_ec.Object.EchoOnActionCommand);

                // 2. No value
                Assert.True(commandManager.TryProcessCommand(_ec.Object, "::echo::"));
                Assert.Equal(TaskResult.Failed, _ec.Object.CommandResult);
                Assert.False(_ec.Object.EchoOnActionCommand);
            }
        }
        public void PromptsAgainWhenFailsValidation()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                var readLineValues = new Queue <string>(new[] { "Some invalid prompt value", "Some valid prompt value" });
                _terminal
                .Setup(x => x.ReadLine())
                .Returns(() => readLineValues.Dequeue());
                _terminal
                .Setup(x => x.ReadSecret())
                .Throws <InvalidOperationException>();
                hc.SetSingleton(_terminal.Object);
                _promptManager.Initialize(hc);

                // Act.
                string actual = ReadValue(validator: x => x == "Some valid prompt value");

                // Assert.
                Assert.Equal("Some valid prompt value", actual);
                _terminal.Verify(x => x.ReadLine(), Times.Exactly(2));
            }
        }
Exemplo n.º 26
0
        private TestHostContext CreateTestContext([CallerMemberName] String testName = "")
        {
            var hc = new TestHostContext(this, testName);
            var expressionManager = new ExpressionManager();

            expressionManager.Initialize(hc);
            hc.SetSingleton <IExpressionManager>(expressionManager);
            Dictionary <string, VariableValue> variablesToCopy = new Dictionary <string, VariableValue>();

            variablesToCopy.Add(Constants.Variables.Agent.RetainDefaultEncoding, new VariableValue("true", false));
            List <string> warnings;

            _variables = new Variables(
                hostContext: hc,
                copy: variablesToCopy,
                warnings: out warnings);
            _ec = new Mock <IExecutionContext>();
            _ec.SetupAllProperties();
            _ec.Setup(x => x.Variables).Returns(_variables);
            _stepsRunner = new StepsRunner();
            _stepsRunner.Initialize(hc);
            return(hc);
        }
        private TestHostContext SetupMocks([CallerMemberName] string name = "")
        {
            var _hc = new TestHostContext(this, name);

            _hc.SetSingleton(new TaskRestrictionsChecker() as ITaskRestrictionsChecker);
            _ec = new Mock <IExecutionContext>();

            _endpoint = new ServiceEndpoint()
            {
                Id            = Guid.Empty,
                Url           = new Uri("https://test.com"),
                Authorization = new EndpointAuthorization()
                {
                    Scheme = "Test",
                }
            };

            _ec.Setup(x => x.Endpoints).Returns(new List <ServiceEndpoint> {
                _endpoint
            });
            _ec.Setup(x => x.GetHostContext()).Returns(_hc);

            return(_hc);
        }
        public async void TestGetCapabilitiesWithoutDotCapabilities()
        {
            using (var hc = new TestHostContext(this))
                using (var tokenSource = new CancellationTokenSource())
                {
                    Mock <IConfigurationManager> configurationManager = new Mock <IConfigurationManager>();
                    hc.SetSingleton <IConfigurationManager>(configurationManager.Object);

                    // Arrange
                    var provider = new UserCapabilitiesProvider();
                    provider.Initialize(hc);
                    var settings = new AgentSettings()
                    {
                        AgentName = "IAmAgent007"
                    };

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

                    // Assert
                    Assert.NotNull(capabilities);
                    Assert.Empty(capabilities);
                }
        }
Exemplo n.º 29
0
        public TestHostContext Setup([CallerMemberName] string name = "")
        {
            // Setup the host context.
            TestHostContext hc = new TestHostContext(this, name);

            // Create a random work path.
            var configStore = new Mock<IConfigurationStore>();
            _workFolder = Path.Combine(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                $"_work_{Path.GetRandomFileName()}");
            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, string>(), new List<MaskHint>(), out warnings);
            _variables.Set(Constants.Variables.System.CollectionId, CollectionId);
            _variables.Set(WellKnownDistributedTaskVariables.TFCollectionUrl, CollectionUrl);
            _variables.Set(Constants.Variables.System.DefinitionId, DefinitionId);
            _variables.Set(Constants.Variables.Build.DefinitionName, DefinitionName);
            _ec.Setup(x => x.Variables).Returns(_variables);

            // Setup the endpoint.
            _endpoint = new ServiceEndpoint() { Url = new Uri(EndpointUrl) };

            // Setup the tracking manager.
            _trackingManager = new TrackingManager();
            _trackingManager.Initialize(hc);

            return hc;
        }
Exemplo n.º 30
0
        // 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 = Path.Combine(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                $"_work_{Path.GetRandomFileName()}");
            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, string>(), new List <MaskHint>(), 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.
            _endpoint = new ServiceEndpoint()
            {
                Name = "Some endpoint name",
                Url  = new Uri("http://contoso.visualstudio.com"),
            };

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

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

            case ExistingConfigKind.Nonmatching:
                _existingConfig = new TrackingConfig(_ec.Object, _endpoint, 2, NonmatchingHashKey);
                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, _endpoint, 3, HashKey);
                Assert.Equal("3", _newConfig.BuildDirectory);
            }

            // Setup the tracking manager.
            _trackingManager = new Mock <ITrackingManager>();
            _trackingManager
            .Setup(x => x.LoadIfExists(_ec.Object, _trackingFile))
            .Returns(_existingConfig);
            if (existingConfigKind == ExistingConfigKind.None || existingConfigKind == ExistingConfigKind.Nonmatching)
            {
                _trackingManager
                .Setup(x => x.Create(_ec.Object, _endpoint, HashKey, _trackingFile))
                .Returns(_newConfig);
                if (existingConfigKind == ExistingConfigKind.Nonmatching)
                {
                    _trackingManager
                    .Setup(x => x.MarkForGarbageCollection(_ec.Object, _existingConfig));
                }
            }
            else if (existingConfigKind == ExistingConfigKind.Matching)
            {
                _trackingManager
                .Setup(x => x.UpdateJobRunProperties(_ec.Object, _existingConfig, _trackingFile));
            }
            else
            {
                throw new NotSupportedException();
            }

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

            // Setup the build directory manager.
            _buildDirectoryManager = new BuildDirectoryManager();
            _buildDirectoryManager.Initialize(hc);
            return(hc);
        }
Exemplo n.º 31
0
        private void SetupMocks([CallerMemberName] string name = "")
        {
            TestHostContext hc = new TestHostContext(this, name);
            _ec = new Mock<IExecutionContext>();
            List<string> warnings;
            var variables = new Variables(hc, new Dictionary<string, string>(), new List<MaskHint>(), out warnings);
            _ec.Setup(x => x.Variables).Returns(variables);

            hc.SetSingleton<ITestResultsServer>(_testResultServer.Object);

            _publisher = new TestRunPublisher();
            _publisher.Initialize(hc);
            _publisher.InitializePublisher(_ec.Object, new Client.VssConnection(new Uri("http://dummyurl"), new Common.VssCredentials()), "Project1", _reader.Object);
        }
        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.FileTable).Returns(new List <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;
        }
Exemplo n.º 33
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 <IRunnerServer>(_runnerServer.Object);
                hc.SetSingleton <IConfigurationStore>(_configurationStore.Object);
                _configurationStore.Setup(x => x.GetSettings()).Returns(new RunnerSettings()
                {
                    PoolId = 1
                });
                _runnerServer.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);
                _runnerServer.Verify(x => x.RenewAgentRequestAsync(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <Guid>(), It.IsAny <CancellationToken>()), Times.Exactly(5));
                _runnerServer.Verify(x => x.RefreshConnectionAsync(RunnerConnectionType.JobRequest, It.IsAny <TimeSpan>()), Times.Exactly(3));
                _runnerServer.Verify(x => x.SetConnectionTimeout(RunnerConnectionType.JobRequest, It.IsAny <TimeSpan>()), Times.Never);
            }
        }
Exemplo n.º 34
0
        public async void TestExecuteCommandForRunAsService(string[] args, bool configureAsService, Times expectedTimes)
        {
            using (var hc = new TestHostContext(this))
            {
                hc.SetSingleton<IConfigurationManager>(_configurationManager.Object);
                hc.SetSingleton<IPromptManager>(_promptManager.Object);
                hc.SetSingleton<IMessageListener>(_messageListener.Object);

                var command = new CommandSettings(hc, args);

                _configurationManager.Setup(x => x.IsConfigured()).Returns(true);
                _configurationManager.Setup(x => x.LoadSettings())
                    .Returns(new AgentSettings { });
                _configurationManager.Setup(x => x.IsServiceConfigured()).Returns(configureAsService);
                _messageListener.Setup(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult(false));

                var agent = new Agent.Listener.Agent();
                agent.Initialize(hc);
                agent.TokenSource = new CancellationTokenSource();
                await agent.ExecuteCommand(command);

                _messageListener.Verify(x => x.CreateSessionAsync(It.IsAny<CancellationToken>()), expectedTimes);
            }
        }
        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);

            _mockCodeCoverageEnabler = new Mock <ICodeCoverageEnabler>();
            _mockCodeCoverageEnabler.Setup(x => x.Name).Returns("mockCCTool_mockBuildTool");
            _mockCodeCoverageEnabler.Setup(x => x.EnableCodeCoverage(It.IsAny <IExecutionContext>(), It.IsAny <CodeCoverageEnablerInputs>()));
            _hc.SetSingleton(_mockCodeCoverageEnabler.Object);

            _mockExtensionManager = new Mock <IExtensionManager>();
            _mockExtensionManager.Setup(x => x.GetExtensions <ICodeCoverageSummaryReader>()).Returns(new List <ICodeCoverageSummaryReader> {
                _mocksummaryReader.Object
            });
            _mockExtensionManager.Setup(x => x.GetExtensions <ICodeCoverageEnabler>()).Returns(new List <ICodeCoverageEnabler> {
                _mockCodeCoverageEnabler.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, string>(), new List <MaskHint>(), 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 = ServiceEndpoints.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);
                }
            });
        }
Exemplo n.º 36
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 <IJobNotification>(_jobNotification.Object);
                    hc.SetSingleton <IMessageListener>(_messageListener.Object);
                    hc.SetSingleton <IPromptManager>(_promptManager.Object);
                    hc.SetSingleton <IAgentServer>(_agentServer.Object);
                    hc.SetSingleton <IVstsAgentWebProxy>(_proxy.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, tokenSource.Token);
                        }

                        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 <AgentJobRequestMessage>()))
                    .Callback(() =>
                    {
                    });
                    _jobNotification.Setup(x => x.StartClient(It.IsAny <String>(), It.IsAny <CancellationToken>()))
                    .Callback(() =>
                    {
                    });
                    _jobNotification.Setup(x => x.StartClient(It.IsAny <String>()))
                    .Callback(() =>
                    {
                    });

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

                    //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
                        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 <AgentJobRequestMessage>()), 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());
                    }
                }
        }
Exemplo n.º 37
0
        public void GetSourceGitFetchWithClean()
        {
            using (TestHostContext tc = new TestHostContext(this))
            {
                var trace = tc.GetTrace();
                // Arrange.
                string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
                try
                {
                    Directory.CreateDirectory(dumySourceFolder);
                    string dumyGitFolder = Path.Combine(dumySourceFolder, ".git");
                    Directory.CreateDirectory(dumyGitFolder);
                    string dumyGitConfig = Path.Combine(dumyGitFolder, "config");
                    File.WriteAllText(dumyGitConfig, "test git confg file");

                    var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "refs/remotes/origin/master", "", false);
                    var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", true, false);

                    var _gitCommandManager = GetDefaultGitCommandMock();
                    tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
                    tc.SetSingleton<IWhichUtil>(new WhichUtil());

                    GitSourceProvider gitSourceProvider = new GitSourceProvider();
                    gitSourceProvider.Initialize(tc);

                    // Act.
                    gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();

                    // Assert.
                    _gitCommandManager.Verify(x => x.GitClean(executionContext.Object, dumySourceFolder));
                    _gitCommandManager.Verify(x => x.GitReset(executionContext.Object, dumySourceFolder));
                    _gitCommandManager.Verify(x => x.GitDisableAutoGC(executionContext.Object, dumySourceFolder));
                    _gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", It.Is<string>(s => s.Equals("https://*****:*****@github.com/Microsoft/vsts-agent"))));
                    _gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", It.Is<string>(s => s.Equals("https://*****:*****@github.com/Microsoft/vsts-agent"))));
                    _gitCommandManager.Verify(x => x.GitFetch(executionContext.Object, dumySourceFolder, "origin", It.IsAny<List<string>>(), It.IsAny<string>(), It.IsAny<CancellationToken>()));
                    _gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
                    _gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
                    _gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, "refs/remotes/origin/master", It.IsAny<CancellationToken>()));
                }
                finally
                {
                    IOUtil.DeleteDirectory(dumySourceFolder, CancellationToken.None);
                }
            }
        }
Exemplo n.º 38
0
        public void GetSourceReCloneOnUrlNotMatch()
        {
            using (TestHostContext tc = new TestHostContext(this))
            {
                var trace = tc.GetTrace();
                // Arrange.
                string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
                try
                {
                    Directory.CreateDirectory(dumySourceFolder);
                    string dumyGitFolder = Path.Combine(dumySourceFolder, ".git");
                    Directory.CreateDirectory(dumyGitFolder);
                    string dumyGitConfig = Path.Combine(dumyGitFolder, "config");
                    File.WriteAllText(dumyGitConfig, "test git confg file");

                    var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "refs/heads/users/user1", "", true);
                    var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", false, false);

                    var _gitCommandManager = GetDefaultGitCommandMock();
                    _gitCommandManager
                        .Setup(x => x.GitGetFetchUrl(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
                        .Returns(Task.FromResult<Uri>(new Uri("https://github.com/Microsoft/vsts-another-agent")));

                    tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
                    tc.SetSingleton<IWhichUtil>(new WhichUtil());

                    GitSourceProvider gitSourceProvider = new GitSourceProvider();
                    gitSourceProvider.Initialize(tc);

                    // Act.
                    gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();

                    // Assert.
                    _gitCommandManager.Verify(x => x.GitInit(executionContext.Object, dumySourceFolder));
                    _gitCommandManager.Verify(x => x.GitRemoteAdd(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
                    _gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, "refs/remotes/origin/users/user1", It.IsAny<CancellationToken>()));
                }
                finally
                {
                    IOUtil.DeleteDirectory(dumySourceFolder, CancellationToken.None);
                }
            }
        }
Exemplo n.º 39
0
        // 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 = Path.Combine(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                $"_work_{Path.GetRandomFileName()}");
            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, string>(), new List<MaskHint>(), 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.
            _endpoint = new ServiceEndpoint()
            {
                Name = "Some endpoint name",
                Url = new Uri("http://contoso.visualstudio.com"),
            };

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

            // Store the existing config object.
            switch (existingConfigKind)
            {
                case ExistingConfigKind.Matching:
                    _existingConfig = new TrackingConfig(_ec.Object, _endpoint, 1, HashKey);
                    Assert.Equal("1", _existingConfig.BuildDirectory);
                    break;
                case ExistingConfigKind.Nonmatching:
                    _existingConfig = new TrackingConfig(_ec.Object, _endpoint, 2, NonmatchingHashKey);
                    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, _endpoint, 3, HashKey);
                Assert.Equal("3", _newConfig.BuildDirectory);
            }

            // Setup the tracking manager.
            _trackingManager = new Mock<ITrackingManager>();
            _trackingManager
                .Setup(x => x.LoadIfExists(_ec.Object, _trackingFile))
                .Returns(_existingConfig);
            if (existingConfigKind == ExistingConfigKind.None || existingConfigKind == ExistingConfigKind.Nonmatching)
            {
                _trackingManager
                    .Setup(x => x.Create(_ec.Object, _endpoint, HashKey, _trackingFile))
                    .Returns(_newConfig);
                if (existingConfigKind == ExistingConfigKind.Nonmatching)
                {
                    _trackingManager
                        .Setup(x => x.MarkForGarbageCollection(_ec.Object, _existingConfig));
                }
            }
            else if (existingConfigKind == ExistingConfigKind.Matching)
            {
                _trackingManager
                    .Setup(x => x.UpdateJobRunProperties(_ec.Object, _existingConfig, _trackingFile));
            }
            else
            {
                throw new NotSupportedException();
            }

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

            // Setup the build directory manager.
            _buildDirectoryManager = new BuildDirectoryManager();
            _buildDirectoryManager.Initialize(hc);
            return hc;
        }
Exemplo n.º 40
0
 private TestHostContext CreateTestContext([CallerMemberName] string testName = "")
 {
     TestHostContext hc = new TestHostContext(this, testName);
     hc.SetSingleton<IPromptManager>(_promptManager.Object);
     hc.SetSingleton<ISecretMasker>(_secretMasker.Object);
     return hc;
 }
Exemplo n.º 41
0
        public void PromptsAgainWhenFailsValidation()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                var readLineValues = new Queue<string>(new[] { "Some invalid prompt value", "Some valid prompt value" });
                _terminal
                    .Setup(x => x.ReadLine())
                    .Returns(() => readLineValues.Dequeue());
                _terminal
                    .Setup(x => x.ReadSecret())
                    .Throws<InvalidOperationException>();
                hc.SetSingleton(_terminal.Object);
                _promptManager.Initialize(hc);

                // Act.
                string actual = ReadValue(validator: x => x == "Some valid prompt value");

                // Assert.
                Assert.Equal("Some valid prompt value", actual);
                _terminal.Verify(x => x.ReadLine(), Times.Exactly(2));
            }
        }
Exemplo n.º 42
0
        public void ThrowsWhenUnattended()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                // Arrange.
                _terminal
                    .Setup(x => x.ReadLine())
                    .Throws<InvalidOperationException>();
                _terminal
                    .Setup(x => x.ReadSecret())
                    .Throws<InvalidOperationException>();
                hc.SetSingleton(_terminal.Object);
                _promptManager.Initialize(hc);

                try
                {
                    // Act.
                    string actual = ReadValue(unattended: true);

                    // Assert.
                    throw new InvalidOperationException();
                }
                catch (Exception ex)
                {
                    // Assert.
                    Assert.Equal(_unattendedExceptionMessage, ex.Message);
                }
            }
        }
Exemplo n.º 43
0
        public void ShipEmptyLog()
        {
            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();
                    _jobServerQueue.Setup(x => x.QueueFileUpload(It.IsAny<Guid>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true));

                    //Act
                    pagingLogger.Setup(timeLineId, timeLineRecordId);
                    pagingLogger.End();

                    //Assert
                    _jobServerQueue.Verify(x => x.QueueFileUpload(It.IsAny<Guid>(), It.IsAny<Guid>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true), Times.Exactly(0));                    
                }
            }
            finally
            {
                //cleanup
                CleanLogFolder();
            }
        }
        private TestHostContext Setup([CallerMemberName] string name    = "",
                                      bool createWorkDirectory          = true,
                                      CheckoutConfigType checkOutConfig = CheckoutConfigType.SingleCheckoutDefaultPath,
                                      string pathToSelfRepo             = "")
        {
            bool isMulticheckoutScenario = checkOutConfig == CheckoutConfigType.MultiCheckoutCustomPath || checkOutConfig == CheckoutConfigType.MultiCheckoutDefaultPath;
            bool isCustomPathScenario    = checkOutConfig == CheckoutConfigType.SingleCheckoutCustomPath || checkOutConfig == CheckoutConfigType.MultiCheckoutCustomPath;

            TestHostContext hc = new TestHostContext(this, name);

            this.stubWorkFolder = hc.GetDirectory(WellKnownDirectory.Work);
            if (createWorkDirectory)
            {
                Directory.CreateDirectory(this.stubWorkFolder);
            }

            _ec = new Mock <IExecutionContext>();

            _extensionManager      = new Mock <IExtensionManager>();
            _sourceProvider        = new Mock <ISourceProvider>();
            _buildDirectoryManager = new Mock <IBuildDirectoryManager>();
            _workspaceOptions      = new Pipelines.WorkspaceOptions();
            _configurationStore    = new Mock <IConfigurationStore>();
            _configurationStore.Setup(store => store.GetSettings()).Returns(new AgentSettings {
                WorkFolder = this.stubWorkFolder
            });

            steps = new List <Pipelines.JobStep>();
            var selfCheckoutTask = new Pipelines.TaskStep()
            {
                Reference = new Pipelines.TaskStepDefinitionReference()
                {
                    Id      = Guid.Parse("6d15af64-176c-496d-b583-fd2ae21d4df4"),
                    Name    = "Checkout",
                    Version = "1.0.0"
                }
            };

            selfCheckoutTask.Inputs.Add("repository", "self");
            if (isCustomPathScenario)
            {
                selfCheckoutTask.Inputs.Add("path", pathToSelfRepo);
            }
            steps.Add(selfCheckoutTask);

            // Setup second checkout only for multicheckout jobs
            if (isMulticheckoutScenario)
            {
                var anotherCheckoutTask = new Pipelines.TaskStep()
                {
                    Reference = new Pipelines.TaskStepDefinitionReference()
                    {
                        Id      = Guid.Parse("6d15af64-176c-496d-b583-fd2ae21d4df4"),
                        Name    = "Checkout",
                        Version = "1.0.0"
                    }
                };
                anotherCheckoutTask.Inputs.Add("repository", "BuildRepo");
                anotherCheckoutTask.Inputs.Add("path", "s/BuildRepo");
                steps.Add(anotherCheckoutTask);
            }

            hc.SetSingleton(_buildDirectoryManager.Object);
            hc.SetSingleton(_extensionManager.Object);
            hc.SetSingleton(_configurationStore.Object);

            var buildVariables = GetBuildVariables();

            _variables = new Variables(hc, buildVariables, out _);
            _ec.Setup(x => x.Variables).Returns(_variables);

            repositories = new List <Pipelines.RepositoryResource>();
            repositories.Add(GetRepository(hc, "self", "App", "App"));
            repositories.Add(GetRepository(hc, "repo2", "BuildRepo", "BuildRepo"));
            _ec.Setup(x => x.Repositories).Returns(repositories);

            jobSettings = new Dictionary <string, string>();
            jobSettings.Add(WellKnownJobSettings.HasMultipleCheckouts, isMulticheckoutScenario.ToString());
            _ec.Setup(x => x.JobSettings).Returns(jobSettings);

            _ec.Setup(x =>
                      x.SetVariable(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .Callback((string varName, string varValue, bool isSecret, bool isOutput, bool isFilePath, bool isReadOnly) => { _variables.Set(varName, varValue, false); });

            _extensionManager.Setup(x => x.GetExtensions <ISourceProvider>())
            .Returns(new List <ISourceProvider> {
                _sourceProvider.Object
            });

            _sourceProvider.Setup(x => x.RepositoryType)
            .Returns(Pipelines.RepositoryTypes.ExternalGit);

            _buildDirectoryManager.Setup(x => x.PrepareDirectory(_ec.Object, repositories, _workspaceOptions))
            .Returns(new TrackingConfig(_ec.Object, repositories, 1));

            buildJobExtension = new BuildJobExtension();
            buildJobExtension.Initialize(hc);
            return(hc);
        }
Exemplo n.º 45
0
        public void GetSourceGitClonePR()
        {
            using (TestHostContext tc = new TestHostContext(this))
            {
                var trace = tc.GetTrace();
                // Arrange.
                string dumySourceFolder = Path.Combine(IOUtil.GetBinPath(), "SourceProviderL0");
                var executionContext = GetTestExecutionContext(tc, dumySourceFolder, "refs/pull/12345", "a596e13f5db8869f44574be0392fb8fe1e790ce4", false);
                var endpoint = GetTestSourceEndpoint("https://github.com/Microsoft/vsts-agent", false, false);

                var _gitCommandManager = GetDefaultGitCommandMock();
                tc.SetSingleton<IGitCommandManager>(_gitCommandManager.Object);
                tc.SetSingleton<IWhichUtil>(new WhichUtil());

                GitSourceProvider gitSourceProvider = new GitSourceProvider();
                gitSourceProvider.Initialize(tc);

                // Act.
                gitSourceProvider.GetSourceAsync(executionContext.Object, endpoint, default(CancellationToken)).GetAwaiter().GetResult();

                // Assert.
                _gitCommandManager.Verify(x => x.GitInit(executionContext.Object, dumySourceFolder));
                _gitCommandManager.Verify(x => x.GitRemoteAdd(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
                _gitCommandManager.Verify(x => x.GitFetch(executionContext.Object, dumySourceFolder, "origin", new List<string>() { "+refs/pull/12345:refs/remotes/pull/12345" }, It.IsAny<string>(), It.IsAny<CancellationToken>()));
                _gitCommandManager.Verify(x => x.GitRemoteSetUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
                _gitCommandManager.Verify(x => x.GitRemoteSetPushUrl(executionContext.Object, dumySourceFolder, "origin", "https://github.com/Microsoft/vsts-agent"));
                _gitCommandManager.Verify(x => x.GitCheckout(executionContext.Object, dumySourceFolder, It.Is<string>(s => s.Equals("refs/remotes/pull/12345")), It.IsAny<CancellationToken>()));
            }
        }
Exemplo n.º 46
0
        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);

            _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[]
            {
                "configure",
                "--windowslogonaccount", "wont be honored",
                "--windowslogonpassword", "sssh",
                "--norestart",
                _runOnce
            });

            _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());
        }
Exemplo n.º 47
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<IJobNotification>(_jobNotification.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;
                   });
                _jobNotification.Setup(x => x.StartClient(It.IsAny<String>(), It.IsAny<CancellationToken>()))
                    .Callback(() =>
                    {

                    });

                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());
                }
            }
        }
Exemplo n.º 48
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);

            _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);
        }
Exemplo n.º 49
0
        public async void DispatchCancellation()
        {
            //Arrange
            using (var hc = new TestHostContext(this))
            {
                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 cancelMessage = CreateJobCancelMessage(jobMessage.JobId);
                var arWorkerMessages = new WorkerMessage[]
                    {
                        new WorkerMessage
                        {
                            Body = JsonUtility.ToString(jobMessage),
                            MessageType = MessageType.NewJobRequest
                        },
                        new WorkerMessage
                        {
                            Body = JsonUtility.ToString(cancelMessage),
                            MessageType = MessageType.CancelRequest
                        }

                    };
                var workerMessages = new Queue<WorkerMessage>(arWorkerMessages);

                _processChannel.Setup(x => x.ReceiveAsync(It.IsAny<CancellationToken>()))
                    .Returns(() => Task.FromResult(workerMessages.Dequeue()));
                _jobRunner.Setup(x => x.RunAsync(It.IsAny<JobRequestMessage>(), It.IsAny<CancellationToken>()))
                    .Returns(
                    async (JobRequestMessage jm, CancellationToken ct) =>
                    {
                        await Task.Delay(-1, ct);
                        return TaskResult.Canceled;
                    });

                //Act
                await Assert.ThrowsAsync<TaskCanceledException>(
                    async () => await worker.RunAsync("1", "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>()));
            }
        }
        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>();
            _mocksummaryReader.Setup(x => x.Name).Returns("mockCCTool");
            _mocksummaryReader.Setup(x => x.GetCodeCoverageSummary(It.IsAny<IExecutionContext>(), It.IsAny<string>()))
                .Returns(_codeCoverageStatistics);
            _hc.SetSingleton(_mocksummaryReader.Object);

            _mockCodeCoverageEnabler = new Mock<ICodeCoverageEnabler>();
            _mockCodeCoverageEnabler.Setup(x => x.Name).Returns("mockCCTool_mockBuildTool");
            _mockCodeCoverageEnabler.Setup(x => x.EnableCodeCoverage(It.IsAny<IExecutionContext>(), It.IsAny<CodeCoverageEnablerInputs>()));
            _hc.SetSingleton(_mockCodeCoverageEnabler.Object);

            _mockExtensionManager = new Mock<IExtensionManager>();
            _mockExtensionManager.Setup(x => x.GetExtensions<ICodeCoverageSummaryReader>()).Returns(new List<ICodeCoverageSummaryReader> { _mocksummaryReader.Object });
            _mockExtensionManager.Setup(x => x.GetExtensions<ICodeCoverageEnabler>()).Returns(new List<ICodeCoverageEnabler> { _mockCodeCoverageEnabler.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, string>(), new List<MaskHint>(), 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 = ServiceEndpoints.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);
                }
            });
        }
        private void SetupMocks([CallerMemberName] string name = "")
        {
            _hc = new TestHostContext(this, name);
            _hc.SetSingleton(_mockResultReader.Object);

            _mockExtensionManager = new Mock<IExtensionManager>();
            _mockExtensionManager.Setup(x => x.GetExtensions<IResultReader>()).Returns(new List<IResultReader> { _mockResultReader.Object, new JUnitResultReader(), new NUnitResultReader() });
            _hc.SetSingleton(_mockExtensionManager.Object);

            _hc.SetSingleton(_mockTestRunPublisher.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, string>(), new List<MaskHint>(), out warnings);
            _variables.Set("build.buildId", "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 = ServiceEndpoints.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);
                }
            });
        }
        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.SetSingleton <IExtensionManager>(_extnMgr.Object);
            tc.SetSingleton <IAgentServer>(_agentServer.Object);
            tc.SetSingleton <ILocationServer>(_locationServer.Object);
            tc.SetSingleton <IDeploymentGroupServer>(_machineGroupServer.Object);
            tc.SetSingleton <IEnvironmentsServer>(_environmentsServer.Object);
            tc.SetSingleton <ICapabilitiesManager>(_capabilitiesManager);
            tc.SetSingleton <IVstsAgentWebProxy>(_vstsAgentWebProxy.Object);
            tc.SetSingleton <IAgentCertificateManager>(_cert.Object);

            tc.SetSingleton <IWindowsServiceControlManager>(_windowsServiceControlManager.Object);
            tc.SetSingleton <ILinuxServiceControlManager>(_linuxServiceControlManager.Object);
            tc.SetSingleton <IMacOSServiceControlManager>(_macServiceControlManager.Object);

            tc.SetSingleton <IRSAKeyManager>(_rsaKeyManager.Object);

            return(tc);
        }
Exemplo n.º 53
0
        private void Setup([CallerMemberName] string name = "")
        {
            // Random work folder.
            _workFolder = Path.Combine(IOUtil.GetBinPath(), $"_work_{Path.GetRandomFileName()}");

            // Mocks.
            _jobServer = new Mock<IJobServer>();
            _taskServer = new Mock<ITaskServer>();
            _configurationStore = new Mock<IConfigurationStore>();
            _configurationStore
                .Setup(x => x.GetSettings())
                .Returns(
                    new AgentSettings
                    {
                        WorkFolder = _workFolder
                    });
            _ec = new Mock<IExecutionContext>();
            _ec.Setup(x => x.CancellationToken).Returns(_ecTokenSource.Token);

            // Test host context.
            _hc = new TestHostContext(this, name);
            _hc.SetSingleton<IJobServer>(_jobServer.Object);
            _hc.SetSingleton<ITaskServer>(_taskServer.Object);
            _hc.SetSingleton<IConfigurationStore>(_configurationStore.Object);

            // Instance to test.
            _taskManager = new TaskManager();
            _taskManager.Initialize(_hc);
        }