/** * Returns the URL of the webapp top page. * URL ends with '/'. * <p>This is actually the same as {@link #getURL} and should not be confused with {@link #contextPath}. */ public String getContextPath() throws IOException { return getURL().toExternalForm(); }
/** * Blocks until the ENTER key is hit. * This is useful during debugging a test so that one can inspect the state of Hudson through the web browser. */ public void interactiveBreak() throws Exception { System.out.println("Jenkins is running at " + getURL()); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
assert !path.startsWith("/"); URL postUrl = new URL(getURL().toExternalForm() + path); HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
/** * Constructs the java command for launching a jenkins-cli command. * * @param cmd the cli command to run with parameters. * @return the full command <code>java -jar path/to/jenkins-cli.jar -s theurl cmd...</code>. * @throws IOException if so * @throws URISyntaxException if so */ List<String> javaCliJarCmd(String... cmd) throws IOException, URISyntaxException { List<String> commands = new ArrayList<String>(cmd.length + 5); commands.add(String.format("%s/bin/java", System.getProperty("java.home"))); commands.add("-jar"); commands.add(new File(j.jenkins.getJnlpJars("jenkins-cli.jar").getURL().toURI()).getAbsolutePath()); commands.add("-s"); commands.add(j.getURL().toExternalForm()); Collections.addAll(commands, cmd); return commands; }
LOGGER.log(Level.INFO, "Running on {0}", getURL());
public void configureCloud() throws Exception { cloud = setupCloud(this); createSecret(cloud.connect()); cloud.getTemplates().clear(); cloud.addTemplate(buildBusyboxTemplate("busybox")); // Agents running in Kubernetes (minikube) need to connect to this server, so localhost does not work URL url = story.j.getURL(); String hostAddress = System.getProperty("jenkins.host.address"); if (hostAddress == null) { hostAddress = InetAddress.getLocalHost().getHostAddress(); } URL nonLocalhostUrl = new URL(url.getProtocol(), hostAddress, url.getPort(), url.getFile()); JenkinsLocationConfiguration.get().setUrl(nonLocalhostUrl.toString()); story.j.jenkins.clouds.add(cloud); }
/** * Remove Server from UI. * @param serverName the name of the Gerrit server you want to access. * @return true if the form had a button and was posted * @throws Exception if error removing server. */ private boolean removeServer(String serverName) throws Exception { URL url = new URL(j.getURL(), Functions.joinPath(serverURL, "server", serverName, "remove")); HtmlPage removalPage = j.createWebClient().getPage(url); HtmlForm form = removalPage.getFormByName(removalFormName); List<HtmlElement> buttons = form.getHtmlElementsByTagName("button"); textContent = form.getTextContent(); if (buttons.size() >= 1) { j.submit(form); return true; } else { return false; } }
private void assertSniff(String user, String sniffed, boolean ok) throws Exception { AuthSniffer sniffer = new AuthSniffer(); URL sniffURL = sniffer.start(); try { JenkinsRule.WebClient wc = r.createWebClient().login(user); String checkUrl = "job/p/descriptorByName/hudson.scm.listtagsparameter.ListSubversionTagsParameterDefinition/checkCredentialsId?value=svncreds&tagsDir=" + URLEncoder.encode(sniffURL.toString(), "UTF-8"); System.err.println("Connecting to " + checkUrl + " as " + user); // TODO createCrumbedUrl does not work as it does not notice the existing query string String formValidation = wc.getPage(wc.addCrumb(new WebRequest(new URL(r.getURL(), checkUrl), HttpMethod.POST))).getWebResponse().getContentAsString(); System.err.println("Response: " + formValidation); if (ok) { assertEquals("<div/>", formValidation); } else { assertNotEquals("<div/>", formValidation); } // GET accesses not permitted in any event: wc.assertFails(checkUrl, HttpURLConnection.HTTP_BAD_METHOD); } finally { assertEquals(sniffed, sniffer.stop()); } } private static class AuthSniffer {
/** * Tests a form submitting part of snippetizer. * * @param json * The form submission value from the configuration page to be tested. * @param responseText * Expected snippet to be generated * @param referer * needed because of {@link StaplerReferer} */ public void assertGenerateSnippet(@Nonnull String json, @Nonnull String responseText, @CheckForNull String referer) throws Exception { JenkinsRule.WebClient wc = r.createWebClient(); WebRequest wrs = new WebRequest(new URL(r.getURL(), Snippetizer.GENERATE_URL), HttpMethod.POST); if (referer != null) { wrs.setAdditionalHeader("Referer", referer); } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("json", json)); // 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()); }
/** * Tests a form submitting part of the generator. * * @param desc * The describable we'll translate to JSON. * @param responseText * Expected directive snippet to be generated */ 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()); }
@Test public void canStillProvideTheCommitNotifyAction() throws Exception { j.jenkins.setCrumbIssuer(null); String uuid = "12345678-1234-1234-1234-123456789012"; JenkinsRule.WebClient wc = j.createWebClient(); String relativeUrl = "subversion/" + uuid + "/notifyCommit/"; try { // protected against GET request wc.goTo(relativeUrl); fail(); } catch (FailingHttpStatusCodeException e) { assertEquals(405, e.getStatusCode()); } WebRequest request = new WebRequest(new URL(j.getURL() + relativeUrl), HttpMethod.POST); HtmlPage page = wc.getPage(request); j.assertGoodStatus(page); }
/** * Config the server. * @param jenkinsRule The Jenkins rule for the test instance. * @throws IOException if so (as the Gerrit boys seem to say). */ private void configure(JenkinsRule jenkinsRule) throws IOException { PluginImpl.getInstance().addServer(this); Config config = (Config)getConfig(); config.setGerritFrontEndURL(jenkinsRule.getURL().toString() + getUrlName() + "/"); config.setUseRestApi(true); config.setGerritHttpUserName("user"); config.setGerritHttpPassword("passwd"); config.setRestCodeReview(true); config.setRestVerified(true); }
public void registerHook(FilePath repo) throws Exception { assert !repo.isRemote() : "TODO not currently supported for remote repositories since the callback URL would not be accessible from the Docker container unless we do some more exotic network configuration"; FilePath hgDir = repo.child(".hg"); FilePath hook = hgDir.child("hook.py"); hook.write( "import urllib\n" + "import urllib2\n" + "\n" + "def commit(ui, repo, node, **kwargs):\n" + " data = {\n" + " 'url': '" + repo.toURI().toString() + "',\n" + " 'branch': repo[node].branch(),\n" + " 'changesetId': node,\n" + " }\n" + " req = urllib2.Request('" + j.getURL() + "mercurial/notifyCommit')\n" + " rsp = urllib2.urlopen(req, urllib.urlencode(data))\n" + " ui.warn('Notify Commit hook response: %s\\n' % rsp.read())\n" + " pass\n", null); hgDir.child("hgrc").write( "[hooks]\n" + "commit.jenkins = python:" + hook.getRemote() + ":commit", null); }
/** * Add a GerritServer with default configs from the UI. * * @param serverName the name * @throws Exception if error getting URL or getting page from URL. */ private void addNewServerWithDefaultConfigs(String serverName) throws Exception { URL url = new URL(j.getURL(), newServerURL); HtmlPage page = j.createWebClient().getPage(url); HtmlForm form = page.getFormByName(newServerFormName); form.getInputByName(inputFormName).setValueAttribute(serverName); List<HtmlRadioButtonInput> radioButtons = form.getRadioButtonsByName(radioButtonName); HtmlRadioButtonInput radioButtonDefaultConfig = null; for (HtmlRadioButtonInput button : radioButtons) { if (radioButtonDefaultConfigValue.equals(button.getValueAttribute())) { radioButtonDefaultConfig = button; radioButtonDefaultConfig.setChecked(true); } } assertTrue("Failed to choose 'GerritServer with Default Configurations'", radioButtonDefaultConfig.isChecked()); j.submit(form); }
private FreeStyleBuild sendCommitTriggerMultipleSvnLocations(FreeStyleProject p, boolean includeRevision) throws Exception { String repoUUID = "71c3de6d-444a-0410-be80-ed276b4c234a"; WebClient wc = r.createWebClient(); WebRequest wr = new WebRequest(new URL(r.getURL() + "subversion/" + repoUUID + "/notifyCommit"), HttpMethod.POST); wr.setRequestBody("A trunk/hudson/test-projects/trivial-ant/build.xml\n" + "M trunk/hudson/test-projects/trivial-maven/src/main/"); wr.setAdditionalHeader("Content-Type", "text/plain;charset=UTF-8"); if (includeRevision) { wr.setAdditionalHeader("X-Hudson-Subversion-Revision", "18075"); } WebConnection conn = wc.getWebConnection(); WebResponse resp = conn.getResponse(wr); assertTrue(r.isGoodHttpStatus(resp.getStatusCode())); Thread.sleep(1000); r.waitUntilNoActivity(); FreeStyleBuild b = p.getLastBuild(); assertNotNull(b); r.assertBuildStatus(Result.SUCCESS,b); return b; }
private FreeStyleBuild sendCommitTrigger(FreeStyleProject p, boolean includeRevision) throws Exception { String repoUUID = "71c3de6d-444a-0410-be80-ed276b4c234a"; WebClient wc = r.createWebClient(); WebRequest wr = new WebRequest(new URL(r.getURL() + "subversion/" + repoUUID + "/notifyCommit"), HttpMethod.POST); wr.setRequestBody("A trunk/hudson/test-projects/trivial-ant/build.xml"); wr.setAdditionalHeader("Content-Type", "text/plain;charset=UTF-8"); if (includeRevision) { wr.setAdditionalHeader("X-Hudson-Subversion-Revision", "13000"); } WebConnection conn = wc.getWebConnection(); WebResponse resp = conn.getResponse(wr); assertTrue(r.isGoodHttpStatus(resp.getStatusCode())); Thread.sleep(1000); r.waitUntilNoActivity(); FreeStyleBuild b = p.getLastBuild(); assertNotNull(b); r.assertBuildStatus(Result.SUCCESS,b); return b; }
/** * Add a GerritServer by copying existing configs from the UI. * * @param newServerName the name of the new server * @param fromServerName the name of the server from which the config is copied. * @throws Exception if error getting URL or getting page from URL. */ private void addNewServerByCopyingConfig(String newServerName, String fromServerName) throws Exception { URL url = new URL(j.getURL(), newServerURL); HtmlPage page = j.createWebClient().getPage(url); HtmlForm form = page.getFormByName(newServerFormName); form.getInputByName(inputFormName).setValueAttribute(newServerName); List<HtmlRadioButtonInput> radioButtons = form.getRadioButtonsByName(radioButtonName); HtmlRadioButtonInput radioButtonCopy = null; for (HtmlRadioButtonInput button : radioButtons) { if (radioButtonCopyValue.equals(button.getValueAttribute())) { radioButtonCopy = button; radioButtonCopy.setChecked(true); } } assertTrue("Failed to choose 'Copy from Existing Server Configurations'", radioButtonCopy.isChecked()); form.getInputByName(fromInputFormName).setValueAttribute(fromServerName); j.submit(form); }
PluginImpl.getInstance().addServer(server1); Config config = (Config)server1.getConfig(); config.setGerritFrontEndURL(j.getURL().toString() + "gerrit/"); config.setUseRestApi(true); config.setGerritHttpUserName("user");
/** * Tests that configuring an existing project via jenkins http rest doesn't produce duplicated triggers * and that the trigger is configured for the new project pattern. * * @throws Exception if so */ @Test @LocalData public void testReconfigureUsingRestApi() throws Exception { assertNrOfEventListeners(0); TopLevelItem testProj = j.jenkins.getItem("testProj"); String gerritProjectPattern = "someotherproject"; XmlPage xmlPage = loadConfigXmlViaHttp(testProj); Document document = xmlPage.getXmlDocument(); String xml = changeConfigXml(gerritProjectPattern, document); URL url = UrlUtils.toUrlUnsafe(j.getURL().toExternalForm() + testProj.getUrl() + "config.xml"); WebRequest request = new WebRequest(url, HttpMethod.POST); request.setRequestBody(xml); j.jenkins.setCrumbIssuer(null); Page page = j.createWebClient().getPage(request); j.assertGoodStatus(page); assertNrOfEventListeners(0); assertEventListenerWithSomeOtherProjectSet(gerritProjectPattern); }