Exemple #1
0
        public void RunJenoOutsideRepository_BreakExecution()
        {
            var gitWrapper = new Mock <IGitClient>();

            gitWrapper.Setup(s => s.IsGitRepository(It.IsAny <string>()))
            .Returns(Task.FromResult(false));
            gitWrapper.Setup(s => s.GetRepoName(It.IsAny <string>()))
            .Returns(Task.FromResult(DefaultKey));
            gitWrapper.Setup(s => s.GetCurrentBranch(It.IsAny <string>()))
            .Returns(Task.FromResult(Branch));

            var client = new MockHttpMessageHandler();

            client.When($"{JenkinsUrl}/job/{DefaultJob}/{Branch}/buildWithParameters")
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var command = new RunJob(gitWrapper.Object,
                                     GetEncryptorMock().Object,
                                     GetUserConsoleMock().Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock().Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);

            Assert.That(async() => await app.ExecuteAsync(new string[] { Command }), Throws.TypeOf <JenoException>()
                        .With.Property(nameof(JenoException.ExitCode)).EqualTo(JenoCodes.DefaultError)
                        .And.Property(nameof(JenoException.Message)).Contains("Current directory is not a git repository."));
        }
Exemple #2
0
        public async Task PassJobParameters_RunJubWithCustomParameters()
        {
            var parameters = new List <string>
            {
                "runUnitTests=true",
                "buildType=Quick",
                "sendEmail=true"
            };

            var client = new MockHttpMessageHandler();

            client.Expect($"{JenkinsUrl}/{DefaultJob}/job/{Branch}/buildWithParameters?{string.Join("&", parameters)}")
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var command = new RunJob(GetDefaultGitMock().Object,
                                     GetEncryptorMock().Object,
                                     GetUserConsoleMock().Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock().Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);

            parameters.Insert(0, Command);

            var code = await app.ExecuteAsync(parameters.ToArray());

            Assert.That(code, Is.EqualTo(JenoCodes.Ok));
        }
Exemple #3
0
        public async Task TryToRunJobOnJenkinsWithCSRFProtectionWithoutSavedPassword_AskUserForPassword()
        {
            var basicAuthHeader = new BasicAuthenticationHeader(UserName, Password);
            var tokenAuthHeader = new BearerAuthenticationHeader(Token);

            var configuration = new JenoConfiguration
            {
                JenkinsUrl = JenkinsUrl,
                UserName   = UserName,
                Token      = Token,
                Password   = string.Empty,
                Repository = new Dictionary <string, string>()
                {
                    { "firstExampleRepoUrl", "firstExampleJob" },
                    { "secondExampleRepoUrl", "secondExampleJob" },
                    { DefaultKey, DefaultJob },
                }
            };

            var client = new MockHttpMessageHandler();

            client.Expect($"{JenkinsUrl}/{DefaultJob}/job/{Branch}/buildWithParameters")
            .WithHeaders("Authorization", $"{tokenAuthHeader.Scheme} {tokenAuthHeader.Parameter}")
            .Respond(request => new HttpResponseMessage
            {
                StatusCode   = HttpStatusCode.Forbidden,
                ReasonPhrase = "No valid crumb was included in the request"
            });
            client.Expect($"{JenkinsUrl}/crumbIssuer/api/json")
            .WithHeaders("Authorization", $"{basicAuthHeader.Scheme} {basicAuthHeader.Parameter}")
            .Respond(CrumbContentType, JsonConvert.SerializeObject(_crumbHeader));
            client.Expect($"{JenkinsUrl}/{DefaultJob}/job/{Branch}/buildWithParameters")
            .WithHeaders("Authorization", $"{basicAuthHeader.Scheme} {basicAuthHeader.Parameter}")
            .WithHeaders(_crumbHeader.CrumbRequestField, _crumbHeader.Crumb)
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var passwordProvider = GetUserConsoleMock();

            var command = new RunJob(GetDefaultGitMock().Object,
                                     GetEncryptorMock().Object,
                                     passwordProvider.Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock(configuration).Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);

            var result = await app.ExecuteAsync(new string[] { Command });

            Assert.That(result, Is.EqualTo(JenoCodes.Ok));
            passwordProvider.Verify(s => s.ReadInput("password", true), Times.AtLeastOnce);
        }
Exemple #4
0
        public async Task PassRepositoryDefinedInConfiguration_RunJobSavedInConfiguration()
        {
            var exampleRepo = "firstExampleRepoUrl";
            var exampleJob  = "firstExampleJob";

            var configuration = new JenoConfiguration
            {
                JenkinsUrl = JenkinsUrl,
                UserName   = UserName,
                Token      = Token,
                Password   = Password,
                Repository = new Dictionary <string, string>()
                {
                    { exampleRepo, exampleJob },
                    { "secondExampleRepoUrl", "secondExampleJob" },
                    { DefaultKey, DefaultJob },
                }
            };

            var gitWrapper = new Mock <IGitClient>();

            gitWrapper.Setup(s => s.IsGitRepository(It.IsAny <string>()))
            .Returns(Task.FromResult(true));
            gitWrapper.Setup(s => s.GetRepoName(It.IsAny <string>()))
            .Returns(Task.FromResult(exampleRepo));
            gitWrapper.Setup(s => s.GetCurrentBranch(It.IsAny <string>()))
            .Returns(Task.FromResult(Branch));

            var client = new MockHttpMessageHandler();

            client.When($"{JenkinsUrl}/{exampleJob}/job/{Branch}/buildWithParameters")
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var command = new RunJob(gitWrapper.Object,
                                     GetEncryptorMock().Object,
                                     GetUserConsoleMock().Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock(configuration).Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);
            var code = await app.ExecuteAsync(new string[] { Command });

            Assert.That(code, Is.EqualTo(JenoCodes.Ok));
        }
        /// <summary>
        ///     Runs a piece of code through the runner.
        /// </summary>
        /// <param name="runJob"></param>
        /// <returns></returns>
        public HttpResponseMessage Run(RunJob runJob)
        {
            var result = _compiler.CompileFromPlainText(_participant, runJob.Code);
            var runResult = _runner.Run(_participant);

            var response = new RunResult{
                BuildResult = new BuildController.BuildResult{
                    Output = result.StandardOutput,
                    Error = result.StandardError,
                    CompileTime = result.CompilationTime
                },
                Error = runResult.Error,
                Output = result.StandardError.Length > 0 ? "Build gefaald. Zie de build tab" : runResult.Output,
                RunTime = runResult.RunTime
            };

            return Request.CreateResponse(HttpStatusCode.Created, response);
        }
Exemple #6
0
        /// <summary>
        ///     Runs a piece of code through the runner.
        /// </summary>
        /// <param name="runJob"></param>
        /// <returns></returns>
        public HttpResponseMessage Run(RunJob runJob)
        {
            var result    = _compiler.CompileFromPlainText(_participant, runJob.Code);
            var runResult = _runner.Run(_participant);

            var response = new RunResult {
                BuildResult = new BuildController.BuildResult {
                    Output      = result.StandardOutput,
                    Error       = result.StandardError,
                    CompileTime = result.CompilationTime
                },
                Error   = runResult.Error,
                Output  = result.StandardError.Length > 0 ? "Build gefaald. Zie de build tab" : runResult.Output,
                RunTime = runResult.RunTime
            };

            return(Request.CreateResponse(HttpStatusCode.Created, response));
        }
Exemple #7
0
        public async Task TryRunJobOnJenkinsWithCSRFProtection_UseBasicCredentialsAndAskForCrumb()
        {
            var basicAuthHeader = new BasicAuthenticationHeader(UserName, Password);
            var tokenAuthHeader = new BearerAuthenticationHeader(Token);

            var client = new MockHttpMessageHandler();

            client.Expect($"{JenkinsUrl}/{DefaultJob}/job/{Branch}/buildWithParameters")
            .WithHeaders("Authorization", $"{tokenAuthHeader.Scheme} {tokenAuthHeader.Parameter}")
            .Respond(request => new HttpResponseMessage
            {
                StatusCode   = HttpStatusCode.Forbidden,
                ReasonPhrase = "No valid crumb was included in the request"
            });
            client.Expect($"{JenkinsUrl}/crumbIssuer/api/json")
            .WithHeaders("Authorization", $"{basicAuthHeader.Scheme} {basicAuthHeader.Parameter}")
            .Respond(CrumbContentType, JsonConvert.SerializeObject(_crumbHeader));
            client.Expect($"{JenkinsUrl}/{DefaultJob}/job/{Branch}/buildWithParameters")
            .WithHeaders("Authorization", $"{basicAuthHeader.Scheme} {basicAuthHeader.Parameter}")
            .WithHeaders(_crumbHeader.CrumbRequestField, _crumbHeader.Crumb)
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var command = new RunJob(GetDefaultGitMock().Object,
                                     GetEncryptorMock().Object,
                                     GetUserConsoleMock().Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock().Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);

            var result = await app.ExecuteAsync(new string[] { Command });

            Assert.That(result, Is.EqualTo(JenoCodes.Ok));
        }
Exemple #8
0
        public void MissingTokenInConfiguration_InformUserAndShowLinkToTokenGenerator()
        {
            var configuration = new JenoConfiguration
            {
                JenkinsUrl = JenkinsUrl,
                UserName   = UserName,
                Token      = string.Empty,
                Password   = Password,
                Repository = new Dictionary <string, string>()
                {
                    { "firstExampleRepoUrl", "firstExampleJob" },
                    { "secondExampleRepoUrl", "secondExampleJob" },
                    { DefaultKey, DefaultJob },
                }
            };

            var client = new MockHttpMessageHandler();

            client.When($"{JenkinsUrl}/job/{DefaultJob}/job/{Branch}/buildWithParameters")
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var command = new RunJob(GetDefaultGitMock().Object,
                                     GetEncryptorMock().Object,
                                     GetUserConsoleMock().Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock(configuration).Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);

            Assert.That(async() => await app.ExecuteAsync(new string[] { Command }), Throws.TypeOf <JenoException>()
                        .With.Property(nameof(JenoException.ExitCode)).EqualTo(JenoCodes.DefaultError)
                        .And.Property(nameof(JenoException.Message)).Contains("User token is undefined"));
        }
Exemple #9
0
        public void PassIncorrectJobParameters_InformAboutInvalidParameters()
        {
            var parameters = new List <string>
            {
                "runUnitTeststrue",
                "buildType=Quick",
                "sendEmail=true"
            };

            var client = new MockHttpMessageHandler();

            client.Expect($"{JenkinsUrl}/job/{DefaultJob}/{Branch}/buildWithParameters?{string.Join("&", parameters)}")
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var command = new RunJob(GetDefaultGitMock().Object,
                                     GetEncryptorMock().Object,
                                     GetUserConsoleMock().Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock().Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);

            parameters.Insert(0, Command);

            Assert.That(async() => await app.ExecuteAsync(parameters.ToArray()), Throws.TypeOf <JenoException>()
                        .With.Property(nameof(JenoException.ExitCode)).EqualTo(JenoCodes.DefaultError)
                        .And.Property(nameof(JenoException.Message)).Contains("Some of job parameters have incorrect format")
                        .And.Property(nameof(JenoException.Message)).Contains("runUnitTeststrue")
                        .And.Property(nameof(JenoException.Message)).Not.Contains("sendEmail=true"));
        }
Exemple #10
0
        public async Task PassUndefinedRepository_RunDefaultJob()
        {
            var undefinedRepository = "fifthExampleRepo";

            var gitWrapper = new Mock <IGitClient>();

            gitWrapper.Setup(s => s.IsGitRepository(It.IsAny <string>()))
            .Returns(Task.FromResult(true));
            gitWrapper.Setup(s => s.GetRepoName(It.IsAny <string>()))
            .Returns(Task.FromResult(undefinedRepository));
            gitWrapper.Setup(s => s.GetCurrentBranch(It.IsAny <string>()))
            .Returns(Task.FromResult(Branch));

            var client = new MockHttpMessageHandler();

            client.When($"{JenkinsUrl}/{DefaultJob}/job/{Branch}/buildWithParameters")
            .Respond(HttpStatusCode.OK);

            var httpClientFactory = new Mock <IHttpClientFactory>();

            httpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>()))
            .Returns(client.ToHttpClient());

            var command = new RunJob(gitWrapper.Object,
                                     GetEncryptorMock().Object,
                                     GetUserConsoleMock().Object,
                                     httpClientFactory.Object,
                                     GetOptionsMock().Object);

            var app = new CommandLineApplication();

            app.Command(command.Name, command.Command);
            var code = await app.ExecuteAsync(new string[] { Command });

            Assert.That(code, Is.EqualTo(JenoCodes.Ok));
        }