org.jvnet.hudson.test.JenkinsRule Java Examples
The following examples show how to use
org.jvnet.hudson.test.JenkinsRule.
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: JmhBenchmarkState.java From jenkins-test-harness with MIT License | 6 votes |
private void launchInstance() throws Exception { ImmutablePair<Server, ServletContext> results = JenkinsRule._createWebServer(contextPath, localPort::setValue, getClass().getClassLoader(), localPort.getValue(), JenkinsRule::_configureUserRealm); server = results.left; ServletContext webServer = results.right; jenkins = new Hudson(temporaryDirectoryAllocator.allocate(), webServer); JenkinsRule._configureJenkinsForTest(jenkins); JenkinsRule._configureUpdateCenter(jenkins); jenkins.getActions().add(this); String url = Objects.requireNonNull(getJenkinsURL()).toString(); Objects.requireNonNull(JenkinsLocationConfiguration.get()).setUrl(url); LOGGER.log(Level.INFO, "Running on {0}", url); }
Example #2
Source File: MattermostSendStepIntegrationTest.java From jenkins-mattermost-plugin with MIT License | 6 votes |
@Test public void test_global_config_override() 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');", true)); WorkflowRun run = jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0).get()); // everything should come from step configuration //jenkinsRule.assertLogContains( String format = String.format( "Mattermost Send Pipeline step configured values from global config - connector: %s, icon: %s, channel: %s, color: %s", false, false, false, false); String log = JenkinsRule.getLog(run); Assert.assertTrue(log.contains(format)); // run); }
Example #3
Source File: RoundTripAbstractTest.java From configuration-as-code-plugin with MIT License | 6 votes |
private void applyConfigViaWebUI(String jenkinsConfig) throws Exception { // The UI requires the path to the config file File f = tempFolder.newFile(); writeToFile(jenkinsConfig, f.getAbsolutePath()); // Call the replace url JenkinsRule.WebClient client = r.j.createWebClient(); WebRequest request = new WebRequest(client.createCrumbedUrl("configuration-as-code/replace"), POST); NameValuePair param = new NameValuePair("_.newSource", f.toURI().toURL().toExternalForm()); request.setRequestParameters(Collections.singletonList(param)); request.setRequestParameters(Collections.singletonList(param)); WebResponse response = client.loadWebResponse(request); assertEquals("Failed to POST to " + request.getUrl().toString(), 200, response.getStatusCode()); String res = response.getContentAsString(); /* The result page has: Configuration loaded from : <ul> <li>path</li> </ul> path is the file used to store the configuration. */ assertThat(res, containsString(f.toURI().toURL().toExternalForm())); }
Example #4
Source File: KubernetesPipelineTest.java From kubernetes-plugin with Apache License 2.0 | 6 votes |
@Test public void computerCantBeConfigured() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.ADMINISTER).everywhere().to("admin")); SemaphoreStep.waitForStart("pod/1", b); Optional<KubernetesSlave> optionalNode = r.jenkins.getNodes().stream().filter(KubernetesSlave.class::isInstance).map(KubernetesSlave.class::cast).findAny(); assertTrue(optionalNode.isPresent()); KubernetesSlave node = optionalNode.get(); JenkinsRule.WebClient wc = r.createWebClient().login("admin"); wc.getOptions().setPrintContentOnFailingStatusCode(false); HtmlPage nodeIndex = wc.getPage(node); assertNotXPath(nodeIndex, "//*[text() = 'configure']"); wc.assertFails(node.toComputer().getUrl()+"configure", 403); SemaphoreStep.success("pod/1", null); }
Example #5
Source File: KubernetesCloudTest.java From kubernetes-plugin with Apache License 2.0 | 6 votes |
@Test public void defaultWorkspaceVolume() throws Exception { KubernetesCloud cloud = new KubernetesCloud("kubernetes"); j.jenkins.clouds.add(cloud); j.jenkins.save(); JenkinsRule.WebClient wc = j.createWebClient(); HtmlPage p = wc.goTo("configureClouds/"); HtmlForm f = p.getFormByName("config"); HtmlButton buttonExtends = HtmlFormUtil.getButtonByCaption(f, "Pod Templates..."); buttonExtends.click(); HtmlButton buttonAdd = HtmlFormUtil.getButtonByCaption(f, "Add Pod Template"); buttonAdd.click(); HtmlButton buttonDetails = HtmlFormUtil.getButtonByCaption(f, "Pod Template details..."); buttonDetails.click(); DomElement templates = p.getElementByName("templates"); HtmlInput templateName = getInputByName(templates, "_.name"); templateName.setValueAttribute("default-workspace-volume"); j.submit(f); cloud = j.jenkins.clouds.get(KubernetesCloud.class); PodTemplate podTemplate = cloud.getTemplates().get(0); assertEquals("default-workspace-volume", podTemplate.getName()); assertEquals(WorkspaceVolume.getDefault(), podTemplate.getWorkspaceVolume()); }
Example #6
Source File: GerritReviewStepTest.java From gerrit-code-review-plugin with Apache License 2.0 | 6 votes |
@Test public void gerritCommentStepInvokeMissingCredTest() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition( new CpsFlowDefinition( "node {\n" + " withEnv([\n" + " 'GERRIT_API_URL=http://host/a/project',\n" + " 'GERRIT_CREDENTIALS_ID=cid',\n" + " ]) {\n" + " gerritReview label: 'Verified', score: -1, message: 'Does not work'\n" + " }\n" + "}", true)); WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); String log = JenkinsRule.getLog(run); j.assertLogContains("Gerrit Review requires authentication", run); }
Example #7
Source File: GerritReviewStepTest.java From gerrit-code-review-plugin with Apache License 2.0 | 6 votes |
@Test public void gerritCommentStepInvokeNoCredTest() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition( new CpsFlowDefinition( "node {\n" + " withEnv([\n" + " 'GERRIT_API_URL=http://host/a/project',\n" + " ]) {\n" + " gerritReview label: 'Verified', score: -1, message: 'Does not work'\n" + " }\n" + "}", true)); WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); String log = JenkinsRule.getLog(run); j.assertLogContains("Gerrit Review requires authentication", run); }
Example #8
Source File: GerritReviewStepTest.java From gerrit-code-review-plugin with Apache License 2.0 | 6 votes |
@Test public void gerritCommentStepInvokeNoAPITest() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition( new CpsFlowDefinition( "node {\n" + " withEnv([\n" + " ]) {\n" + " gerritReview label: 'Verified', score: -1, message: 'Does not work'\n" + " }\n" + "}", true)); WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0)); String log = JenkinsRule.getLog(run); j.assertLogContains("Gerrit Review is disabled no API URL", run); }
Example #9
Source File: Security1290Test.java From configuration-as-code-plugin with MIT License | 6 votes |
@Test public void configurationAsCodePagesPermissions() throws Exception { final String ADMIN = "admin"; final String USER = "user"; j.jenkins.setCrumbIssuer(null); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() .grant(Jenkins.ADMINISTER).everywhere().to(ADMIN) .grant(Jenkins.READ).everywhere().to(USER) ); JenkinsRule.WebClient adminWc = j.createWebClient(); adminWc.login(ADMIN); JenkinsRule.WebClient userWc = j.createWebClient() .withThrowExceptionOnFailingStatusCode(false); userWc.login(USER); assertRightPermissionConfigurations("configuration-as-code/schema", adminWc, userWc); assertRightPermissionConfigurations("configuration-as-code/reference", adminWc, userWc); }
Example #10
Source File: DockerDirectiveGeneratorTest.java From docker-workflow-plugin with MIT License | 6 votes |
private void assertGenerateDirective(@Nonnull AbstractDirective desc, @Nonnull String responseText) throws Exception { // First, make sure the expected response text actually matches the toGroovy for the directive. assertEquals(desc.toGroovy(true), responseText); // Then submit the form with the appropriate JSON (we generate it from the directive, but it matches the form JSON exactly) JenkinsRule.WebClient wc = r.createWebClient(); WebRequest wrs = new WebRequest(new URL(r.getURL(), DirectiveGenerator.GENERATE_URL), HttpMethod.POST); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("json", staplerJsonForDescr(desc).toString())); // WebClient.addCrumb *replaces* rather than *adds*: params.add(new NameValuePair(r.jenkins.getCrumbIssuer().getDescriptor().getCrumbRequestField(), r.jenkins.getCrumbIssuer().getCrumb(null))); wrs.setRequestParameters(params); WebResponse response = wc.getPage(wrs).getWebResponse(); assertEquals("text/plain", response.getContentType()); assertEquals(responseText, response.getContentAsString().trim()); }
Example #11
Source File: CLICommandInvoker.java From jenkins-test-harness with MIT License | 6 votes |
private void setAuth() { if (permissions.isEmpty()) return; JenkinsRule.DummySecurityRealm realm = rule.createDummySecurityRealm(); realm.addGroups(username, "group"); originalSecurityRealm = rule.jenkins.getSecurityRealm(); rule.jenkins.setSecurityRealm(realm); originalAuthorizationStrategy = rule.jenkins.getAuthorizationStrategy(); rule.jenkins.setAuthorizationStrategy(new GrantPermissions(username, permissions)); command.setTransportAuth(user().impersonate()); // Otherwise it is SYSTEM, which would be relevant for a command overriding main: originalSecurityContext = ACL.impersonate(Jenkins.ANONYMOUS); }
Example #12
Source File: SaveableChangeListenerTest.java From audit-log-plugin with MIT License | 6 votes |
@Issue("ISSUE-35") @Test public void testOnCredentialsUsage() throws Exception { UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob","secret"); CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), credentials); JenkinsRule.WebClient wc = j.createWebClient(); FreeStyleProject job = j.createFreeStyleProject(); job.addProperty(new ParametersDefinitionProperty( new CredentialsParameterDefinition( "SECRET", "The secret", "secret-id", Credentials.class.getName(), false ))); job.getBuildersList().add(new CaptureEnvironmentBuilder()); job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))).get(); List<LogEvent> events = app.getEvents(); assertThat(events).hasSize(4); assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).containsSequence("createItem", "buildStart", "useCredentials", "buildFinish"); }
Example #13
Source File: DockerNodeStepTest.java From docker-plugin with MIT License | 6 votes |
private void doCleanUp() { try { // remove all nodes final JenkinsRule j = story.j; final Jenkins jenkins = j.jenkins; final List<Node> nodes = jenkins.getNodes(); for (final Node node : nodes) { jenkins.removeNode(node); } // now trigger the docker cleanup, telling it it's long overdue. final DockerContainerWatchdog cleaner = jenkins.getExtensionList(DockerContainerWatchdog.class).get(0); final String cleanerThreadName = cleaner.name; final Clock now = Clock.systemUTC(); final Clock future = Clock.offset(now, Duration.ofMinutes(60)); waitUntilNoThreadRunning(cleanerThreadName); TestableDockerContainerWatchdog.setClockOn(cleaner, future); cleaner.doRun(); waitUntilNoThreadRunning(cleanerThreadName); TestableDockerContainerWatchdog.setClockOn(cleaner, now); } catch (Throwable loggedAndSuppressed) { loggedAndSuppressed.printStackTrace(); } }
Example #14
Source File: ReadYamlStepTest.java From pipeline-utility-steps-plugin with MIT License | 6 votes |
@Test public void readText() throws Exception { WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "def yaml = readYaml text: '''" + yamlText + "'''\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)); WorkflowRun run = p.scheduleBuild2(0).get(); System.out.println(JenkinsRule.getLog(run)); j.assertBuildStatusSuccess(run); }
Example #15
Source File: TestHelpers.java From lockable-resources-plugin with MIT License | 6 votes |
/** * Get a resource from the JSON API and validate some basic properties. This allows to verify that * the API returns sane values while running other tests. */ public static JSONObject getResourceFromApi( JenkinsRule rule, String resourceName, boolean isLocked) throws IOException { JSONObject data = getApiData(rule); JSONArray resources = data.getJSONArray("resources"); assertThat(resources, is(not(nullValue()))); JSONObject res = (JSONObject) (resources.stream() .filter(e -> resourceName.equals(((JSONObject) e).getString("name"))) .findAny() .orElseThrow( () -> new AssertionError("Could not find '" + resourceName + "' in API."))); assertThat(res, hasEntry("locked", isLocked)); return res; }
Example #16
Source File: AbsolutePathGeneratorITest.java From warnings-ng-plugin with MIT License | 6 votes |
@SuppressWarnings("checkstyle:IllegalCatch") private Slave createAgentWithWrongWorkspaceFolder() { try { JenkinsRule jenkinsRule = getJenkins(); int size = jenkinsRule.jenkins.getNodes().size(); DumbSlave slave = new DumbSlave("slave" + size, agentWorkspace.getRoot().getPath().toLowerCase(Locale.ENGLISH), jenkinsRule.createComputerLauncher(null)); slave.setLabelString("agent"); jenkinsRule.jenkins.addNode(slave); jenkinsRule.waitOnline(slave); return slave; } catch (Exception e) { throw new AssertionError(e); } }
Example #17
Source File: Migrate2_3xIT.java From aws-codecommit-trigger-plugin with Apache License 2.0 | 5 votes |
@Test public void shouldNotSeeMigrationButton() throws IOException, SAXException { JenkinsRule.WebClient webClient = jenkinsRule.createWebClient(); DomElement configureSection = webClient.goTo("configure").getElementsByName("AwsCodeCommitTriggerPlugin").get(0); List<?> buttons = configureSection.getByXPath("//button[contains(.,'Migration')]"); Assertions.assertThat(buttons).isEmpty(); }
Example #18
Source File: CLICommandInvoker.java From jenkins-test-harness with MIT License | 5 votes |
public CLICommandInvoker(final JenkinsRule rule, final CLICommand command) { if (command.getClass().getAnnotation(Extension.class) == null) { throw new AssertionError(String.format( "Command %s is missing @Extension annotation.", command.getClass() )); } this.rule = rule; this.command = command; }
Example #19
Source File: GogsWebHookJenkinsTest.java From gogs-webhook-plugin with MIT License | 5 votes |
@Test @Issue("SECURITY-1438") public void ensureTheSecretIsEncryptedInHtml() throws Exception { Secret secret = Secret.fromString("s3cr3t"); FreeStyleProject p = prepareProjectWithGogsProperty(secret); JenkinsRule.WebClient wc = j.createWebClient(); // there are some errors in the page and thus the status is 500 but the content is there wc.getOptions().setThrowExceptionOnFailingStatusCode(false); HtmlPage htmlPage = wc.goTo(p.getUrl() + "configure"); String pageContent = htmlPage.getWebResponse().getContentAsString(); assertThat(pageContent, not(containsString(secret.getPlainText()))); assertThat(pageContent, containsString(secret.getEncryptedValue())); }
Example #20
Source File: GlobalRoleBenchmark.java From folder-auth-plugin with MIT License | 5 votes |
@Override public void setup() { getJenkins().setSecurityRealm(new JenkinsRule().createDummySecurityRealm()); Set<GlobalRole> globalRoles = new HashSet<>(); for (int i = 0; i < getRoleCount(); i++) { globalRoles.add(new GlobalRole("role" + i, wrapPermissions(Item.DISCOVER, Item.CONFIGURE), ImmutableSet.of("user" + i))); } FolderBasedAuthorizationStrategy strategy = new FolderBasedAuthorizationStrategy( globalRoles, Collections.emptySet(), Collections.emptySet()); acl = strategy.getRootACL(); assertFalse(acl.hasPermission(Objects.requireNonNull(User.getById("user3", true)).impersonate(), Item.CREATE)); }
Example #21
Source File: TestUtils.java From phabricator-jenkins-plugin with MIT License | 5 votes |
public static LauncherFactory createLauncherFactory(JenkinsRule j) throws Exception { return new LauncherFactory( j.createLocalLauncher(), getDefaultEnvVars(), System.err, new FilePath(j.getWebAppRoot()) ); }
Example #22
Source File: EndpointTest.java From github-branch-source-plugin with MIT License | 5 votes |
private Page post(String relative, String userName) throws Exception { final JenkinsRule.WebClient client; if (userName != null) { client = j.createWebClient().login(userName); } else { client = j.createWebClient(); } final WebRequest request = new WebRequest(new URL(client.getContextPath() + relative), client.getBrowserVersion().getHtmlAcceptHeader()); request.setHttpMethod(HttpMethod.POST); request.setRequestParameters(Arrays.asList(new NameValuePair(Functions.getCrumbRequestField(), Functions.getCrumb(null)))); return client.getPage(request); }
Example #23
Source File: DockerTraceabilityRootActionTest.java From docker-traceability-plugin with MIT License | 5 votes |
@Test public void rawContainerDockerInspectSubmissions() throws Exception { // Read data from resources String inspectData = JSONSamples.inspectContainerData.readString(); InspectContainerResponse inspectResponse = JSONSamples.inspectContainerData. readObject(InspectContainerResponse[].class)[0]; final String containerId = inspectResponse.getId(); final String imageId = inspectResponse.getImageId(); // Init system data JenkinsRule.WebClient client = j.createWebClient(); final DockerTraceabilityRootAction action = DockerTraceabilityRootAction.getInstance(); assertNotNull(action); // Prepare a run with Fingerprints and referenced facets createTestBuildRefFacet(imageId, "test"); // Submit JSON action.doSubmitContainerStatus(inspectData, null, null, null, 0, null, null); // Ensure there's a fingerprint for container, which refers the image final DockerDeploymentFacet containerFacet = assertExistsDeploymentFacet(containerId, imageId); // Ensure there's a fingerprint for image final DockerDeploymentRefFacet containerRefFacet = assertExistsDeploymentRefFacet(containerId, imageId); // Try to call the actions method to retrieve the data final Page res; try { res = client.goTo("docker-traceability/rawContainerInfo?id="+containerId, null); } catch (Exception ex) { ex.getMessage(); throw new AssertionError("Cannot get a response from rawInfo page", ex); } final String responseJSON = res.getWebResponse().getContentAsString(); ObjectMapper mapper= new ObjectMapper(); final InspectContainerResponse[] parsedData = mapper.readValue(responseJSON, InspectContainerResponse[].class); assertEquals(1, parsedData.length); }
Example #24
Source File: DockerTraceabilityRootActionTest.java From docker-traceability-plugin with MIT License | 5 votes |
@Test public void containerIDs_CRUD() throws Exception { // TODO: replace by a helper method from the branch JenkinsRule.WebClient client = j.createWebClient(); @CheckForNull DockerTraceabilityRootAction action = null; for (Action rootAction : j.getInstance().getActions()) { if (rootAction instanceof DockerTraceabilityRootAction) { action = (DockerTraceabilityRootAction) rootAction; break; } } assertNotNull(action); final String id1 = FingerprintTestUtil.generateDockerId("1"); final String id2 = FingerprintTestUtil.generateDockerId("2"); final String id3 = FingerprintTestUtil.generateDockerId("3"); // Check consistency of create/update commands action.addContainerID(id1); assertEquals(1, action.getContainerIDs().size()); action.addContainerID(id2); assertEquals(2, action.getContainerIDs().size()); action.addContainerID(id2); assertEquals(2, action.getContainerIDs().size()); // Remove data using API. First entry is non-existent action.doDeleteContainer(id3); assertEquals(2, action.getContainerIDs().size()); action.doDeleteContainer(id1); assertEquals(1, action.getContainerIDs().size()); action.doDeleteContainer(id1); assertEquals(1, action.getContainerIDs().size()); // Reload the data and ensure the status has been persisted correctly action = new DockerTraceabilityRootAction(); assertEquals(1, action.getContainerIDs().size()); for (String id : action.getContainerIDs()) { assertEquals(id2, id); } }
Example #25
Source File: TestReportUiTest.java From junit-plugin with MIT License | 5 votes |
/** * Validate CSS styles present to prevent duration text from wrapping */ @Issue("JENKINS-24352") @Test public void testDurationStyle() throws Exception { AbstractBuild b = configureTestBuild("render-test"); JenkinsRule.WebClient wc = j.createWebClient(); wc.setAlertHandler(new AlertHandler() { @Override public void handleAlert(Page page, String message) { throw new AssertionError(); } }); HtmlPage pg = wc.getPage(b, "testReport"); // these are from the test result file: String duration14sec = Util.getTimeSpanString((long) (14.398 * 1000)); String duration3_3sec = Util.getTimeSpanString((long) (3.377 * 1000)); String duration2_5sec = Util.getTimeSpanString((long) (2.502 * 1000)); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]")); pg = wc.getPage(b, "testReport/org.twia.vendor"); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration3_3sec + "')][contains(@class,'no-wrap')]")); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration14sec + "')][contains(@class,'no-wrap')]")); pg = wc.getPage(b, "testReport/org.twia.vendor/VendorManagerTest"); Assert.assertNotNull(pg.getFirstByXPath("//td[contains(text(),'" + duration2_5sec + "')][contains(@class,'no-wrap')]")); }
Example #26
Source File: TestUtility.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
static void setupGitLabConnections(JenkinsRule jenkins, MockServerRule mockServer) throws IOException { GitLabConnectionConfig connectionConfig = jenkins.get(GitLabConnectionConfig.class); String apiTokenId = "apiTokenId"; for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); credentialsStore.addCredentials(domains.get(0), new StringCredentialsImpl(CredentialsScope.SYSTEM, apiTokenId, "GitLab API Token", Secret.fromString(TestUtility.API_TOKEN))); } } connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V3, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V3GitLabClientBuilder(), false, 10, 10)); connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V4, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V4GitLabClientBuilder(), false, 10, 10)); }
Example #27
Source File: IntegrationTest.java From zulip-plugin with MIT License | 5 votes |
@Test public void testFreestyle() throws Exception { // Initialize project with send and notification step FreeStyleProject project = j.createFreeStyleProject(); ZulipSendStep sendStep = new ZulipSendStep(); sendStep.setStream("testStream"); sendStep.setTopic("testTopic"); sendStep.setMessage("testMessage"); project.getBuildersList().add(sendStep); ZulipNotifier notifier = new ZulipNotifier(); notifier.setStream("testStream"); notifier.setTopic("testTopic"); project.getPublishersList().add(notifier); // Do a round-trip to verify project settings load & save correctly JenkinsRule.WebClient webClient = j.createWebClient(); HtmlPage p = webClient.getPage(project, "configure"); HtmlForm f = p.getFormByName("config"); j.submit(f); ZulipSendStep assertStep = project.getBuildersList().get(ZulipSendStep.class); assertEquals("testStream", assertStep.getStream()); assertEquals("testTopic", assertStep.getTopic()); assertEquals("testMessage", assertStep.getMessage()); ZulipNotifier assertNotifier = project.getPublishersList().get(ZulipNotifier.class); assertEquals("testStream", assertNotifier.getStream()); assertEquals("testTopic", assertNotifier.getTopic()); // Perform build and verify it's successful j.buildAndAssertSuccess(project); verifyNotificationsSent(2); }
Example #28
Source File: LockStepTest.java From lockable-resources-plugin with MIT License | 5 votes |
@Test public void unlockButtonWithWaitingRuns() throws Exception { LockableResourcesManager.get().createResource("resource1"); WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition( new CpsFlowDefinition( "retry(99) {\n" + " lock('resource1') {\n" + " semaphore('wait-inside')\n" + " }\n" + "}", true)); JenkinsRule.WebClient wc = j.createWebClient(); WorkflowRun prevBuild = null; for (int i = 0; i < 3; i++) { WorkflowRun rNext = p.scheduleBuild2(0).waitForStart(); if (prevBuild != null) { j.waitForMessage( "[resource1] is locked by " + prevBuild.getFullDisplayName() + ", waiting...", rNext); isPaused(rNext, 1, 1); wc.goTo("lockable-resources/unlock?resource=resource1"); } j.waitForMessage("Lock acquired on [resource1]", rNext); SemaphoreStep.waitForStart("wait-inside/" + (i + 1), rNext); isPaused(rNext, 1, 0); if (prevBuild != null) { SemaphoreStep.success("wait-inside/" + i, null); j.assertBuildStatusSuccess(j.waitForCompletion(prevBuild)); } prevBuild = rNext; } SemaphoreStep.success("wait-inside/3", null); j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(prevBuild)); }
Example #29
Source File: LockStepTest.java From lockable-resources-plugin with MIT License | 5 votes |
@Issue("JENKINS-34433") @Test public void manualUnreserveUnblocksJob() throws Exception { LockableResourcesManager.get().createResource("resource1"); JenkinsRule.WebClient wc = j.createWebClient(); wc.goTo("lockable-resources/reserve?resource=resource1"); LockableResource resource1 = LockableResourcesManager.get().fromName("resource1"); assertNotNull(resource1); resource1.setReservedBy("someone"); assertTrue(resource1.isReserved()); JSONObject apiRes = TestHelpers.getResourceFromApi(j, "resource1", false); assertThat(apiRes, hasEntry("reserved", true)); assertThat(apiRes, hasEntry("reservedBy", "someone")); WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition( new CpsFlowDefinition( "retry(99) {\n" + " lock('resource1') {\n" + " semaphore('wait-inside')\n" + " }\n" + "}", true)); WorkflowRun r = p.scheduleBuild2(0).waitForStart(); j.waitForMessage("[resource1] is locked, waiting...", r); wc.goTo("lockable-resources/unreserve?resource=resource1"); SemaphoreStep.waitForStart("wait-inside/1", r); SemaphoreStep.success("wait-inside/1", null); j.assertBuildStatusSuccess(j.waitForCompletion(r)); }
Example #30
Source File: GitClientSampleRepoRule.java From git-client-plugin with MIT License | 5 votes |
public void notifyCommit(JenkinsRule r) throws Exception { synchronousPolling(r); WebResponse webResponse = r.createWebClient().goTo("git/notifyCommit?url=" + bareUrl(), "text/plain").getWebResponse(); LOGGER.log(Level.FINE, webResponse.getContentAsString()); for (NameValuePair pair : webResponse.getResponseHeaders()) { if (pair.getName().equals("Triggered")) { LOGGER.log(Level.FINE, "Triggered: " + pair.getValue()); } } r.waitUntilNoActivity(); }