Class JenkinsRule.WebClient

  • All Implemented Interfaces:
    Serializable, AutoCloseable
    Enclosing class:
    JenkinsRule

    public class JenkinsRule.WebClient
    extends com.gargoylesoftware.htmlunit.WebClient
    Extends WebClient and provide convenience methods for accessing Hudson.
    See Also:
    Serialized Form
    • Field Summary

      • Fields inherited from class com.gargoylesoftware.htmlunit.WebClient

        ABOUT_BLANK, ABOUT_SCHEME, TARGET_BLANK, TARGET_SELF, URL_ABOUT_BLANK
    • Constructor Summary

      Constructors 
      Constructor Description
      WebClient()  
    • Method Summary

      All Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      com.gargoylesoftware.htmlunit.WebRequest addCrumb​(com.gargoylesoftware.htmlunit.WebRequest req)
      Adds a security crumb to the request.
      void addWebResponseListener​(WebResponseListener listener)  
      void assertFails​(String url, int statusCode)
      Verify that the server rejects an attempt to load the given page.
      URL createCrumbedUrl​(String relativePath)
      Creates a URL with crumb parameters relative to {getContextPath()
      com.gargoylesoftware.htmlunit.html.HtmlPage eval​(Runnable requestHandler)
      Makes an HTTP request, process it with the given request handler, and returns the response.
      <V> V executeOnServer​(Callable<V> c)
      Executes the given closure on the server, by the servlet request handling thread, in the context of an HTTP request.
      String getContextPath()
      Returns the URL of the webapp top page.
      JenkinsRule.JSONWebResponse getJSON​(String path)
      Get JSON from a Jenkins relative endpoint.
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.Item item)  
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.Item item, String relative)  
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.Node item)  
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.Node item, String relative)  
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.Run r)
      Short for getPage(r,""), to access the top page of a build.
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.Run r, String relative)
      Accesses a page inside Run.
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.View view)  
      com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.View view, String relative)  
      com.gargoylesoftware.htmlunit.Page getPage​(String url)
      Deprecated.
      This method expects a full URL.
      com.gargoylesoftware.htmlunit.html.HtmlPage goTo​(String relative)
      Requests an HTML page within Jenkins.
      com.gargoylesoftware.htmlunit.Page goTo​(String relative, String expectedContentType)
      Requests a page within Jenkins.
      com.gargoylesoftware.htmlunit.xml.XmlPage goToXml​(String path)
      Loads a page as XML.
      org.mozilla.javascript.tools.debugger.Dim interactiveJavaScriptDebugger()
      Starts an interactive JavaScript debugger, and break at the next JavaScript execution.
      boolean isJavaScriptEnabled()
      Returns true if JavaScript is enabled and the script engine was loaded successfully.
      boolean isRedirectEnabled()
      Returns whether or not redirections will be followed automatically on receipt of a redirect status code from the server.
      boolean isThrowExceptionOnFailingStatusCode()
      Returns true if an exception will be thrown in the event of a failing response code.
      com.gargoylesoftware.htmlunit.WebResponse loadWebResponse​(com.gargoylesoftware.htmlunit.WebRequest webRequest)  
      JenkinsRule.WebClient login​(String username)
      Logs in to Hudson, by using the user name as the password.
      JenkinsRule.WebClient login​(String username, String password)
      Logs in to Jenkins.
      JenkinsRule.WebClient login​(String username, String password, boolean rememberMe)
      Logs in to Jenkins.
      JenkinsRule.JSONWebResponse postJSON​(String path, net.sf.json.JSON json)
      POST JSON content to a Jenkins relative endpoint.
      JenkinsRule.JSONWebResponse putJSON​(String path, net.sf.json.JSON json)
      Send JSON content to a Jenkins relative endpoint.
      com.gargoylesoftware.htmlunit.html.HtmlPage search​(String q)  
      void setJavaScriptEnabled​(boolean enabled)
      Enables/disables JavaScript support.
      void setRedirectEnabled​(boolean enabled)
      Sets whether or not redirections will be followed automatically on receipt of a redirect status code from the server.
      void setThrowExceptionOnFailingStatusCode​(boolean enabled)
      Changes the behavior of this webclient when a script error occurs.
      JenkinsRule.WebClient withBasicApiToken​(hudson.model.User user)
      Retrieve the ApiTokenProperty from the user, derive credentials from it and place it in Basic authorization header.
      JenkinsRule.WebClient withBasicApiToken​(String userId)
      Retrieve the ApiTokenProperty from the associated user, derive credentials from it and place it in Basic authorization header
      JenkinsRule.WebClient withBasicCredentials​(String loginAndPassword)
      Use loginAndPassword as login AND password, especially useful for JenkinsRule.DummySecurityRealm Add the "Authorization" header with Basic credentials derived from login using Base64
      JenkinsRule.WebClient withBasicCredentials​(String login, String passwordOrToken)
      Add the "Authorization" header with Basic credentials derived from login and password using Base64
      JenkinsRule.WebClient withJavaScriptEnabled​(boolean enabled)
      Enables/disables JavaScript support.
      JenkinsRule.WebClient withRedirectEnabled​(boolean enabled)
      Sets whether or not redirections will be followed automatically on receipt of a redirect status code from the server.
      JenkinsRule.WebClient withThrowExceptionOnFailingStatusCode​(boolean enabled)
      Changes the behavior of this webclient when a script error occurs.
      • Methods inherited from class com.gargoylesoftware.htmlunit.WebClient

        addCookie, addRequestHeader, addWebWindowListener, close, containsWebWindow, deregisterWebWindow, download, expandUrl, getActiveXObjectMap, getAjaxController, getAlertHandler, getAppletConfirmHandler, getAttachmentHandler, getBrowserVersion, getCache, getClipboardHandler, getConfirmHandler, getCookieManager, getCookies, getCredentialsProvider, getCssErrorHandler, getCurrentWindow, getExecutor, getFrameContentHandler, getHTMLParserListener, getIncorrectnessListener, getInternals, getJavaScriptEngine, getJavaScriptErrorListener, getJavaScriptTimeout, getMSXMLActiveXObjectFactory, getOnbeforeunloadHandler, getOptions, getPage, getPage, getPage, getPageCreator, getPromptHandler, getRefreshHandler, getScriptPreProcessor, getStatusHandler, getStorageHolder, getTopLevelWindows, getWebConnection, getWebConsole, getWebStartHandler, getWebWindowByName, getWebWindows, guessContentType, initialize, initializeEmptyWindow, isJavaScriptEngineEnabled, loadDownloadedResponses, loadHtmlCodeIntoCurrentWindow, loadWebResponseInto, loadWebResponseInto, loadXHtmlCodeIntoCurrentWindow, openDialogWindow, openTargetWindow, openWindow, openWindow, printContentIfNecessary, registerWebWindow, removeRequestHeader, removeWebWindowListener, setActiveXObjectMap, setAjaxController, setAlertHandler, setAppletConfirmHandler, setAttachmentHandler, setCache, setClipboardHandler, setConfirmHandler, setCookieManager, setCredentialsProvider, setCssErrorHandler, setCurrentWindow, setExecutor, setFrameContentHandler, setHTMLParserListener, setIncorrectnessListener, setJavaScriptEngine, setJavaScriptErrorListener, setJavaScriptTimeout, setOnbeforeunloadHandler, setPageCreator, setPromptHandler, setRefreshHandler, setScriptPreProcessor, setStatusHandler, setWebConnection, setWebStartHandler, throwFailingHttpStatusCodeExceptionIfNecessary, waitForBackgroundJavaScript, waitForBackgroundJavaScriptStartingBefore
    • Constructor Detail

      • WebClient

        public WebClient()
    • Method Detail

      • addWebResponseListener

        public void addWebResponseListener​(WebResponseListener listener)
      • loadWebResponse

        public com.gargoylesoftware.htmlunit.WebResponse loadWebResponse​(com.gargoylesoftware.htmlunit.WebRequest webRequest)
                                                                  throws IOException
        Overrides:
        loadWebResponse in class com.gargoylesoftware.htmlunit.WebClient
        Throws:
        IOException
      • isJavaScriptEnabled

        public boolean isJavaScriptEnabled()
        Returns true if JavaScript is enabled and the script engine was loaded successfully. Short-hand method to ease discovery of feature + improve readability
        Overrides:
        isJavaScriptEnabled in class com.gargoylesoftware.htmlunit.WebClient
        Returns:
        true if JavaScript is enabled
        Since:
        2.0
        See Also:
        WebClientOptions.isJavaScriptEnabled()
      • setJavaScriptEnabled

        public void setJavaScriptEnabled​(boolean enabled)
        Enables/disables JavaScript support. Short-hand method to ease discovery of feature + improve readability
        Parameters:
        enabled - true to enable JavaScript support
        Since:
        2.0
        See Also:
        WebClientOptions.setJavaScriptEnabled(boolean)
      • withJavaScriptEnabled

        public JenkinsRule.WebClient withJavaScriptEnabled​(boolean enabled)
        Enables/disables JavaScript support. Fluent method to ease discovery of feature + improve readability
        Parameters:
        enabled - true to enable JavaScript support
        Returns:
        self for fluent method chaining
        Since:
        2.42
        See Also:
        WebClientOptions.setJavaScriptEnabled(boolean)
      • isThrowExceptionOnFailingStatusCode

        public boolean isThrowExceptionOnFailingStatusCode()
        Returns true if an exception will be thrown in the event of a failing response code. Short-hand method to ease discovery of feature + improve readability
        Returns:
        true if an exception will be thrown in the event of a failing response code
        Since:
        2.42
        See Also:
        WebClientOptions.isThrowExceptionOnFailingStatusCode()
      • setThrowExceptionOnFailingStatusCode

        public void setThrowExceptionOnFailingStatusCode​(boolean enabled)
        Changes the behavior of this webclient when a script error occurs. Short-hand method to ease discovery of feature + improve readability
        Parameters:
        enabled - true to enable this feature
        Since:
        2.42
        See Also:
        WebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)
      • withThrowExceptionOnFailingStatusCode

        public JenkinsRule.WebClient withThrowExceptionOnFailingStatusCode​(boolean enabled)
        Changes the behavior of this webclient when a script error occurs. Fluent method to ease discovery of feature + improve readability
        Parameters:
        enabled - true to enable this feature
        Returns:
        self for fluent method chaining
        Since:
        2.42
        See Also:
        WebClientOptions.setThrowExceptionOnFailingStatusCode(boolean)
      • isRedirectEnabled

        public boolean isRedirectEnabled()
        Returns whether or not redirections will be followed automatically on receipt of a redirect status code from the server. Short-hand method to ease discovery of feature + improve readability
        Returns:
        true if automatic redirection is enabled
        Since:
        2.42
        See Also:
        WebClientOptions.isRedirectEnabled()
      • setRedirectEnabled

        public void setRedirectEnabled​(boolean enabled)
        Sets whether or not redirections will be followed automatically on receipt of a redirect status code from the server. Short-hand method to ease discovery of feature + improve readability
        Parameters:
        enabled - true to enable automatic redirection
        Since:
        2.42
        See Also:
        WebClientOptions.setRedirectEnabled(boolean)
      • withRedirectEnabled

        public JenkinsRule.WebClient withRedirectEnabled​(boolean enabled)
        Sets whether or not redirections will be followed automatically on receipt of a redirect status code from the server. Fluent method to ease discovery of feature + improve readability
        Parameters:
        enabled - true to enable automatic redirection
        Returns:
        self for fluent method chaining
        Since:
        2.42
        See Also:
        WebClientOptions.setRedirectEnabled(boolean)
      • executeOnServer

        public <V> V executeOnServer​(Callable<V> c)
                              throws Exception
        Executes the given closure on the server, by the servlet request handling thread, in the context of an HTTP request.

        In JenkinsRule, a thread that's executing the test code is different from the thread that carries out HTTP requests made through JenkinsRule.WebClient. But sometimes you want to make assertions and other calls with side-effect from within the request handling thread.

        This method allows you to do just that. It is useful for testing some methods that require StaplerRequest and StaplerResponse, or getting the credential of the current user (via Jenkins.getAuthentication(), and so on.

        Parameters:
        c - The closure to be executed on the server.
        Returns:
        The return value from the closure.
        Throws:
        Exception - If a closure throws any exception, that exception will be carried forward.
      • getPage

        public com.gargoylesoftware.htmlunit.html.HtmlPage getPage​(hudson.model.Run r,
                                                                   String relative)
                                                            throws IOException,
                                                                   SAXException
        Accesses a page inside Run.
        Parameters:
        relative - Relative URL within the build URL, like "changes". Doesn't start with '/'. Can be empty.
        Throws:
        IOException
        SAXException
      • getPage

        public com.gargoylesoftware.htmlunit.Page getPage​(String url)
                                                   throws IOException,
                                                          com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException
        Deprecated.
        This method expects a full URL. This method is marked as deprecated to warn you that you probably should be using goTo(String) method, which accepts a relative path within the Hudson being tested. (IOW, if you really need to hit a website on the internet, there's nothing wrong with using this method.)
        Overrides:
        getPage in class com.gargoylesoftware.htmlunit.WebClient
        Throws:
        IOException
        com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException
      • goTo

        public com.gargoylesoftware.htmlunit.html.HtmlPage goTo​(String relative)
                                                         throws IOException,
                                                                SAXException
        Requests an HTML page within Jenkins.
        Parameters:
        relative - Relative path within Jenkins. Starts without '/'. For example, "job/test/" to go to a job top page.
        Throws:
        IOException
        SAXException
      • goTo

        public com.gargoylesoftware.htmlunit.Page goTo​(String relative,
                                                       @CheckForNull
                                                       String expectedContentType)
                                                throws IOException,
                                                       SAXException
        Requests a page within Jenkins.
        Parameters:
        relative - Relative path within Jenkins. Starts without '/'. For example, "job/test/" to go to a job top page.
        expectedContentType - the expected WebResponse.getContentType(), or null to do no such check
        Throws:
        IOException
        SAXException
      • goToXml

        public com.gargoylesoftware.htmlunit.xml.XmlPage goToXml​(String path)
                                                          throws IOException,
                                                                 SAXException
        Loads a page as XML. Useful for testing Jenkins's XML API, in concert with assertXPath(DomNode page, String xpath)
        Parameters:
        path - the path part of the url to visit
        Returns:
        the XmlPage found at that url
        Throws:
        IOException
        SAXException
      • assertFails

        public void assertFails​(String url,
                                int statusCode)
                         throws Exception
        Verify that the server rejects an attempt to load the given page.
        Parameters:
        url - a URL path (relative to Jenkins root)
        statusCode - the expected failure code (such as HttpURLConnection.HTTP_FORBIDDEN)
        Throws:
        Exception
        Since:
        1.504
      • addCrumb

        public com.gargoylesoftware.htmlunit.WebRequest addCrumb​(com.gargoylesoftware.htmlunit.WebRequest req)
        Adds a security crumb to the request. Use createCrumbedUrl(java.lang.String) instead if you intend to call WebRequest.setRequestBody(java.lang.String), typical of a POST request.
      • withBasicCredentials

        @NonNull
        public JenkinsRule.WebClient withBasicCredentials​(@NonNull
                                                          String login,
                                                          @NonNull
                                                          String passwordOrToken)
        Add the "Authorization" header with Basic credentials derived from login and password using Base64
        Since:
        2.32
      • withBasicCredentials

        @NonNull
        public JenkinsRule.WebClient withBasicCredentials​(@NonNull
                                                          String loginAndPassword)
        Use loginAndPassword as login AND password, especially useful for JenkinsRule.DummySecurityRealm Add the "Authorization" header with Basic credentials derived from login using Base64
        Since:
        2.32
      • withBasicApiToken

        @NonNull
        public JenkinsRule.WebClient withBasicApiToken​(@NonNull
                                                       hudson.model.User user)
        Retrieve the ApiTokenProperty from the user, derive credentials from it and place it in Basic authorization header. If there is not available token it will generate one using the new system.
        Since:
        2.32 (since TODO it creates a new token everytime it's called)
        See Also:
        withBasicCredentials(String, String)
      • withBasicApiToken

        @NonNull
        public JenkinsRule.WebClient withBasicApiToken​(@NonNull
                                                       String userId)
        Retrieve the ApiTokenProperty from the associated user, derive credentials from it and place it in Basic authorization header
        Since:
        2.32
        See Also:
        withBasicApiToken(User)
      • interactiveJavaScriptDebugger

        public org.mozilla.javascript.tools.debugger.Dim interactiveJavaScriptDebugger()
        Starts an interactive JavaScript debugger, and break at the next JavaScript execution.

        This is useful during debugging a test so that you can step execute and inspect state of JavaScript. This will launch a Swing GUI, and the method returns immediately.

        Note that installing a debugger appears to make an execution of JavaScript substantially slower.

        TODO: because each script block evaluation in HtmlUnit is done in a separate Rhino context, if you step over from one script block, the debugger fails to kick in on the beginning of the next script block. This makes it difficult to set a break point on arbitrary script block in the HTML page. We need to fix this by tweaking Dim.StackFrame.onLineChange(Context, int).

      • getJSON

        public JenkinsRule.JSONWebResponse getJSON​(@NonNull
                                                   String path)
                                            throws IOException
        Get JSON from a Jenkins relative endpoint. You can preconfigure the web client for example to set a token for authentication, or accept error HTTP status before calling this method.
        Parameters:
        path - relative path, should not start with '/'
        Returns:
        The JSON response from server.
        Throws:
        IOException
      • putJSON

        public JenkinsRule.JSONWebResponse putJSON​(@NonNull
                                                   String path,
                                                   @NonNull
                                                   net.sf.json.JSON json)
                                            throws IOException
        Send JSON content to a Jenkins relative endpoint. You can preconfigure the web client for example to set a token for authentication, or accept error HTTP status before calling this method.
        Parameters:
        path - relative path, should not start with '/'
        json - the json payload to send
        Returns:
        The JSON response from server.
        Throws:
        IOException
      • postJSON

        public JenkinsRule.JSONWebResponse postJSON​(@NonNull
                                                    String path,
                                                    @NonNull
                                                    net.sf.json.JSON json)
                                             throws IOException
        POST JSON content to a Jenkins relative endpoint. You can preconfigure the web client for example to set a token for authentication or pass a crumb before calling this method.
        Parameters:
        path - relative path, should not start with '/'
        json - the json payload to send
        Returns:
        The JSON response from server.
        Throws:
        IOException