Interface RequestFixture


  • public interface RequestFixture
    A contrived request environment, suitable for unit testing Handler implementations.

    A request fixture emulates a request, and the effective state of the request handling in the handler pipeline.

    A request fixture can be obtained by the requestFixture() method. However it is often more convenient to use the alternative handle(Handler, Action) method.

    See Also:
    handle(Handler)
    • Method Summary

      All Methods Static Methods Instance Methods Abstract Methods 
      Modifier and Type Method Description
      RequestFixture body​(byte[] bytes, java.lang.String contentType)
      Sets the request body to be the given bytes, and adds a Content-Type request header of the given value.
      RequestFixture body​(java.lang.String text, java.lang.String contentType)
      Sets the request body to be the given string in utf8 bytes, and adds a Content-Type request header of the given value.
      MultipartFileSpec file()
      A specification of a file to upload (see RFC2388)
      RequestFixture file​(java.lang.String field, java.lang.String filename, java.lang.String data)
      Uploads a file via a multipart form (see RFC2388)
      MultipartFormSpec form()
      A specification of a multipart form (see RFC2388)
      RequestFixture form​(java.util.Map<java.lang.String,​java.lang.String> fields)
      Sets the fields on a multipart form (see RFC2388)
      ratpack.registry.RegistrySpec getRegistry()
      A specification of the context registry.
      static HandlingResult handle​(ratpack.func.Action<? super ratpack.handling.Chain> chainAction, ratpack.func.Action<? super RequestFixture> requestFixtureAction)
      Unit test a Handler chain.
      HandlingResult handle​(ratpack.handling.Handler handler)
      Invokes the given handler with a newly created Context based on the state of this fixture.
      static HandlingResult handle​(ratpack.handling.Handler handler, ratpack.func.Action<? super RequestFixture> action)
      Unit test a single Handler.
      HandlingResult handleChain​(ratpack.func.Action<? super ratpack.handling.Chain> chainAction)
      Similar to handle(Handler), but for testing a handler chain.
      RequestFixture header​(java.lang.CharSequence name, java.lang.String value)
      Set a request header value.
      RequestFixture localAddress​(com.google.common.net.HostAndPort local)
      Set the local address to which this request is made.
      RequestFixture method​(java.lang.String method)
      Set the request method (case insensitive).
      RequestFixture pathBinding​(java.lang.String boundTo, java.lang.String pastBinding, java.util.Map<java.lang.String,​java.lang.String> pathTokens)
      Adds a path binding, with the given path tokens and parts.
      RequestFixture pathBinding​(java.lang.String boundTo, java.lang.String pastBinding, java.util.Map<java.lang.String,​java.lang.String> pathTokens, java.lang.String description)
      Adds a path binding, with the given path tokens and parts.
      RequestFixture pathBinding​(java.util.Map<java.lang.String,​java.lang.String> pathTokens)
      Adds a path binding, with the given path tokens.
      RequestFixture protocol​(java.lang.String protocol)
      Set the HTTP protocol for the request.
      RequestFixture registry​(ratpack.func.Action<? super ratpack.registry.RegistrySpec> action)
      Configures the context registry.
      RequestFixture remoteAddress​(com.google.common.net.HostAndPort remote)
      Set the remote address from which the request is made.
      static RequestFixture requestFixture()
      Create a request fixture, for unit testing of handlers.
      RequestFixture responseHeader​(java.lang.CharSequence name, java.lang.String value)
      Set a response header value.
      RequestFixture serverConfig​(ratpack.func.Action<? super ratpack.server.ServerConfigBuilder> action)
      Configures the server config to have no base dir and given configuration.
      RequestFixture timeout​(int timeoutSeconds)
      Sets the maximum time to allow the handler under test to produce a result.
      RequestFixture uri​(java.lang.String uri)
      The URI of the request.
    • Method Detail

      • handle

        static HandlingResult handle​(ratpack.handling.Handler handler,
                                     ratpack.func.Action<? super RequestFixture> action)
                              throws java.lang.Exception
        Unit test a single Handler.
        
         import ratpack.handling.Context;
         import ratpack.handling.Handler;
         import ratpack.test.handling.RequestFixture;
         import ratpack.test.handling.HandlingResult;
        
         import static org.junit.Assert.assertEquals;
        
         public class Example {
        
           public static class MyHandler implements Handler {
             public void handle(Context ctx) throws Exception {
               String outputHeaderValue = ctx.getRequest().getHeaders().get("input-value") + ":bar";
               ctx.getResponse().getHeaders().set("output-value", outputHeaderValue);
               ctx.render("received: " + ctx.getRequest().getPath());
             }
           }
        
           public static void main(String[] args) throws Exception {
             HandlingResult result = RequestFixture.handle(new MyHandler(), fixture ->
                 fixture.header("input-value", "foo").uri("some/path")
             );
        
             assertEquals("received: some/path", result.rendered(String.class));
             assertEquals("foo:bar", result.getHeaders().get("output-value"));
           }
         }
         
        Parameters:
        handler - The handler to invoke
        action - The configuration of the context for the handler
        Returns:
        A result object indicating what happened
        Throws:
        HandlerTimeoutException - if the handler takes more than timeout(int) seconds to send a response or call next() on the context
        java.lang.Exception - any thrown by action
        See Also:
        handle(Action, Action)
      • handle

        static HandlingResult handle​(ratpack.func.Action<? super ratpack.handling.Chain> chainAction,
                                     ratpack.func.Action<? super RequestFixture> requestFixtureAction)
                              throws java.lang.Exception
        Unit test a Handler chain.
        
         import ratpack.func.Action;
         import ratpack.handling.Chain;
         import ratpack.test.handling.RequestFixture;
         import ratpack.test.handling.HandlingResult;
        
         import static org.junit.Assert.assertEquals;
        
         public class Example {
        
           public static class MyHandlers implements Action<Chain> {
             public void execute(Chain chain) throws Exception {
               chain.all(ctx -> {
                 String outputHeaderValue = ctx.getRequest().getHeaders().get("input-value") + ":bar";
                 ctx.getResponse().getHeaders().set("output-value", outputHeaderValue);
                 ctx.next();
               });
               chain.all(ctx -> ctx.render("received: " + ctx.getRequest().getPath()) );
             }
           }
        
           public static void main(String[] args) throws Exception {
             HandlingResult result = RequestFixture.handle(new MyHandlers(), fixture ->
                 fixture.header("input-value", "foo").uri("some/path")
             );
        
             assertEquals("received: some/path", result.rendered(String.class));
             assertEquals("foo:bar", result.getHeaders().get("output-value"));
           }
         }
         
        Parameters:
        chainAction - the definition of a handler chain to test
        requestFixtureAction - the configuration of the request fixture
        Returns:
        a result object indicating what happened
        Throws:
        HandlerTimeoutException - if the handler takes more than timeout(int) seconds to send a response or call next() on the context
        java.lang.Exception - any thrown by chainAction or requestFixtureAction
        See Also:
        handle(Handler, Action)
      • body

        RequestFixture body​(byte[] bytes,
                            java.lang.String contentType)
        Sets the request body to be the given bytes, and adds a Content-Type request header of the given value.

        By default the body is empty.

        Parameters:
        bytes - the request body in bytes
        contentType - the content type of the request body
        Returns:
        this
      • body

        RequestFixture body​(java.lang.String text,
                            java.lang.String contentType)
        Sets the request body to be the given string in utf8 bytes, and adds a Content-Type request header of the given value.

        By default the body is empty.

        Parameters:
        text - the request body as a string
        contentType - the content type of the request body
        Returns:
        this
      • file

        MultipartFileSpec file()
        A specification of a file to upload (see RFC2388)

        Can be used to construct a multipart form with files

        Returns:
        a specification of a multipart file
      • file

        RequestFixture file​(java.lang.String field,
                            java.lang.String filename,
                            java.lang.String data)
        Uploads a file via a multipart form (see RFC2388)
        Parameters:
        field - form field name
        filename - filename of uploaded file
        data - content of file
        Returns:
        this
      • form

        MultipartFormSpec form()
        A specification of a multipart form (see RFC2388)

        Can be used to construct a multipart form with name value pairs and files

        Note that more than one value and more than one file can be associated with a single field

        Returns:
        a specification of a multipart form
      • form

        RequestFixture form​(java.util.Map<java.lang.String,​java.lang.String> fields)
        Sets the fields on a multipart form (see RFC2388)
        Parameters:
        fields - map of field name to field value
        Returns:
        this
      • getRegistry

        ratpack.registry.RegistrySpec getRegistry()
        A specification of the context registry.

        Can be used to make objects (e.g. support services) available via context registry lookup.

        By default, only a ServerErrorHandler and ClientErrorHandler are in the context registry.

        Returns:
        a specification of the context registry
      • handle

        HandlingResult handle​(ratpack.handling.Handler handler)
                       throws HandlerTimeoutException
        Invokes the given handler with a newly created Context based on the state of this fixture.

        The return value can be used to examine the effective result of the handler.

        A result may be one of the following:

        • The sending of a response via one of the Response.send() methods
        • Rendering to the response via the Context.render(Object)
        • Raising of a client error via Context.clientError(int)
        • Raising of a server error via Context.error(Throwable)
        • Raising of a server error by the throwing of an exception
        • Delegating to the next handler by invoking one of the Context.next() methods
        Note that any handlers inserted by the handler under test will be invoked. If the last inserted handler delegates to the next handler, the handling will terminate with a result indicating that the effective result was delegating to the next handler.

        This method blocks until a result is achieved, even if the handler performs an asynchronous operation (such as performing blocking IO). As such, a time limit on the execution is imposed which by default is 5 seconds. The time limit can be changed via the timeout(int) method. If the time limit is reached, a HandlerTimeoutException is thrown.

        Parameters:
        handler - the handler to test
        Returns:
        the effective result of the handling
        Throws:
        HandlerTimeoutException - if the handler does not produce a result in the time limit defined by this fixture
      • handleChain

        HandlingResult handleChain​(ratpack.func.Action<? super ratpack.handling.Chain> chainAction)
                            throws java.lang.Exception
        Similar to handle(Handler), but for testing a handler chain.
        Parameters:
        chainAction - the handler chain to test
        Returns:
        the effective result of the handling
        Throws:
        HandlerTimeoutException - if the handler does not produce a result in the time limit defined by this fixture
        java.lang.Exception - any thrown by chainAction
      • header

        RequestFixture header​(java.lang.CharSequence name,
                              java.lang.String value)
        Set a request header value.

        By default there are no request headers.

        Parameters:
        name - the header name
        value - the header value
        Returns:
        this
      • serverConfig

        RequestFixture serverConfig​(ratpack.func.Action<? super ratpack.server.ServerConfigBuilder> action)
                             throws java.lang.Exception
        Configures the server config to have no base dir and given configuration.

        By default the server config is equivalent to ServerConfig.builder().build().

        Parameters:
        action - configuration of the server config
        Returns:
        this
        Throws:
        java.lang.Exception - any thrown by action
      • method

        RequestFixture method​(java.lang.String method)
        Set the request method (case insensitive).

        The default method is "GET".

        Parameters:
        method - the request method
        Returns:
        this
      • pathBinding

        RequestFixture pathBinding​(java.util.Map<java.lang.String,​java.lang.String> pathTokens)
        Adds a path binding, with the given path tokens.

        By default, there are no path tokens and no path binding.

        Parameters:
        pathTokens - the path tokens to make available to the handler(s) under test
        Returns:
        this
      • pathBinding

        RequestFixture pathBinding​(java.lang.String boundTo,
                                   java.lang.String pastBinding,
                                   java.util.Map<java.lang.String,​java.lang.String> pathTokens)
        Adds a path binding, with the given path tokens and parts.

        By default, there are no path tokens and no path binding.

        Parameters:
        boundTo - the part of the request path that the binding bound to
        pastBinding - the part of the request path past boundTo
        pathTokens - the path tokens and binding to make available to the handler(s) under test
        Returns:
        this
      • pathBinding

        RequestFixture pathBinding​(java.lang.String boundTo,
                                   java.lang.String pastBinding,
                                   java.util.Map<java.lang.String,​java.lang.String> pathTokens,
                                   java.lang.String description)
        Adds a path binding, with the given path tokens and parts.

        By default, there are no path tokens and no path binding.

        Parameters:
        boundTo - the part of the request path that the binding bound to
        pastBinding - the part of the request path past boundTo
        pathTokens - the path tokens and binding to make available to the handler(s) under test
        description - the description of the request path binding
        Returns:
        this
      • registry

        RequestFixture registry​(ratpack.func.Action<? super ratpack.registry.RegistrySpec> action)
                         throws java.lang.Exception
        Configures the context registry.
        Parameters:
        action - a registry specification action
        Returns:
        this
        Throws:
        java.lang.Exception - any thrown by action
      • responseHeader

        RequestFixture responseHeader​(java.lang.CharSequence name,
                                      java.lang.String value)
        Set a response header value.

        Can be used to simulate the setting of a response header by an upstream handler.

        By default there are no request headers.

        Parameters:
        name - the header name
        value - the header value
        Returns:
        this
      • timeout

        RequestFixture timeout​(int timeoutSeconds)
        Sets the maximum time to allow the handler under test to produce a result.

        As handlers may execute asynchronously, a maximum time limit must be used to guard against never ending handlers.

        Parameters:
        timeoutSeconds - the maximum number of seconds to allow the handler(s) under test to produce a result
        Returns:
        this
      • uri

        RequestFixture uri​(java.lang.String uri)
        The URI of the request.

        No encoding is performed on the given value. It is expected to be a well formed URI path string (potentially including query and fragment strings)

        Parameters:
        uri - the URI of the request
        Returns:
        this
      • remoteAddress

        RequestFixture remoteAddress​(com.google.common.net.HostAndPort remote)
        Set the remote address from which the request is made.

        Effectively the return value of Request.getRemoteAddress().

        Parameters:
        remote - the remote host and port address
        Returns:
        this
      • localAddress

        RequestFixture localAddress​(com.google.common.net.HostAndPort local)
        Set the local address to which this request is made.

        Effectively the return value of Request.getLocalAddress().

        Parameters:
        local - the local host and port address
        Returns:
        this
      • protocol

        RequestFixture protocol​(java.lang.String protocol)
        Set the HTTP protocol for the request.
        Parameters:
        protocol - The string representation of the HTTP protocol.
        Returns:
        this