org.jenkinsci.plugins.workflow.job.WorkflowJob Java Examples

The following examples show how to use org.jenkinsci.plugins.workflow.job.WorkflowJob. 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: S3PresignUrlStepTests.java    From pipeline-aws-plugin with Apache License 2.0 7 votes vote down vote up
@Test
public void presignWithCustomMethod() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "s3PresignTest");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def url = s3PresignURL(bucket: 'foo', key: 'bar', httpMethod: 'POST')\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);

	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"), Mockito.any(), Mockito.eq(HttpMethod.POST));
}
 
Example #2
Source File: StepsITest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
/**
 * Registers a new {@link GroovyParser} (a Pep8 parser) in Jenkins global configuration and runs this parser on an
 * error log with 8 issues.
 */
@Test
public void shouldShowWarningsOfGroovyParser() {
    WorkflowJob job = createPipelineWithWorkspaceFiles("pep8Test.txt");
    job.setDefinition(asStage(
            "def groovy = scanForIssues "
                    + "tool: groovyScript(parserId: 'groovy-pep8', pattern:'**/*issues.txt', reportEncoding:'UTF-8')",
            "publishIssues issues:[groovy]"));

    ParserConfiguration configuration = ParserConfiguration.getInstance();
    String id = "groovy-pep8";
    configuration.setParsers(Collections.singletonList(
            new GroovyParser(id, "Groovy Pep8",
                    "(.*):(\\d+):(\\d+): (\\D\\d*) (.*)",
                    toString("groovy/pep8.groovy"), "")));
    Run<?, ?> run = buildSuccessfully(job);

    ResultAction action = getResultAction(run);
    assertThat(action.getId()).isEqualTo(id);
    assertThat(action.getDisplayName()).contains("Groovy Pep8");

    AnalysisResult result = action.getResult();
    assertThat(result.getIssues()).hasSize(8);
    assertThat(result.getIssues().getPropertyCount(Issue::getOrigin)).containsOnly(entry(id, 8));
}
 
Example #3
Source File: WithContainerStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void death() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            DockerTestUtil.assumeDocker();
            logging.record(BourneShellScript.class, Level.FINE);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                "node {\n" +
                "  withDockerContainer('httpd:2.4.12') {\n" +
                "    sh \"sleep 5; ps -e -o pid,command | egrep '${pwd tmp: true}/durable-.+/script.sh' | fgrep -v grep | sort -n | tr -s ' ' | cut -d ' ' -f2 | xargs kill -9\"\n" +
                "  }\n" +
                "}", true));
            Field hci = BourneShellScript.class.getDeclaredField("HEARTBEAT_CHECK_INTERVAL");
            hci.setAccessible(true);
            int orig = (int) hci.get(null);
            hci.set(null, 5);
            try {
                WorkflowRun b = story.j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
                story.j.assertLogContains("script returned exit code -1", b);
            } finally {
                hci.set(null, orig);
            }
        }
    });
}
 
Example #4
Source File: CertificateMultiBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Test
public void basicsPipeline() throws Exception {
	// create the Credentials
	String alias = "androiddebugkey";
	String password = "android";
	StandardCertificateCredentials c = new CertificateCredentialsImpl(CredentialsScope.GLOBAL, "my-certificate", alias,
			password, new CertificateCredentialsImpl.FileOnMasterKeyStoreSource(certificate.getAbsolutePath()));
	CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
	// create the Pipeline job
	WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
	String pipelineScript = IOUtils.toString(getTestResourceInputStream("basicsPipeline-Jenkinsfile"));
	p.setDefinition(new CpsFlowDefinition(pipelineScript, true));
	// copy resources into workspace
	FilePath workspace = r.jenkins.getWorkspaceFor(p);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.sh", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.sh", 0755);
	// execute the pipeline
	WorkflowRun b = p.scheduleBuild2(0).waitForStart();
	r.waitForCompletion(b);
	r.assertBuildStatusSuccess(b);
}
 
Example #5
Source File: ReadPropertiesStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void readText() throws Exception {
    Properties props = new Properties();
    props.setProperty("test", "One");
    props.setProperty("another", "Two");
    StringWriter propsString = new StringWriter();
    props.store(propsString, "Pipeline test");

    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
                    "def props = readProperties text: '''" + propsString.toString() + "'''\n" +
                    "assert props['test'] == 'One'\n" +
                    "assert props['another'] == 'Two'\n" +
                    "assert props.test == 'One'\n" +
                    "assert props.another == 'Two'\n", true));
    j.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
 
Example #6
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetStackParametersFromMap() 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()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', params: ['foo': 'bar', 'baz': 'true'])\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.anyString(), Mockito.anyString(), Mockito.eq(Arrays.asList(
			new Parameter().withParameterKey("foo").withParameterValue("bar"),
			new Parameter().withParameterKey("baz").withParameterValue("true")
	)), Mockito.anyCollectionOf(Tag.class), Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(),
											   Mockito.any());
}
 
Example #7
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 #8
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStepWithNotFoundGlobalCredentials() throws Exception {

	String globalBaseCreds = "something-random";

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(globalBaseCreds);

	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithNotFoundGlobalCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + globalBaseCreds + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);

	jenkinsRule.assertBuildStatus(Result.FAILURE, job.scheduleBuild2(0));
}
 
Example #9
Source File: WithContainerStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void basics() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            DockerTestUtil.assumeDocker();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                "node {\n" +
                "  withDockerContainer('httpd:2.4.12') {\n" +
                "    sh 'cp /usr/local/apache2/conf/extra/httpd-userdir.conf .; ls -la'\n" +
                "  }\n" +
                "  sh 'ls -la; cat *.conf'\n" +
                "}", true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            story.j.assertLogContains("Require method GET POST OPTIONS", b);
        }
    });
}
 
Example #10
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 #11
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
@Test
public void skipIfLocked() throws Exception {
  LockableResourcesManager lm = LockableResourcesManager.get();
  lm.createResourceWithLabel("resource1", "label1");
  lm.reserve(Arrays.asList(lm.fromName("resource1")), "test");

  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(resource: 'resource1', skipIfLocked: true) {\n" + "  echo 'Running body'\n" + "}",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  j.waitForCompletion(b1);
  j.assertBuildStatus(Result.SUCCESS, b1);
  j.assertLogContains("[resource1] is locked, skipping execution...", b1);
  j.assertLogNotContains("Running body", b1);
}
 
Example #12
Source File: ReadYamlStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
  public void checksPrimitivesAndDates() throws Exception {
WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
		"node('slaves') {\n" + "  def yaml = readYaml text: '''" + yamlText + "'''\n" 
				+ "  assert yaml.getClass().getName() == 'java.util.LinkedHashMap'\n" +
				"  assert yaml.boolean.getClass().getName() == 'java.lang.Boolean'\n" +
				"  assert yaml.string.getClass().getName() == 'java.lang.String'\n" +
				"  assert yaml.integer.getClass().getName() == 'java.lang.Integer'\n" +
				"  assert yaml.double.getClass().getName() == 'java.lang.Double'\n" +
				"  def timeZone = TimeZone.getTimeZone('UTC')\n" +
				"  assert yaml.date.format('yyyy-MM-dd HH:mm:ss',timeZone) == '2001-12-14 21:59:43'\n" +
				"  assert yaml.date.getClass().getName() == 'java.util.Date'\n" +
				"  assert yaml.billTo.getClass().getName() == 'java.util.LinkedHashMap'\n" +
				"  assert yaml.billTo.address.getClass().getName() == 'java.util.LinkedHashMap'\n" +
				"  assert yaml.billTo.address.postal.getClass().getName() == 'java.lang.Integer'\n" +
				"  assert yaml.array.getClass().getName() == 'java.util.ArrayList'\n" +
		        "  assert yaml.array[0].getClass().getName() == 'java.lang.String'\n" +
				"  assert yaml.array[1].getClass().getName() == 'java.lang.String'\n" +
		        "}",
		true));
j.assertBuildStatusSuccess(p.scheduleBuild2(0));
  }
 
Example #13
Source File: WithMavenStepTest.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void disable_all_publishers() throws Exception {

    loadMonoDependencyMavenProjectInGitRepo( this.gitRepoRule );

    String pipelineScript = "node('master') {\n" + "    git($/" + gitRepoRule.toString() + "/$)\n"
            + "    withMaven(publisherStrategy: 'EXPLICIT') {\n"
            + "        sh 'mvn package'\n"
            + "    }\n"
            + "}";

    String commonsLang3version35Md5 = "780b5a8b72eebe6d0dbff1c11b5658fa";
    WorkflowJob firstPipeline = jenkinsRule.createProject(WorkflowJob.class, "disable-all-publishers");
    firstPipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
    jenkinsRule.assertBuildStatus(Result.SUCCESS, firstPipeline.scheduleBuild2(0));
    FingerprintMap fingerprintMap = jenkinsRule.jenkins.getFingerprintMap();
    Fingerprint fingerprint = fingerprintMap.get(commonsLang3version35Md5);
    Assert.assertThat( fingerprint, Matchers.nullValue() );
}
 
Example #14
Source File: ECRListImagesStepTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void listImages() throws Exception {
	Mockito.when(ecr.listImages(Mockito.any())).thenReturn(new ListImagesResult()
			.withImageIds(new ImageIdentifier().withImageDigest("id1").withImageTag("it1"))
			.withNextToken("next")
	).thenReturn(new ListImagesResult()
			.withImageIds(new ImageIdentifier().withImageDigest("id2").withImageTag("it2"))
	);
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def images = ecrListImages()\n"
			+ "  echo \"imagesCount=${images.size()}\"\n"
			+ "  echo \"images=${images.toString()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("imagesCount=2", run);
	this.jenkinsRule.assertLogContains("images=[[imageTag:it1, imageDigest:id1], [imageTag:it2, imageDigest:id2]]", run);

	Mockito.verify(this.ecr, Mockito.times(2)).listImages(Mockito.any());
}
 
Example #15
Source File: JobViews.java    From jenkins-build-monitor-plugin with MIT License 6 votes vote down vote up
public JobView viewOf(Job<?, ?> job) {
    List<Feature> viewFeatures = newArrayList();

    // todo: a more elegant way of assembling the features would be nice
    viewFeatures.add(new HasHeadline(new HeadlineConfig(config.shouldDisplayCommitters())));
    viewFeatures.add(new KnowsLastCompletedBuildDetails());
    viewFeatures.add(new KnowsCurrentBuildsDetails());

    if (jenkins.hasPlugin(Claim)) {
        viewFeatures.add(new CanBeClaimed());
    }

    if (jenkins.hasPlugin(Build_Failure_Analyzer)) {
        viewFeatures.add(new CanBeDiagnosedForProblems(config.getBuildFailureAnalyzerDisplayedField()));
    }

    if (jenkins.hasPlugin(Badge_Plugin)) {
        viewFeatures.add(new HasBadgesBadgePlugin());
    } else if (jenkins.hasPlugin(Groovy_Post_Build) && hasGroovyPostbuildActionClass()) {
        viewFeatures.add(new HasBadgesGroovyPostbuildPlugin());
    }

    boolean isPipelineJob = jenkins.hasPlugin(Pipeline) && job instanceof WorkflowJob;

    return JobView.of(job, viewFeatures, isPipelineJob);
}
 
Example #16
Source File: MattermostSendStepIntegrationTest.java    From jenkins-mattermost-plugin with MIT License 6 votes vote down vote up
@Test
  public void test_fail_on_error() throws Exception {
    WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow");
    // just define message
	  job.setDefinition(
			  new CpsFlowDefinition(
					  "mattermostSend(message: 'message', endpoint: 'endpoint', icon: 'icon', channel: '#channel', color: 'good', failOnError: true);",
					  true));
	  //noinspection ConstantConditions
	  //job.scheduleBuild(0,new Cause.UserIdCause());
	  QueueTaskFuture<WorkflowRun> workflowRunQueueTaskFuture = job.scheduleBuild2(0);
	  //WorkflowRun workflowRun = workflowRunQueueTaskFuture.getStartCondition().get();
	  //workflowRun.getExecutionPromise().get();
	  WorkflowRun run = jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRunQueueTaskFuture);
	  //jenkinsRule.assertBuildStatusSuccess(workflowRun);
	  // everything should come from step configuration
//	  String log = JenkinsRule.getLog(run);
//	  Assert.assertTrue(log.contains("Warn"));
	  //TODO jenkinsRule.assertLogContains(
	  //   "Mattermost notification failed. See Jenkins logs for details.", run);
  }
 
Example #17
Source File: FromFingerprintStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
private void assertBuild(final String projectName, final String pipelineCode, final String fromImage) throws Exception {
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            assumeDocker();

            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, projectName);
            p.setDefinition(new CpsFlowDefinition(pipelineCode, true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            DockerClient client = new DockerClient(new LocalLauncher(StreamTaskListener.NULL), null, null);
            String ancestorImageId = client.inspect(new EnvVars(), fromImage, ".Id");
            story.j.assertLogContains(ancestorImageId.replaceFirst("^sha256:", "").substring(0, 12), b);
            Fingerprint f = DockerFingerprints.of(ancestorImageId);
            assertNotNull(f);
            DockerDescendantFingerprintFacet descendantFacet = f.getFacet(DockerDescendantFingerprintFacet.class);
            assertNotNull(descendantFacet);
        }
    });
}
 
Example #18
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 6 votes vote down vote up
@Test
public void buildWithWrongCredentialsMustFailEnterprise() throws Exception {

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.CREDENTIALS_LOGIN_INVALID, b1);
}
 
Example #19
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
@Test
public void lockWithLabel() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', variable: 'var') {\n"
              + "	echo \"Resource locked: ${env.var}\"\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  j.waitForCompletion(b1);
  j.assertBuildStatus(Result.SUCCESS, b1);
  j.assertLogContains("Lock released on resource [Label: label1]", b1);
  j.assertLogContains("Resource locked: resource1", b1);
  isPaused(b1, 1, 0);

  assertNotNull(LockableResourcesManager.get().fromName("resource1"));
}
 
Example #20
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getPipelineWihoutNodesAllStepsTest() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");


    job1.setDefinition(new CpsFlowDefinition("node {\n" +
                                                 "    sh \"echo Building...\"\n" +
                                                 "}\n" +
                                                 "    node{\n" +
                                                 "        echo \"Unit testing...\"\n" +
                                                 "        sh \"echo Tests running\"\n" +
                                                 "        sh \"echo Tests completed\"\n" +
                                                 "    }", false
    ));
    WorkflowRun b1 = job1.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b1);

    List<Map> resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/", List.class);
    Assert.assertEquals(4, resp.size());
    String log = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/" + resp.get(0).get("id") + "/log/", String.class);
    assertNotNull(log);
}
 
Example #21
Source File: CFNDeleteStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteStackSet() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnDeleteStackSet(stackSet: 'foo')"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class)
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(StepContext.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	Mockito.verify(stackSet).delete();
}
 
Example #22
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void startMultiBranchPipelineRuns() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }
    WorkflowJob p = scheduleAndFindBranchProject(mp, "feature%2Fux-1");
    j.waitUntilNoActivity();

    Map resp = post("/organizations/jenkins/pipelines/p/branches/"+ Util.rawEncode("feature%2Fux-1")+"/runs/",
        Collections.EMPTY_MAP);
    String id = (String) resp.get("id");
    String link = getHrefFromLinks(resp, "self");
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature%252Fux-1/runs/"+id+"/", link);
}
 
Example #23
Source File: DockerDSLTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void runArgs() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            assumeDocker();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                "node {\n" +
                "  def img = docker.image('httpd:2.4.12')\n" +
                "  img.run().stop()\n" +
                "  img.run('--memory-swap=-1').stop()\n" +
                "  img.withRun {}\n" +
                "  img.withRun('--memory-swap=-1') {}\n" +
                "  img.inside {}\n" +
                "  img.inside('--memory-swap=-1') {}\n" +
            "}", true));
            story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
        }
    });
}
 
Example #24
Source File: MarathonStepTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Test that using "appid" instead of "id" shows a deprecation warning message.
 *
 * @throws Exception in case something unexpected happens
 */
@Test
public void testStepAppIdDeprecationMessage() throws Exception {
    final String groovyScript = "node { " +
            "writeFile(encoding: 'utf-8', file: 'marathon.json', text: '''%s''');\n" +
            "marathon(appid: 'testStepAppIdDeprecationMessage', url: '%s'); " +
            "}";

    TestUtils.enqueueFailureResponse(httpServer, 404);
    final String      url     = TestUtils.getHttpAddresss(httpServer);
    final String      payload = TestUtils.loadFixture("idonly.json");
    final String      script  = String.format(groovyScript, payload, url);
    final WorkflowJob job     = basicSetupWithScript(script);
    final WorkflowRun run     = basicRunWithFailure(job);
    j.assertLogContains("DEPRECATION WARNING", run);
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
}
 
Example #25
Source File: BashSecretPatternFactory2Test.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Test
// DO NOT DO THIS IN PRODUCTION; IT IS QUOTED WRONG
public void testSecretsWithBackslashesStillMaskedWhenUsedWithoutProperQuoting() throws Exception {
    WorkflowJob project = j.createProject(WorkflowJob.class);
    String password = "foo\\bar\\";
    String credentialsId = CredentialsTestUtil.registerStringCredentials(j.jenkins, password);
    project.setDefinition(new CpsFlowDefinition(
            "node {\n" +
            "  withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
                    "    sh ': $CREDENTIALS'\n" + // forgot quotes
                    "    sh(/: $CREDENTIALS/)\n" + // using Groovy variable and forgot quotes
                    "  }\n" +
                    "}", true));

    WorkflowRun run = j.assertBuildStatusSuccess(project.scheduleBuild2(0));

    j.assertLogContains(": ****", run);
    j.assertLogNotContains(password, run);
    j.assertLogNotContains("foo", run);
    j.assertLogNotContains("bar", run);
}
 
Example #26
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 #27
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-27486")
@Test public void masking() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            String credentialsId = "creds";
            String secret = "s3cr3t";
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
                    + "node {\n"
                    + "  withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'SECRET')]) {\n"
                    // forgot set +x, ran /usr/bin/env, etc.
                    + "    if (isUnix()) {sh 'echo $SECRET > oops'} else {bat 'echo %SECRET% > oops'}\n"
                    + "  }\n"
                    + "}", true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get());
            story.j.assertLogNotContains(secret, b);
            story.j.assertLogContains("echo ****", b);
        }
    });
}
 
Example #28
Source File: VaultTokenCredentialBindingIT.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldUseSpecifiedEnvironmentVariables() {
    final String credentialsId = "creds";
    final String vaultAddr = "https://localhost:8200";
    final String token = "fakeToken";
    final String jobId = "testJob";
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            VaultTokenCredential c = new VaultTokenCredential(CredentialsScope.GLOBAL,
                credentialsId, "fake description", Secret.fromString(token));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next()
                .addCredentials(Domain.global(), c);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, jobId);
            p.setDefinition(new CpsFlowDefinition(""
                + "node {\n"
                + "  withCredentials([[$class: 'VaultTokenCredentialBinding', addrVariable: 'FOO', tokenVariable: 'BAR', credentialsId: '"
                + credentialsId + "', vaultAddr: '" + vaultAddr + "']]) {\n"
                + "      " + getShellString() + " 'echo " + getVariable("FOO") + ":"
                + getVariable("BAR") + " > script'\n"
                + "  }\n"
                + "}", true));
            WorkflowRun b = p.scheduleBuild2(0).waitForStart();
            story.j.assertBuildStatus(Result.SUCCESS, story.j.waitForCompletion(b));
            story.j.assertLogNotContains(token, b);
            FilePath script = story.j.jenkins.getWorkspaceFor(p).child("script");
            assertEquals(vaultAddr + ":" + token, script.readToString().trim());
        }
    });
}
 
Example #29
Source File: WriteYamlStepTest.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
@Test
public void overwriteExistingFile() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "list");
    p.setDefinition(new CpsFlowDefinition(
            "node('slaves') {\n" +
                    "  writeFile file: 'test.yml', text: 'overwrite me' \n" +
                    "  writeYaml file: 'test.yml', overwrite: true, data: 'overwritten' \n" +
                    "  final text = readFile file: 'test.yml' \n" +
                    "  if (text != 'overwritten\\n') error('got ' + text) \n" +
                    "}",
            true));
    j.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
 
Example #30
Source File: ScriptedPipelineTest.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
/**
 * Verifies a simple scripted pipeline that fails sends the correct notifications
 * @throws Exception
 */
@Test
public void testScriptedFail() throws Exception {

    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
                    "    stage('Stage 1') {\n" +
                    "        echo 'hi'\n" +
                    "    }\n" +
                    "    stage('Stage fail') {\n" +
                    "        error 'fail on purpose'\n" +
                    "    }\n" +
                    "    stage('Stage 2') {\n" +
                    "        echo 'bye'\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)).updateBuildStatusForStage(eq("Stage 1"), eq(BuildStage.State.CompletedSuccess), anyLong());
    verify(buildStatus, times(1)).updateBuildStatusForStage(eq("Stage fail"), eq(BuildStage.State.CompletedError), anyLong());
    verify(buildStatus, times(0)).updateBuildStatusForStage(eq("Stage 2"), any(), anyLong());
    verify(buildStatus, times(1)).updateBuildStatusForJob(eq(BuildStage.State.CompletedError), any());

    verify(buildStatus, times(2)).updateBuildStatusForStage(any(), any(), anyLong());
    verify(buildStatus, times(1)).updateBuildStatusForJob(any(), any());
}