org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition Java Examples

The following examples show how to use org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void updateExistingStackWithCustomAdminRole() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(stackSet.exists()).thenReturn(true);
	String operationId = UUID.randomUUID().toString();
	Mockito.when(stackSet.update(Mockito.anyString(), Mockito.anyString(), Mockito.any(UpdateStackSetRequest.class)))
			.thenReturn(new UpdateStackSetResult()
					.withOperationId(operationId)
			);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo', administratorRoleArn: 'bar', executionRoleName: 'baz')"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	Mockito.verify(stackSet).update(Mockito.anyString(), Mockito.anyString(), Mockito.any(UpdateStackSetRequest.class));
}
 
Example #2
Source File: ReadCSVStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void readFileWithFormat() throws Exception {
    String file = writeCSV(getCSV());

    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
            "  def format = CSVFormat.EXCEL.withHeader('key', 'value', 'attr').withSkipHeaderRecord(true)\n" +
            "  List<CSVRecord> records = readCSV file: '" + file + "', format: format\n" +
            "  assert records.size() == 2\n" +
            "  assert records[0].get('key') == 'a'\n" +
            "  assert records[0].get('value') == 'b'\n" +
            "  assert records[0].get('attr') == 'c'\n" +
            "  assert records[1].get('key') == '1'\n" +
            "  assert records[1].get('value') == '2'\n" +
            "  assert records[1].get('attr') == '3'\n" +
            "}", true));
    j.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
 
Example #3
Source File: PipelineEventListenerTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void testParentNodesOrder() throws Exception {
    String script = "node {\n" +
            "    stage('one') {\n" +
            "        sh \"echo 42\"        \n" +
            "        parallel('branch1':{\n" +
            "          sh 'echo \"branch1\"'\n" +
            "        }, 'branch2': {\n" +
            "          sh 'echo \"branch2\"'\n" +
            "        })\n" +
            "    }\n" +
            "\n" +
            "}";
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition(script));
    WorkflowRun b1 = job1.scheduleBuild2(0).get();
    j.assertBuildStatus(Result.SUCCESS, b1);

    List<FlowNode> parallels = getParallelNodes(NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(b1));
    Assert.assertEquals("10", parallels.get(0).getId());
    Assert.assertEquals("Branch: branch1", parallels.get(0).getDisplayName());

    Assert.assertEquals(Lists.newArrayList("2","3","4","5","6","8"),
            new PipelineEventListener().getBranch(parallels.get(0)));
}
 
Example #4
Source File: ReadYamlStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void readFile() throws Exception {
   
	File file = temp.newFile();
	FileUtils.writeStringToFile(file, yamlText);

    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node('slaves') {\n" +
                    "  def yaml = readYaml file: '" + separatorsToSystemEscaped(file.getAbsolutePath()) + "'\n" +
        			"  assert yaml.boolean == true\n" +
        			"  assert yaml.string == 'string'\n" +
        			"  assert yaml.integer == 3\n" +
        			"  assert yaml.double == 3.14\n" +
        			"  assert yaml.null == null\n" +
        			"  assert yaml.billTo.address.postal == 48046\n" +
        			"  assert yaml.array.size() == 2\n" +
        			"  assert yaml.array[0] == 'value1'\n" +
        			"  assert yaml.array[1] == 'value2'\n" +
        	        "  assert yaml.another == null\n" + "}",
        	        true));
    j.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
 
Example #5
Source File: ECRDeleteImagesStepTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteImage() throws Exception {
	Mockito.when(ecr.batchDeleteImage(Mockito.any())).thenReturn(new BatchDeleteImageResult()
			.withFailures(Collections.emptyList())
	);
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  ecrDeleteImage(imageIds: [[imageTag: 'it1', imageDigest: 'id1']], registryId: 'rId', repositoryName: 'rName')\n"
			+ "}\n", true)
	);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	ArgumentCaptor<BatchDeleteImageRequest> argumentCaptor = ArgumentCaptor.forClass(BatchDeleteImageRequest.class);
	Mockito.verify(this.ecr).batchDeleteImage(argumentCaptor.capture());

	BatchDeleteImageRequest request = argumentCaptor.getValue();
	Assert.assertEquals(new BatchDeleteImageRequest()
			.withImageIds(
					new ImageIdentifier().withImageTag("it1").withImageDigest("id1")
			)
			.withRegistryId("rId")
			.withRepositoryName("rName"), request);
}
 
Example #6
Source File: ECRSetRepositoryPolicyStepTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void ecrSetRepositoryPolicy() throws Exception {
	String expectedRegistryId = "my-registryId";
	String expectedRegistryName = "my-registryName";
	String expectedPolicyText = "{\"myPolicyName\": \"myPolicyValue\"}";
	Mockito.when(ecr.setRepositoryPolicy(Mockito.any())).thenReturn(mockSetRepositoryPolicyResult());
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def response = ecrSetRepositoryPolicy()\n"
			+ "  echo \"${response.toString()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("RegistryId: my-registryId,", run);
	this.jenkinsRule.assertLogContains("RepositoryName: my-repositoryName,", run);

	Mockito.verify(this.ecr, Mockito.times(1)).setRepositoryPolicy(Mockito.any());
}
 
Example #7
Source File: ScriptedPipelineTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies a labelled step isn't reported as a stage
 * @throws Exception
 */
@Test
public void testLabel() throws Exception {

    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
                    "    stage('The stage') {\n" +
                    "          sh(script: \"echo 'hello'\", label: 'echo')\n" +
                    "    }\n" +
                    "}",
            true));

    WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    BuildStatusAction buildStatus = mock(BuildStatusAction.class);
    b.addOrReplaceAction(buildStatus);
    r.waitForCompletion(b);
    Thread.sleep(500);

    verify(buildStatus, times(1)).addBuildStatus(any());

    verify(buildStatus, times(1)).updateBuildStatusForStage(eq("The stage"), eq(BuildStage.State.CompletedSuccess), anyLong());
    verify(buildStatus, times(1)).updateBuildStatusForStage(any(), any(), anyLong());
    verify(buildStatus, times(1)).updateBuildStatusForJob(any(), any());
}
 
Example #8
Source File: ReadManifestStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void testText() throws Exception {
    String s = IOUtils.toString(getClass().getResourceAsStream("testmanifest.mf"));
    p.setDefinition(new CpsFlowDefinition(
            "def man = readManifest text: '''" + s + "'''\n" +
                    "assert man != null\n" +
                    "assert man.main != null\n" +
                    "echo man.main['Version']\n" +
                    "assert man.main['Version'] == '6.15.8'\n" +
                    "echo man.main['Application-Name']\n" +
                    "assert man.main['Application-Name'] == 'My App'\n" +
                    "assert man.entries['Section1']['Shame'] == 'On U'\n" +
                    "assert man.entries['Section2']['Shame'] == 'On Me'\n"
            , true));
    j.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
 
Example #9
Source File: AbstractPipelineTestProject.java    From aws-codecommit-trigger-plugin with Apache License 2.0 6 votes vote down vote up
protected void subscribeProject(ProjectFixture fixture) throws Exception {
    String name = UUID.randomUUID().toString();
    WorkflowJob job = jenkinsRule.getInstance().createProject(WorkflowJob.class, name);

    String script = fixture.getPipelineScript().replace("${EmitEvent}", AbstractPipelineTestProject.class.getName() + ".emitBuildEvent()");
    CpsFlowDefinition flowDefinition = new CpsFlowDefinition(script, true);
    job.setDefinition(flowDefinition);

    QueueTaskFuture<WorkflowRun> run = job.scheduleBuild2(0);
    WorkflowRun wfRun = run.get();
    Assertions.assertThat(wfRun.getResult())
        .describedAs("Pipeline unable to start succeed")
        .isEqualTo(Result.SUCCESS);
    jenkinsRule.assertBuildStatusSuccess(wfRun);

    resetPipelineBuildEvent(fixture);

    if (!fixture.isHasTrigger()) {
        return;
    }

    final String uuid = this.sqsQueue.getUuid();
    SQSTrigger trigger = new SQSTrigger(uuid, fixture.isSubscribeInternalScm(), fixture.getScmConfigs());
    job.addTrigger(trigger);
    trigger.start(job, false);
}
 
Example #10
Source File: FolderIT.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
@Test
public void jenkinsfileShouldOverrideFolderConfig() throws Exception {
    WorkflowJob pipeline = folder1.createProject(WorkflowJob.class, "Pipeline");
    pipeline.setDefinition(new CpsFlowDefinition("node {\n" +
        "    wrap([$class: 'VaultBuildWrapperWithMockAccessor', \n" +
        "                   configuration: [$class: 'VaultConfiguration', \n" +
        "                             vaultCredentialId: '" + GLOBAL_CREDENTIALS_ID_2 + "', \n"
        +
        "                             vaultUrl: '" + JENKINSFILE_URL + "'], \n" +
        "                   vaultSecrets: [\n" +
        "                            [$class: 'VaultSecret', path: 'secret/path1', secretValues: [\n"
        +
        "                            [$class: 'VaultSecretValue', envVar: 'envVar1', vaultKey: 'key1']]]]]) {\n"
        +
        "            " + getShellString() + " \"echo ${env.envVar1}\"\n" +
        "      }\n" +
        "}", true));

    WorkflowRun build = pipeline.scheduleBuild2(0).get();

    jenkins.assertBuildStatus(Result.SUCCESS, build);
    jenkins.assertLogContains("echo ****", build);
}
 
Example #11
Source File: FindFilesStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void simpleList() throws Exception {
    String flow = CODE.replace("%TESTCODE%",
            "def files = findFiles()\n" +
                    "echo \"${files.length} files\"\n" +
                    "for(int i = 0; i < files.length; i++) {\n" +
                    "  echo \"F: ${files[i].path.replace('\\\\', '/')}\"\n" +
                    "}"
    );
    p.setDefinition(new CpsFlowDefinition(flow, true));
    WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
    j.assertLogContains("4 files", run);
    j.assertLogContains("F: 1.txt", run);
    j.assertLogContains("F: 2.txt", run);
    j.assertLogContains("F: a/", run);
    j.assertLogContains("F: b/", run);
    j.assertLogNotContains("F: a/3.txt", run);
    j.assertLogNotContains("F: a/ab/7.txt", run);
}
 
Example #12
Source File: ReadManifestStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void testJarWithGradleManifest() throws Exception {
    URL resource = getClass().getResource("gradle-manifest.war");

    String remoting = new File(resource.getPath()).getAbsolutePath().replace('\\', '/');
    p.setDefinition(new CpsFlowDefinition(
            "node('slaves') {\n" +
                    "  def man = readManifest file: '" + separatorsToSystemEscaped(remoting) + "'\n" +
                    "  assert man != null\n" +
                    "  assert man.main != null\n" +
                    "  echo man.main['Implementation-Version']\n" +
                    "  assert man.main['Implementation-Version'] == '1.0'\n" +
                    "}\n"
            , true));
    WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
    j.assertLogContains("Reading: META-INF/MANIFEST.MF", run);
}
 
Example #13
Source File: FindFilesStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void listAll() throws Exception {
    String flow = CODE.replace("%TESTCODE%",
            "def files = findFiles(glob: '**/*.txt')\n" +
                    "echo \"${files.length} files\"\n" +
                    "for(int i = 0; i < files.length; i++) {\n" +
                    "  echo \"F: ${files[i].path.replace('\\\\', '/')}\"\n" +
                    "}"
    );
    p.setDefinition(new CpsFlowDefinition(flow, true));
    WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));

    j.assertLogContains("12 files", run);
    j.assertLogContains("F: 1.txt", run);
    j.assertLogContains("F: 2.txt", run);
    j.assertLogContains("F: a/3.txt", run);
    j.assertLogContains("F: a/4.txt", run);
    j.assertLogContains("F: a/aa/5.txt", run);
    j.assertLogContains("F: a/aa/6.txt", run);
    j.assertLogContains("F: a/ab/7.txt", run);
    j.assertLogContains("F: a/ab/8.txt", run);
    j.assertLogContains("F: a/ab/aba/9.txt", run);
    j.assertLogContains("F: a/ab/aba/10.txt", run);
    j.assertLogContains("F: b/11.txt", run);
    j.assertLogContains("F: b/12.txt", run);
}
 
Example #14
Source File: WriteCSVStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void writeFile() throws Exception {
    File output = temp.newFile();

    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
            "  def recordsString = \"key,value,attr\\na,b,c\\n1,2,3\\n\"\n" +
            "  List<CSVRecord> records = readCSV text: recordsString\n" +
            "  writeCSV file: '" + FilenameTestsUtils.toPath(output) + "', records: records\n" +
            "}", true));
    j.assertBuildStatusSuccess(p.scheduleBuild2(0));

    // file exists by default so we check that should not be empty
    assertThat(output.length(), greaterThan(0l));

    String lines = new String(Files.readAllBytes(Paths.get(output.toURI())));
    assertThat(lines.split("\r\n|\r|\n").length, equalTo(3));
}
 
Example #15
Source File: DownstreamPipelineTriggerRunListenerTest.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void test_infinite_loop() throws Exception {
    loadMultiModuleProjectInGitRepo(this.gitRepoRule);
    String pipelineScript = "node('master') {\n" +
            "    git($/" + gitRepoRule.toString() + "/$)\n" +
            "    withMaven() {\n" +
            "        sh 'mvn install'\n" +
            "    }\n" +
            "}";

    WorkflowJob pipeline1 = jenkinsRule.createProject(WorkflowJob.class, "pipeline-1");
    pipeline1.setDefinition(new CpsFlowDefinition(pipelineScript, true));
    WorkflowRun pipeline1Build1 = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline1.scheduleBuild2(0));

    WorkflowJob pipeline2 = jenkinsRule.createProject(WorkflowJob.class, "pipeline-2");
    pipeline2.setDefinition(new CpsFlowDefinition(pipelineScript, true));
    WorkflowRun pipeline2Build1 = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline2.scheduleBuild2(0));


    dumpBuildDetails(pipeline1Build1);
    dumpBuildDetails(pipeline2Build1);

}
 
Example #16
Source File: HTMLArtifactTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void resolveArtifact() throws Exception {
    WorkflowJob p = j.createProject(WorkflowJob.class, "project");

    URL resource = Resources.getResource(getClass(), "HTMLArtifactTest.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    p.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    p.save();

    Run r = p.scheduleBuild2(0).waitForStart();
    j.waitForCompletion(r);

    BluePipeline  bluePipeline = (BluePipeline) BluePipelineFactory.resolve(p);
    BlueArtifactContainer artifacts = bluePipeline.getLatestRun().getArtifacts();

    Assert.assertEquals(1, Iterators.size(artifacts.iterator()));

    BlueArtifact artifact = Iterators.getOnlyElement(artifacts.iterator());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/project/runs/1/artifacts/io.jenkins.blueocean.htmlpublisher.HTMLArtifact%253AMy%252520Cool%252520report/", artifact.getLink().getHref());
    Assert.assertEquals("My Cool report", artifact.getName());
    Assert.assertEquals("My Cool report", artifact.getPath());
    Assert.assertNotNull(artifact.getUrl());
    Assert.assertEquals(-1, artifact.getSize());
    Assert.assertFalse(artifact.isDownloadable());
}
 
Example #17
Source File: UnZipStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void simpleUnZip() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node('slaves') {\n" +
                    "  dir('zipIt') {\n" +
                    "    writeFile file: 'hello.txt', text: 'Hello World!'\n" +
                    "    writeFile file: 'hello.dat', text: 'Hello World!'\n" +
                    "    dir('two') {\n" +
                    "      writeFile file: 'hello.txt', text: 'Hello World2!'\n" +
                    "    }\n" +
                    "    zip zipFile: '../hello.zip'\n" +
                    "  }\n" +
                    "  dir('unzip') {\n" +
                    "    unzip '../hello.zip'\n" +
                    "    String txt = readFile 'hello.txt'\n" +
                    "    echo \"Reading: ${txt}\"\n" +
                    "  }\n" +
                    "}", true));
    WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
    j.assertLogContains("Extracting: hello.txt ->", run);
    j.assertLogContains("Extracting: two/hello.txt ->", run);
    j.assertLogContains("Extracting: hello.dat ->", run);
    j.assertLogContains("Reading: Hello World!", run);
}
 
Example #18
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createEmptyChangeSet() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar"))
			.thenReturn(new DescribeChangeSetResult()
					.withStatus(ChangeSetStatus.FAILED)
					.withStatusReason("The submitted information didn't contain changes. Submit different information to create a change set.")
			);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=0", run);

}
 
Example #19
Source File: StepsITest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
private void configurePublisher(final WorkflowJob job, final String fileName, final String qualityGate) {
    String qualityGateParameter = String.format("qualityGates: [%s]", qualityGate);
    job.setDefinition(new CpsFlowDefinition("node {\n"
            + "  stage ('Integration Test') {\n"
            + "         def issues = scanForIssues tool: checkStyle(pattern: '**/" + fileName + "*')\n"
            + "         def action = publishIssues issues:[issues], " + qualityGateParameter + "\n"
            + "         echo '[id=' + action.getId() + ']' \n"
            + "         echo '[name=' + action.getDisplayName() + ']' \n"
            + "         echo '[isSuccessful=' + action.isSuccessful() + ']' \n"
            + "         def result = action.getResult()\n"
            + "         def status = result.getQualityGateStatus()\n"
            + "         echo '[status=' + status + ']' \n"
            + "         echo '[isSuccessfulQualityGate=' + status.isSuccessful() + ']' \n"
            + "         def totals = result.getTotals()\n"
            + "         echo '[total=' + totals.getTotalSize() + ']' \n"
            + "         echo '[new=' + totals.getNewSize() + ']' \n"
            + "         echo '[fixed=' + totals.getFixedSize() + ']' \n"
            + "  }\n"
            + "}", true));
}
 
Example #20
Source File: S3PresignUrlStepTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void presignWithExpiration() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "s3PresignTest");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def url = s3PresignURL(bucket: 'foo', key: 'bar', durationInSeconds: 10000)\n"
			+ "  echo \"url=$url\"\n"
			+ "}\n", true)
	);
	String urlString = "http://localhost:283/sdkd";
	URL url = new URL(urlString);
	Mockito.when(this.s3.generatePresignedUrl(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(url);

	//minus a buffer for the test
	Date expectedDate = DateTime.now().plusSeconds(10000).minusSeconds(25).toDate();
	WorkflowRun run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	jenkinsRule.assertLogContains("url=" + urlString, run);
	ArgumentCaptor<Date> expirationCaptor = ArgumentCaptor.forClass(Date.class);
	Mockito.verify(s3).generatePresignedUrl(Mockito.eq("foo"), Mockito.eq("bar"), expirationCaptor.capture(), Mockito.eq(HttpMethod.GET));

	Assertions.assertThat(expirationCaptor.getValue()).isAfterOrEqualsTo(expectedDate);
}
 
Example #21
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStepWithAssumeRoleSAMLAssertion() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithAssumeRoleSAMLAssertion");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (role: 'myRole', roleAccount: '123456789012', principalArn: 'arn:aws:iam::123456789012:saml-provider/test', samlAssertion: 'base64SAML', region: 'eu-west-1') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	WorkflowRun workflowRun = job.scheduleBuild2(0).get();
	jenkinsRule.waitForCompletion(workflowRun);
	jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun);
	jenkinsRule.assertLogContains("Requesting assume role", workflowRun);
	jenkinsRule.assertLogContains("Invalid base64 SAMLResponse", workflowRun);
}
 
Example #22
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createEmptyChangeSet_statusReason() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar"))
			.thenReturn(new DescribeChangeSetResult()
					.withStatus(ChangeSetStatus.FAILED)
					.withStatusReason("No updates are to be performed.")
			);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=0", run);

}
 
Example #23
Source File: TimeStamperPluginITest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
/**
 * Tests JENKINS-56484: Error while parsing clang errors with active timestamper plugin.
 */
@Test @org.jvnet.hudson.test.Issue("JENKINS-56484")
public void shouldCorrectlyParseClangErrors() {
    WorkflowJob project = createPipeline();

    createFileInWorkspace(project, "test.c", "int main(void) { }");

    project.setDefinition(new CpsFlowDefinition("node {\n"
            + "    timestamps {\n"
            + "        echo 'test.c:1:2: error: This is an error.'\n"
            + "        recordIssues tools: [clang(id: 'clang', name: 'clang')]\n"
            + "    }\n"
            + "}", true));

    AnalysisResult result = scheduleSuccessfulBuild(project);

    assertThat(result).hasTotalSize(1);
    assertThat(result).hasNoErrorMessages();

    Issue issue = result.getIssues().get(0);
    assertFileName(project, issue, "test.c");
    assertThat(issue).hasLineStart(1);
    assertThat(issue).hasMessage("This is an error.");
    assertThat(issue).hasSeverity(Severity.WARNING_HIGH);
}
 
Example #24
Source File: WriteYamlStepTest.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
@Test
public void invalidDataObject() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "list");
    ScriptApproval.get().approveSignature("staticMethod java.util.TimeZone getDefault");
    p.setDefinition(new CpsFlowDefinition(
                    "node('slaves') {\n" +
                    "  def tz = TimeZone.getDefault() \n" +
                    "  echo \"${tz}\"  \n" +
                    "  writeYaml file: 'test', data: TimeZone.getDefault()\n" +
                    "}",
            true));
    WorkflowRun b = j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
    j.assertLogContains("data parameter has invalid content (no-basic classes)", b);
}
 
Example #25
Source File: CFNUpdateStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void createNonExistantStack() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	Mockito.when(this.stack.exists()).thenReturn(false);
	Mockito.when(this.stack.describeOutputs()).thenReturn(Collections.singletonMap("foo", "bar"));
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  cfnUpdate(stack: 'foo')"
													+ "}\n", true)
	);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.stack).create(Mockito.anyString(), Mockito.anyString(), Mockito.<Parameter>anyCollection(), Mockito.<Tag>anyCollection(), Mockito.<String>anyCollection(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean());
}
 
Example #26
Source File: ReadCSVStepTest.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
@Test
public void readNone() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
            "  List<CSVRecord> records = readCSV()\n" +
            "}", true));
    WorkflowRun run = p.scheduleBuild2(0).get();
    j.assertBuildStatus(Result.FAILURE, run);
    j.assertLogContains(AbstractFileOrTextStepDescriptorImpl_missingRequiredArgument("readCSV"), run);
}
 
Example #27
Source File: CFNUpdateStackTests.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void updateExistantStack() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeOutputs()).thenReturn(Collections.singletonMap("foo", "bar"));
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  cfnUpdate(stack: 'foo')"
													+ "}\n", true)
	);
	this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	Mockito.verify(this.stack).update(Mockito.anyString(), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class), Mockito.anyCollectionOf(String.class), Mockito.any(), Mockito.anyString(), Mockito.any());
}
 
Example #28
Source File: VaultSecretSourceTest.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("vault.yml")
@EnvsFromFile(value = {VAULT_AGENT_FILE, VAULT_APPROLE_FILE})
public void vaultReturns404() throws Exception {
    WorkflowJob pipeline = j.createProject(WorkflowJob.class, "Pipeline");
    String pipelineText =  IOUtils.toString(TestConstants.class.getResourceAsStream("pipeline.groovy"));
    pipeline.setDefinition(new CpsFlowDefinition(pipelineText, true));

    WorkflowRun build = pipeline.scheduleBuild2(0).get();

    j.assertBuildStatus(Result.FAILURE, build);
    j.assertLogContains("Vault credentials not found for '" + VAULT_PATH_KV1_1 + "'", build);
}
 
Example #29
Source File: PipelineRunImplTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-53019")
public void testMultipleRepoChangeSet() throws Exception {
    String jenkinsFile = Resources.toString(Resources.getResource(getClass(), "mulitpleScms.jenkinsfile"), Charsets.UTF_8).replaceAll("%REPO1%", sampleRepo1.toString()).replaceAll("%REPO2%", sampleRepo2.toString());

    WorkflowJob p = j.createProject(WorkflowJob.class, "project");
    p.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    p.save();

    sampleRepo1.init();
    sampleRepo2.init();

    j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0));

    updateREADME(sampleRepo1);
    updateREADME(sampleRepo2);
    TimeUnit.SECONDS.sleep(1);
    updateREADME(sampleRepo2);
    TimeUnit.SECONDS.sleep(1);

    Run r = j.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0));

    Map<String, Object> runDetails = get("/organizations/jenkins/pipelines/" + p.getName() + "/runs/" + r.getId() + "/");
    HashSet<String> commitIds = new HashSet<>();
    for (Object o : (ArrayList) runDetails.get("changeSet")) {
        commitIds.add(((Map) o).get("checkoutCount").toString());
    }
    assertEquals(3, ((ArrayList) runDetails.get("changeSet")).size());
    assertEquals(new HashSet<>(Arrays.asList("0", "1")), commitIds);
}
 
Example #30
Source File: KubernetesPipelineTest.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleMaven() throws Exception {
    configureCloud(r);
    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(loadPipelineScript("simpleMaven.groovy")
            , true));
    WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    assertNotNull(b);
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
    r.assertLogContains("Apache Maven 3.3.9", b);
}