org.jvnet.hudson.test.JenkinsRule.WebClient Java Examples

The following examples show how to use org.jvnet.hudson.test.JenkinsRule.WebClient. 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: TestResultPublishingTest.java    From junit-plugin with MIT License 6 votes vote down vote up
/**
 * Test to demonstrate bug HUDSON-5246, inter-build diffs for junit test results are wrong
 */
@Issue("JENKINS-5246")
@LocalData
@Test
public void testInterBuildDiffs() throws IOException, SAXException {
    Project proj = (Project)rule.jenkins.getItem(TEST_PROJECT_WITH_HISTORY);
    assertNotNull("We should have a project named " + TEST_PROJECT_WITH_HISTORY, proj);

    // Validate that there are test results where I expect them to be:
    WebClient wc = rule.createWebClient();
    Run theRun = proj.getBuildByNumber(4);
    assertTestResultsAsExpected(wc, theRun, "/testReport",
                    "org.jvnet.hudson.examples.small", "12 ms", "FAILURE",
                    /* total tests expected, diff */ 3, 0,
                    /* fail count expected, diff */ 1, 0,
                    /* skip count expected, diff */ 0, 0);


}
 
Example #2
Source File: JUnitResultArchiverTest.java    From junit-plugin with MIT License 6 votes vote down vote up
@Test public void specialCharsInRelativePath() throws Exception {
    Assume.assumeFalse(Functions.isWindows());
    final String ID_PREFIX = "test-../a=%3C%7C%23)/testReport/org.twia.vendor/VendorManagerTest/testCreateAdjustingFirm/";
    final String EXPECTED = "org.twia.dao.DAOException: [S2001] Hibernate encountered an error updating Claim [null]";

    MatrixProject p = j.jenkins.createProject(MatrixProject.class, "test-" + j.jenkins.getItems().size());
    p.setAxes(new AxisList(new TextAxis("a", "<|#)")));
    p.setScm(new SingleFileSCM("report.xml", getClass().getResource("junit-report-20090516.xml")));
    p.getPublishersList().add(new JUnitResultArchiver("report.xml"));

    MatrixBuild b = p.scheduleBuild2(0).get();
    j.assertBuildStatus(Result.UNSTABLE, b);

    WebClient wc = j.createWebClient();
    HtmlPage page = wc.getPage(b, "testReport");

    assertThat(page.asText(), not(containsString(EXPECTED)));

    ((HtmlAnchor) page.getElementById(ID_PREFIX + "-showlink")).click();
    wc.waitForBackgroundJavaScript(10000L);
    assertThat(page.asText(), containsString(EXPECTED));

    ((HtmlAnchor) page.getElementById(ID_PREFIX + "-hidelink")).click();
    wc.waitForBackgroundJavaScript(10000L);
    assertThat(page.asText(), not(containsString(EXPECTED)));
}
 
Example #3
Source File: JUnitResultArchiverTest.java    From junit-plugin with MIT License 6 votes vote down vote up
@LocalData("All")
@Test public void basic() throws Exception {
    FreeStyleBuild build = project.scheduleBuild2(0).get(10, TimeUnit.SECONDS);

    assertTestResults(build);

    WebClient wc = j.new WebClient();
    wc.getPage(project); // project page
    wc.getPage(build); // build page
    wc.getPage(build, "testReport");  // test report
    wc.getPage(build, "testReport/hudson.security"); // package
    wc.getPage(build, "testReport/hudson.security/HudsonPrivateSecurityRealmTest/"); // class
    wc.getPage(build, "testReport/hudson.security/HudsonPrivateSecurityRealmTest/testDataCompatibilityWith1_282/"); // method


}
 
Example #4
Source File: UseRecipesWithJenkinsRuleTest.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Test
@PresetData(DataSet.ANONYMOUS_READONLY)
public void testPresetData() throws Exception {
    WebClient wc = rule.createWebClient();
    wc.assertFails("loginError", SC_UNAUTHORIZED);
    // but not once the user logs in.
    verifyNotError(wc.login("alice"));
}
 
Example #5
Source File: TestResultPublishingTest.java    From junit-plugin with MIT License 5 votes vote down vote up
void assertTestResultsAsExpected(WebClient wc, Run run, String restOfUrl,
                                 String packageName,
                                 String expectedResult, String expectedDurationStr,
                                 int expectedTotalTests, int expectedTotalDiff,
                                 int expectedFailCount, int expectedFailDiff,
                                 int expectedSkipCount, int expectedSkipDiff) throws IOException, SAXException {

    // TODO: verify expectedResult
    // TODO: verify expectedDuration

    XmlPage xmlPage = wc.goToXml(run.getUrl() + restOfUrl + "/" + packageName + "/api/xml");
    int expectedPassCount = expectedTotalTests - expectedFailCount - expectedSkipCount;
    // Verify xml results
    rule.assertXPathValue(xmlPage, "/packageResult/failCount", Integer.toString(expectedFailCount));
    rule.assertXPathValue(xmlPage, "/packageResult/skipCount", Integer.toString(expectedSkipCount));
    rule.assertXPathValue(xmlPage, "/packageResult/passCount", Integer.toString(expectedPassCount));
    rule.assertXPathValue(xmlPage, "/packageResult/name", packageName);

    // TODO: verify html results
    HtmlPage testResultPage =   wc.getPage(run, restOfUrl);

    // Verify inter-build diffs in html table
    String xpathToFailDiff =  "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[4]";
    String xpathToSkipDiff =  "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[6]";
    String xpathToTotalDiff = "//table[@id='testresult']//tr[td//span[text()=\"" + packageName + "\"]]/td[last()]";

    Object totalDiffObj = testResultPage.getFirstByXPath(xpathToTotalDiff);
    assertPaneDiffText("total diff", expectedTotalDiff, totalDiffObj);

    Object failDiffObj = testResultPage.getFirstByXPath(xpathToFailDiff);
    assertPaneDiffText("failure diff", expectedFailDiff, failDiffObj);

    Object skipDiffObj = testResultPage.getFirstByXPath(xpathToSkipDiff);
    assertPaneDiffText("skip diff", expectedSkipDiff, skipDiffObj);

    // TODO: The link in the table for each of the three packages in the testReport table should link to a by-package page,
    // TODO: for example, http://localhost:8080/job/breakable/lastBuild/testReport/com.yahoo.breakable.misc/

}
 
Example #6
Source File: TestResultPublishingTest.java    From junit-plugin with MIT License 5 votes vote down vote up
/**
 * Make sure the open junit publisher shows junit history
 * @throws IOException
 * @throws SAXException
 */
@LocalData
@Test
public void testHistoryPageOpenJunit() throws IOException, SAXException {
    Project proj = (Project)rule.jenkins.getItem(TEST_PROJECT_WITH_HISTORY);
    assertNotNull("We should have a project named " + TEST_PROJECT_WITH_HISTORY, proj);

    // Validate that there are test results where I expect them to be:
    WebClient wc = rule.createWebClient();

    HtmlPage historyPage = wc.getPage(proj.getBuildByNumber(7),"/testReport/history/");
    rule.assertGoodStatus(historyPage);
    rule.assertXPath(historyPage, "//img[@id='graph']");
    rule.assertXPath(historyPage, "//table[@id='testresult']");
    DomElement wholeTable = historyPage.getElementById("testresult");
    assertNotNull("table with id 'testresult' exists", wholeTable);
    assertTrue("wholeTable is a table", wholeTable instanceof HtmlTable);
    HtmlTable table = (HtmlTable) wholeTable;

    // We really want to call table.getRowCount(), but
    // it returns 1, not the real answer,
    // because this table has *two* tbody elements,
    // and getRowCount() only seems to count the *first* tbody.
    // Maybe HtmlUnit can't handle the two tbody's. In any case,
    // the tableText.contains tests do a (ahem) passable job
    // of detecting whether the history results are present.

    String tableText = table.getTextContent();
    assertTrue("Table text is missing the project name",
            tableText.contains(TEST_PROJECT_WITH_HISTORY));
    assertTrue("Table text is missing the build number",
            tableText.contains("7"));
    assertTrue("Table text is missing the test duration",
            tableText.contains("4 ms"));
}
 
Example #7
Source File: TestResultPublishingTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@LocalData
@Test
public void testBasic() throws Exception {
    FreeStyleBuild build = project.scheduleBuild2(0).get(30, TimeUnit.SECONDS);

    assertTestResults(build);

    WebClient wc = rule.createWebClient();
    wc.getPage(project); // project page
    wc.getPage(build); // build page
    wc.getPage(build, "testReport");  // test report
    wc.getPage(build, "testReport/hudson.security"); // package
    wc.getPage(build, "testReport/hudson.security/HudsonPrivateSecurityRealmTest/"); // class
    wc.getPage(build, "testReport/hudson.security/HudsonPrivateSecurityRealmTest/testDataCompatibilityWith1_282/"); // method
}
 
Example #8
Source File: CaseResultTest.java    From junit-plugin with MIT License 5 votes vote down vote up
/**
 * Makes sure the summary page remains text/plain (see commit 7089a81 in JENKINS-1544) but
 * the index page must be in text/html.
 */
@Issue("JENKINS-21261")
@Test
public void testContentType() throws Exception {
    configureTestBuild("foo");
    WebClient wc = rule.createWebClient();
    wc.goTo("job/foo/1/testReport/org.twia.vendor/VendorManagerTest/testCreateAdjustingFirm/","text/html");

    wc.goTo("job/foo/1/testReport/org.twia.vendor/VendorManagerTest/testCreateAdjustingFirm/summary","text/plain");
}
 
Example #9
Source File: JUnitResultArchiverTest.java    From junit-plugin with MIT License 5 votes vote down vote up
private void testSetDescription(String url, TestObject object) throws Exception {
    object.doSubmitDescription("description");

    // test the roundtrip
    final WebClient wc = j.createWebClient();
    HtmlPage page = wc.goTo(url);
    page.getAnchorByHref("editDescription").click();
    wc.waitForBackgroundJavaScript(10000L);
    HtmlForm form = findForm(page, "submitDescription");
    j.submit(form);

    assertEquals("description", object.getDescription());
}
 
Example #10
Source File: TestResultLinksTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@LocalData
@Test
public void testFailureLinks() throws Exception {
    FreeStyleBuild build = project.scheduleBuild2(0).get(10, TimeUnit.SECONDS);
    rule.assertBuildStatus(Result.UNSTABLE, build);

    TestResult theOverallTestResult =   build.getAction(TestResultAction.class).getResult();
    CaseResult theFailedTestCase = theOverallTestResult.getFailedTests().get(0);
    String relativePath = theFailedTestCase.getRelativePathFrom(theOverallTestResult);
    System.out.println("relative path seems to be: " + relativePath); 

    WebClient wc = rule.createWebClient();

    String testReportPageUrl =  project.getLastBuild().getUrl() + "/testReport";
    HtmlPage testReportPage = wc.goTo( testReportPageUrl );

    Page packagePage = testReportPage.getAnchorByText("tacoshack.meals").click();
    rule.assertGoodStatus(packagePage); // I expect this to work; just checking that my use of the APIs is correct.

    // Now we're on that page. We should be able to find a link to the failed test in there.
    HtmlAnchor anchor = testReportPage.getAnchorByText("tacoshack.meals.NachosTest.testBeanDip");
    String href = anchor.getHrefAttribute();
    System.out.println("link is : " + href);
    Page failureFromLink = anchor.click();
    rule.assertGoodStatus(failureFromLink);

    // Now check the >>> link -- this is harder, because we can't do the javascript click handler properly
    // The summary page is just tack on /summary to the url for the test

}
 
Example #11
Source File: ConfigurationAsCodeTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("admin.yml")
public void doViewExport_should_require_authentication() throws Exception {
    WebClient client = j.createWebClient();
    WebRequest request =
        new WebRequest(client.createCrumbedUrl("configuration-as-code/viewExport"), POST);
    WebResponse response = client.loadWebResponse(request);
    assertThat(response.getStatusCode(), is(403));
    String user = "admin";
    WebClient loggedInClient = client.login(user, user);
    response = loggedInClient.loadWebResponse(request);
    assertThat(response.getStatusCode(), is(200));
}
 
Example #12
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
@SuppressFBWarnings(value = "LG", justification = "Setting the logger here helps to clean up the console log for tests")
static WebClient create(final JenkinsRule jenkins, final boolean isJavaScriptEnabled) {
    WebClient webClient = jenkins.createWebClient();
    webClient.setCssErrorHandler(new SilentCssErrorHandler());
    java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.SEVERE);
    webClient.setIncorrectnessListener((s, o) -> {
    });

    webClient.setJavaScriptEnabled(isJavaScriptEnabled);
    webClient.setJavaScriptErrorListener(new IntegrationTestJavaScriptErrorListener());
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    webClient.getCookieManager().setCookiesEnabled(isJavaScriptEnabled);
    webClient.getOptions().setCssEnabled(isJavaScriptEnabled);

    webClient.getOptions().setDownloadImages(false);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setPrintContentOnFailingStatusCode(false);

    return webClient;
}
 
Example #13
Source File: PackageDetectorsITest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
private void checkWebPageForExpectedEmptyResult(final AnalysisResult result) {
    try (WebClient webClient = createWebClient(false)) {
        WebResponse webResponse = webClient.getPage(result.getOwner(), DEFAULT_ENTRY_PATH).getWebResponse();
        HtmlPage htmlPage = HTMLParser.parseHtml(webResponse, webClient.getCurrentWindow());
        assertThat(getLinksWithGivenTargetName(htmlPage, DEFAULT_TAB_TO_INVESTIGATE)).isEmpty();
    }
    catch (IOException | SAXException e) {
        throw new AssertionError(e);
    }
}
 
Example #14
Source File: PackageDetectorsITest.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
private WebClient createWebClient(final boolean javaScriptEnabled) {
    WebClient webClient = getJenkins().createWebClient();
    webClient.setJavaScriptEnabled(javaScriptEnabled);
    return webClient;
}
 
Example #15
Source File: UseRecipesWithJenkinsRuleTest.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
private void verifyNotError(WebClient wc) throws IOException, SAXException {
    HtmlPage p = wc.goTo("loginError");
    URL url = p.getUrl();
    System.out.println(url);
    assertFalse(url.toExternalForm().contains("login"));
}
 
Example #16
Source File: UserLoginListenerTest.java    From audit-log-plugin with MIT License 4 votes vote down vote up
private static WebClient logout(final WebClient wc) throws IOException, SAXException {
    wc.goTo("logout");
    return wc;
}
 
Example #17
Source File: UserLogoutListenerTest.java    From audit-log-plugin with MIT License 4 votes vote down vote up
private static WebClient logout(final WebClient wc) throws IOException, SAXException {
    wc.goTo("logout");
    return wc;
}
 
Example #18
Source File: UserCreationListenerTest.java    From audit-log-plugin with MIT License 4 votes vote down vote up
private static WebClient logout(final WebClient wc) throws IOException, SAXException {
    wc.goTo("logout");
    return wc;
}
 
Example #19
Source File: IntegrationTestWithJenkinsPerSuite.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
@Override
protected WebClient getWebClient(final JavaScriptSupport javaScriptSupport) {
    return javaScriptSupport == JavaScriptSupport.JS_DISABLED ? noJsWebClient : jsEnabledClient;
}
 
Example #20
Source File: IntegrationTestWithJenkinsPerTest.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
@Override
protected WebClient getWebClient(final JavaScriptSupport javaScriptSupport) {
    return javaScriptSupport == JavaScriptSupport.JS_DISABLED ? noJsWebClient : jsEnabledClient;
}
 
Example #21
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 2 votes vote down vote up
/**
 * Returns a {@link WebClient} to access the HTML pages of Jenkins.
 *
 * @param javaScriptSupport
 *         determines whether JavaScript is enabled in the {@link WebClient}
 *
 * @return the web client to use
 */
protected abstract WebClient getWebClient(JavaScriptSupport javaScriptSupport);