All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jayway.restassured.RestAssured Maven / Gradle / Ivy

There is a newer version: 2.9.0
Show newest version
/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jayway.restassured;

import com.jayway.restassured.authentication.*;
import com.jayway.restassured.config.RestAssuredConfig;
import com.jayway.restassured.filter.Filter;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.internal.*;
import com.jayway.restassured.mapper.ObjectMapper;
import com.jayway.restassured.parsing.Parser;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.Argument;
import com.jayway.restassured.specification.RequestSender;
import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static com.jayway.restassured.config.ObjectMapperConfig.objectMapperConfig;

/**
 * REST Assured is a Java DSL for simplifying testing of REST based services built on top of
 * HTTP Builder.
 * It supports POST, GET, PUT, DELETE, HEAD, PATCH  and OPTIONS
 * requests and to verify the response of these requests. Usage examples:
 * 
    *
  1. * Assume that the GET request (to http://localhost:8080/lotto) returns JSON as: *
     * {
     * "lotto":{
     *   "lottoId":5,
     *   "winning-numbers":[2,45,34,23,7,5,3],
     *   "winners":[{
     *     "winnerId":23,
     *     "numbers":[2,45,34,23,3,5]
     *   },{
     *     "winnerId":54,
     *     "numbers":[52,3,12,11,18,22]
     *   }]
     *  }
     * }
     * 
    *

    * REST assured can then help you to easily make the GET request and verify the response. E.g. if you want to verify * that lottoId is equal to 5 you can do like this: *

    *

     * expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");
     * 
    *

    * or perhaps you want to check that the winnerId's are 23 and 54: *

     *  expect().body("lotto.winners.winnerId", hasItems(23, 54)).when().get("/lotto");
     * 
    *
  2. *
  3. * XML can be verified in a similar way. Imagine that a POST request to http://localhost:8080/greetXML returns: *
     * <greeting>
     *     <firstName>{params("firstName")}</firstName>
     *     <lastName>{params("lastName")}</lastName>
     *   </greeting>
     * 
    *

    * i.e. it sends back a greeting based on the firstName and lastName parameter sent in the request. * You can easily perform and verify e.g. the firstName with REST assured: *

     * with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");
     * 
    *

    * If you want to verify both firstName and lastName you may do like this: *

     * with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).and().body("greeting.lastName", equalTo("Doe")).when().post("/greetXML");
     * 
    *

    * or a little shorter: *

     * with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John"), "greeting.lastName", equalTo("Doe")).when().post("/greetXML");
     * 
    *
  4. *
  5. * You can also verify XML responses using x-path. For example: *
     * expect().body(hasXPath("/greeting/firstName", containsString("Jo"))).given().parameters("firstName", "John", "lastName", "Doe").when().post("/greetXML");
     * 
    * or *
     * expect().body(hasXPath("/greeting/firstName[text()='John']")).with().parameters("firstName", "John", "lastName", "Doe").post("/greetXML");
     * 
    *
  6. *
  7. * XML response bodies can also be verified against an XML Schema (XSD) or DTD.
    XSD example: *
     * expect().body(matchesXsd(xsd)).when().get("/carRecords");
     * 
    * DTD example: *
     * expect().body(matchesDtd(dtd)).when().get("/videos");
     * 
    * matchesXsd and matchesDtd are Hamcrest matchers which you can import from {@link com.jayway.restassured.matcher.RestAssuredMatchers}. *
  8. *
  9. * Besides specifying request parameters you can also specify headers, cookies, body and content type.
    *
      *
    • * Cookie: *
       * given().cookie("username", "John").then().expect().body(equalTo("username")).when().get("/cookie");
       * 
      *
    • *
    • * Headers: *
       * given().header("MyHeader", "Something").and(). ..
       * given().headers("MyHeader", "Something", "MyOtherHeader", "SomethingElse").and(). ..
       * 
      *
    • *
    • * Content Type: *
       * given().contentType(ContentType.TEXT). ..
       * 
      *
    • *
    • * Body: *
       * given().request().body("some body"). .. // Works for POST and PUT requests
       * given().request().body(new byte[]{42}). .. // Works for POST
       * 
      *
    • *
    *
  10. *
  11. * You can also verify status code, status line, cookies, headers, content type and body. *
      *
    • * Cookie: *
       * expect().cookie("cookieName", "cookieValue"). ..
       * expect().cookies("cookieName1", "cookieValue1", "cookieName2", "cookieValue2"). ..
       * expect().cookies("cookieName1", "cookieValue1", "cookieName2", containsString("Value2")). ..
       * 
      *
    • *
    • * Status: *
       * expect().statusCode(200). ..
       * expect().statusLine("something"). ..
       * expect().statusLine(containsString("some")). ..
       * 
      *
    • *
    • * Headers: *
       * expect().header("headerName", "headerValue"). ..
       * expect().headers("headerName1", "headerValue1", "headerName2", "headerValue2"). ..
       * expect().headers("headerName1", "headerValue1", "headerName2", containsString("Value2")). ..
       * 
      *
    • *
    • * Content-Type: *
       * expect().contentType(ContentType.JSON). ..
       * 
      *
    • *
    • * REST Assured also supports mapping a request body and response body to and from a Java object using Jackson, Gson or JAXB. Usage example: *
       * Greeting greeting = get("/greeting").as(Greeting.class);
       * 
      *
       * Greeting greeting = new Greeting();
       * greeting.setFirstName("John");
       * greeting.setLastName("Doe");
       *
       * given().body(greeting).when().post("/greeting");
       * 
      * See the javadoc for the body method for more details. *
    • *
    • * Full body/content matching: *
       * expect().body(equalsTo("something")). ..
       * expect().content(equalsTo("something")). .. // Same as above
       * 
      *
    • *
    *
  12. *
  13. * REST assured also supports some authentication schemes, for example basic authentication: *
     * given().auth().basic("username", "password").expect().statusCode(200).when().get("/secured/hello");
     * 
    * Other supported schemes are OAuth and certificate authentication. *
  14. *
  15. * By default REST assured assumes host localhost and port 8080 when doing a request. If you want a different port you can do: *
     * given().port(80). ..
     * 
    * or simply: *
     * .. when().get("http://myhost.org:80/doSomething");
     * 
    *
  16. *
  17. * Parameters can also be set directly on the url: *
     * ..when().get("/name?firstName=John&lastName=Doe");
     * 
    *
  18. *
  19. * You can use the {@link com.jayway.restassured.path.xml.XmlPath} or {@link com.jayway.restassured.path.json.JsonPath} to * easily parse XML or JSON data from a response. *
      *
    1. XML example: *
       *            String xml = post("/greetXML?firstName=John&lastName=Doe").andReturn().asString();
       *            // Now use XmlPath to get the first and last name
       *            String firstName = with(xml).get("greeting.firstName");
       *            String lastName = with(xml).get("greeting.firstName");
       *
       *            // or a bit more efficiently:
       *            XmlPath xmlPath = new XmlPath(xml).setRoot("greeting");
       *            String firstName = xmlPath.get("firstName");
       *            String lastName = xmlPath.get("lastName");
       *        
      *
    2. *
    3. JSON example: *
       *            String json = get("/lotto").asString();
       *            // Now use JsonPath to get data out of the JSON body
       *            int lottoId = with(json).getInt("lotto.lottoId);
       *            List winnerIds = with(json).get("lotto.winners.winnerId");
       *
       *            // or a bit more efficiently:
       *            JsonPath jsonPath = new JsonPath(json).setRoot("lotto");
       *            int lottoId = jsonPath.getInt("lottoId");
       *            List winnderIds = jsonPath.get("winnders.winnderId");
       *        
      *
    4. *
    *
  20. *
  21. * REST Assured providers predefined parsers for e.g. HTML, XML and JSON. But you can parse other kinds of content by registering a predefined parser for unsupported content-types by using: *
     * RestAssured.registerParser(<content-type>, <parser>);
     * 
    * E.g. to register that content-type 'application/vnd.uoml+xml' should be parsed using the XML parser do: *
     * RestAssured.registerParser("application/vnd.uoml+xml", Parser.XML);
     * 
    * You can also unregister a parser using: *
     * RestAssured.unregisterParser("application/vnd.uoml+xml");
     * 
    * If can also specify a default parser for all content-types that do not match a pre-defined or registered parser. This is also useful if the response doesn't contain a content-type at all: *
     * RestAssured.defaultParser = Parser.JSON;
     * 
    *
  22. *
  23. If you need to re-use a specification in multiple tests or multiple requests you can use the {@link com.jayway.restassured.builder.ResponseSpecBuilder} * and {@link com.jayway.restassured.builder.RequestSpecBuilder} like this: *
     * RequestSpecification requestSpec = new RequestSpecBuilder().addParameter("parameter1", "value1").build();
     * ResponseSpecification responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
     *
     * given().
     *         spec(requestSpec).
     * expect().
     *         spec(responseSpec).
     *         body("x.y.z", equalTo("something")).
     * when().
     *        get("/something");
     * 
    *
  24. *
  25. You can also create filters and add to the request specification. A filter allows you to inspect and alter a request before it's actually committed and also inspect and alter the * response before it's returned to the expectations. You can regard it as an "around advice" in AOP terms. Filters can be used to implement custom authentication schemes, session management, logging etc. E.g. *
     * given().filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(302)). ..
     * 
    * will log/print the response body to after each request. *
  26. *
  27. * You can also change the default base URI, base path, port, authentication scheme, root path and filters for all subsequent requests: *
     * RestAssured.baseURI = "http://myhost.org";
     * RestAssured.port = 80;
     * RestAssured.basePath = "/resource";
     * RestAssured.authentication = basic("username", "password");
     * RestAssured.rootPath = "store.book";
     * 
    * This means that a request like e.g. get("/hello") goes to: http://myhost.org:8080/resource/hello * which basic authentication credentials "username" and "password". See {@link #rootPath} for more info about setting the root paths, {@link #filters(java.util.List)} for setting * default filters and {@link #keystore(String, String)} for setting the default keystore when using SSL.
    * You can reset to the standard baseURI (localhost), basePath (empty), standard port (8080), default authentication scheme (none), default parser (none) and default root path (empty string) using: *
     * RestAssured.reset();
     * 
    *
  28. *
*

* In order to use REST assured effectively it's recommended to statically import * methods from the following classes: *

    *
  • com.jayway.restassured.RestAssured.*
  • *
  • com.jayway.restassured.matcher.RestAssuredMatchers.*
  • *
  • org.hamcrest.Matchers.*
  • *
*

*/ public class RestAssured { private static ResponseParserRegistrar RESPONSE_PARSER_REGISTRAR = new ResponseParserRegistrar(); public static final String DEFAULT_URI = "http://localhost"; public static final String DEFAULT_BODY_ROOT_PATH = ""; public static final int DEFAULT_PORT = 8080; public static final String DEFAULT_PATH = ""; public static final AuthenticationScheme DEFAULT_AUTH = new NoAuthScheme(); public static final boolean DEFAULT_URL_ENCODING_ENABLED = true; public static final String DEFAULT_SESSION_ID_VALUE = null; /** * The base URI that's used by REST assured when making requests if a non-fully qualified URI is used in the request. * Default value is {@value #DEFAULT_URI}. */ public static String baseURI = DEFAULT_URI; /** * The port that's used by REST assured when it's left out of the specified URI when making a request. * Default value is {@value #DEFAULT_PORT}. */ public static int port = DEFAULT_PORT; /** * A base path that's added to the {@link #baseURI} by REST assured when making requests. E.g. let's say that * the {@link #baseURI} is http://localhost and basePath is /resource * then *

*

     * ..when().get("/something");
     * 
*

* will make a request to http://localhost/resource. * Default basePath value is empty. */ public static String basePath = DEFAULT_PATH; /** * Specifies if Rest Assured should url encode the URL automatically. Usually this is a recommended but in some cases * e.g. the query parameters are already be encoded before you provide them to Rest Assured then it's useful to disable * URL encoding. For example: *

     * RestAssured.baseURI = "https://jira.atlassian.com";
     * RestAssured.port = 443;
     * RestAssured.urlEncodingEnabled = false; // Because "query" is already url encoded
     * String query = "project%20=%20BAM%20AND%20issuetype%20=%20Bug";
     * String response = get("/rest/api/2.0.alpha1/search?jql={q}",query).andReturn().asString();
     * ...
     * 
* The query is already url encoded so you need to disable Rest Assureds url encoding to prevent double encoding. */ public static boolean urlEncodingEnabled = DEFAULT_URL_ENCODING_ENABLED; /** * Set an authentication scheme that should be used for each request. By default no authentication is used. * If you have specified an authentication scheme and wish to override it for a single request then * you can do this using: *

*

     *     given().auth().none()..
     * 
*/ public static AuthenticationScheme authentication = DEFAULT_AUTH; /** * Define a configuration for redirection settings and http client parameters (default is null). E.g. *
     * RestAssured.config = config().redirect(redirectConfig().followRedirects(true).and().maxRedirects(0));
     * 
*

* config() can be statically imported from {@link RestAssuredConfig}. *

*

*/ public static RestAssuredConfig config = null; /** * Set the default root path of the response body so that you don't need to write the entire path for each expectation. * E.g. instead of writing: *

*

     * expect().
     *          body("x.y.firstName", is(..)).
     *          body("x.y.lastName", is(..)).
     *          body("x.y.age", is(..)).
     *          body("x.y.gender", is(..)).
     * when().
     *          get(..);
     * 
*

* you can use a root and do: *

     * RestAssured.rootPath = "x.y";
     * expect().
     *          body("firstName", is(..)).
     *          body("lastName", is(..)).
     *          body("age", is(..)).
     *          body("gender", is(..)).
     * when().
     *          get(..);
     * 
*/ public static String rootPath = DEFAULT_BODY_ROOT_PATH; /** * Specify a default request specification that will be sent with each request. E,g. *
     * RestAssured.requestSpecification = new RequestSpecBuilder().addParameter("parameter1", "value1").build();
     * 
*

* means that for each request by Rest Assured "parameter1" will be equal to "value1". */ public static RequestSpecification requestSpecification = null; /** * Specify a default parser. This parser will be used if the response content-type * doesn't match any pre-registered or custom registered parsers. Also useful if the response * doesn't contain a content-type at all. */ public static Parser defaultParser = null; /** * Specify a default response specification that will be sent with each request. E,g. *

     * RestAssured.responseSpecification = new ResponseSpecBuilder().expectStatusCode(200).build();
     * 
*

* means that for each response Rest Assured will assert that the status code is equal to 200. */ public static ResponseSpecification responseSpecification = null; /** * Set the default session id value that'll be used for each request. This value will be set in the {@link com.jayway.restassured.config.SessionConfig} so it'll * override the session id value previously defined there (if any). If you need to change the sessionId cookie name you need to configure and supply the {@link com.jayway.restassured.config.SessionConfig} to * RestAssured.config. */ public static String sessionId = DEFAULT_SESSION_ID_VALUE; private static Object requestContentType = null; private static Object responseContentType = null; private static KeystoreSpec keystoreSpec = new NoKeystoreSpecImpl(); private static List filters = new LinkedList(); /** * The following documentation is taken from http://groovy.codehaus.org/modules/http-builder/doc/ssl.html: *

*

SSL Configuration

*

* SSL should, for the most part, "just work." There are a few situations where it is not completely intuitive. You can follow the example below, or see HttpClient's SSLSocketFactory documentation for more information. *

*

SSLPeerUnverifiedException

*

* If you can't connect to an SSL website, it is likely because the certificate chain is not trusted. This is an Apache HttpClient issue, but explained here for convenience. To correct the untrusted certificate, you need to import a certificate into an SSL truststore. *

* First, export a certificate from the website using your browser. For example, if you go to https://dev.java.net in Firefox, you will probably get a warning in your browser. Choose "Add Exception," "Get Certificate," "View," "Details tab." Choose a certificate in the chain and export it as a PEM file. You can view the details of the exported certificate like so: *

     * $ keytool -printcert -file EquifaxSecureGlobaleBusinessCA-1.crt
     * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
     * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
     * Serial number: 1
     * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020
     * Certificate fingerprints:
     * MD5:  8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC
     * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45
     * Signature algorithm name: MD5withRSA
     * Version: 3
     * ....
     * 
* Now, import that into a Java keystore file: *
     * $ keytool -importcert -alias "equifax-ca" -file EquifaxSecureGlobaleBusinessCA-1.crt -keystore truststore.jks -storepass test1234
     * Owner: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
     * Issuer: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
     * Serial number: 1
     * Valid from: Mon Jun 21 00:00:00 EDT 1999 until: Sun Jun 21 00:00:00 EDT 2020
     * Certificate fingerprints:
     * MD5:  8F:5D:77:06:27:C4:98:3C:5B:93:78:E7:D7:7D:9B:CC
     * SHA1: 7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45
     * Signature algorithm name: MD5withRSA
     * Version: 3
     * ...
     * Trust this certificate? [no]:  yes
     * Certificate was added to keystore
     * 
* Now you want to use this truststore in your client: *
     * RestAssured.keystore("/truststore.jks", "test1234");
     * 
* or *
     * given().keystore("/truststore.jks", "test1234"). ..
     * 
*

* * @param pathToJks The path to the JKS. REST Assured will first look in the classpath and if not found it will look for the JKS in the local file-system * @param password The store pass */ public static KeystoreSpec keystore(String pathToJks, String password) { Validate.notEmpty(password, "Password cannot be empty"); return setKeyStore(pathToJks, password); } /** * Use a keystore located on the file-system. See {@link #keystore(String, String)} for more details. * * @param pathToJks The path to JKS file on the file-system * @param password The password for the keystore * @return The request specification * @see #keystore(String, String) */ public static KeystoreSpec keystore(File pathToJks, String password) { Validate.notNull(pathToJks, "Path to JKS on the file system cannot be null"); return setKeyStore(pathToJks, password); } /** * Uses the user default keystore stored in @{user.home}/.keystore * * @param password - Use null for no password * @return */ public static KeystoreSpec keystore(String password) { return setKeyStore(null, password); } /** * The the default filters to apply to each request. * * @param filters The filter list */ public static void filters(List filters) { Validate.notNull(filters, "Filter list cannot be null"); RestAssured.filters.addAll(filters); } /** * The the default filters to apply to each request. * * @param filter The filter to set * @param additionalFilters An optional array of additional filters to set */ public static void filters(Filter filter, Filter... additionalFilters) { Validate.notNull(filter, "Filter cannot be null"); RestAssured.filters.add(filter); if (additionalFilters != null) { Collections.addAll(RestAssured.filters, additionalFilters); } } /** * @return The current default filters */ public static List filters() { return Collections.unmodifiableList(filters); } /** * Set a object mapper that'll be used when serializing and deserializing Java objects to and from it's * document representation (XML, JSON etc). * * @param objectMapper The object mapper to use. */ public static void objectMapper(ObjectMapper objectMapper) { Validate.notNull(objectMapper, "Default object mapper cannot be null"); config = config().objectMapperConfig(objectMapperConfig().defaultObjectMapper(objectMapper)); } public static Object requestContentType() { return requestContentType; } public static Object responseContentType() { return responseContentType; } public static KeystoreSpec keystore() { return keystoreSpec; } /** * Specify the default content type * * @param contentType The content type */ public static void requestContentType(ContentType contentType) { requestContentType = contentType; } /** * Specify the default content type * * @param contentType The content type */ public static void requestContentType(String contentType) { requestContentType = contentType; } /** * Specify the default content type (also sets the accept header). * * @param contentType The content type */ public static void responseContentType(ContentType contentType) { responseContentType = contentType; } /** * Specify the default content type (also sets the accept header). * * @param contentType The content type */ public static void responseContentType(String contentType) { responseContentType = contentType; } /** * Start building the response part of the test com.jayway.restassured.specification. E.g. *

*

     * expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");
     * 
*

* will expect that the response body for the GET request to "/lotto" should * contain JSON or XML which has a lottoId equal to 5. * * @return A response com.jayway.restassured.specification. */ public static ResponseSpecification expect() { return createTestSpecification().getResponseSpecification(); } /** * Start building the request part of the test com.jayway.restassured.specification. E.g. *

*

     * with().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");
     * 
*

* will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and * expect that the response body containing JSON or XML firstName equal to John. *

* The only difference between {@link #with()} and {@link #given()} is syntactical. * * @return A request specification. */ public static RequestSpecification with() { return given(); } /** * Create a list of arguments that can be used to create parts of the path in a body/content expression. * This is useful in situations where you have e.g. pre-defined variables that constitutes the key. For example: *

     * String someSubPath = "else";
     * int index = 1;
     * expect().body("something.%s[%d]", withArgs(someSubPath, index), equalTo("some value")). ..
     * 
*

* or if you have complex root paths and don't wish to duplicate the path for small variations: *

     * expect().
     *          root("filters.filterConfig[%d].filterConfigGroups.find { it.name == 'Gold' }.includes").
     *          body("", withArgs(0), hasItem("first")).
     *          body("", withArgs(1), hasItem("second")).
     *          ..
     * 
*

* The key and arguments follows the standard formatting syntax of Java. * * @return A list of arguments that can be used to build up the */ public static List withArguments(Object firstArgument, Object... additionalArguments) { Validate.notNull(firstArgument, "You need to supply at least one argument"); final List arguments = new LinkedList(); arguments.add(Argument.arg(firstArgument)); if (additionalArguments != null && additionalArguments.length > 0) { for (Object additionalArgument : additionalArguments) { arguments.add(Argument.arg(additionalArgument)); } } return Collections.unmodifiableList(arguments); } /** * Slightly shorter version of {@link #withArguments(Object, Object...)}. * * @return A list of arguments. * @see #withArguments(Object, Object...) */ public static List withArgs(Object firstArgument, Object... additionalArguments) { return withArguments(firstArgument, additionalArguments); } /** * Start building the request part of the test com.jayway.restassured.specification. E.g. *

*

     * given().parameters("firstName", "John", "lastName", "Doe").expect().body("greeting.firstName", equalTo("John")).when().post("/greetXML");
     * 
*

* will send a POST request to "/greetXML" with request parameters firstName=John and lastName=Doe and * expect that the response body containing JSON or XML firstName equal to John. *

* The only difference between {@link #with()} and {@link #given()} is syntactical. * * @return A request specification. */ public static RequestSpecification given() { return createTestSpecification().getRequestSpecification(); } /** * When you have long specifications it can be better to split up the definition of response and request specifications in multiple lines. * You can then pass the response and request specifications to this method. E.g. *

*

     * RequestSpecification requestSpecification = with().parameters("firstName", "John", "lastName", "Doe");
     * ResponseSpecification responseSpecification = expect().body("greeting", equalTo("Greetings John Doe"));
     * given(requestSpecification, responseSpecification).get("/greet");
     * 
*

* This will perform a GET request to "/greet" and verify it according to the responseSpecification. * * @return A test com.jayway.restassured.specification. */ public static RequestSender given(RequestSpecification requestSpecification, ResponseSpecification responseSpecification) { return new TestSpecificationImpl(requestSpecification, responseSpecification); } /** * Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do get("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the GET request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response get(String path, Object... pathParams) { return given().get(path, pathParams); } /** * Perform a GET request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the GET request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response get(String path, Map pathParams) { return given().get(path, pathParams); } /** * Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do post("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response post(String path, Object... pathParams) { return given().post(path, pathParams); } /** * Perform a POST request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response post(String path, Map pathParams) { return given().post(path, pathParams); } /** * Perform a PUT request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do put("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response put(String path, Object... pathParams) { return given().put(path, pathParams); } /** * Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do delete("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response delete(String path, Object... pathParams) { return given().delete(path, pathParams); } /** * Perform a DELETE request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response delete(String path, Map pathParams) { return given().delete(path, pathParams); } /** * Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response head(String path, Object... pathParams) { return given().head(path, pathParams); } /** * Perform a HEAD request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response head(String path, Map pathParams) { return given().head(path, pathParams); } /** * Perform a PATCH request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response patch(String path, Object... pathParams) { return given().patch(path, pathParams); } /** * Perform a PATCH request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response patch(String path, Map pathParams) { return given().patch(path, pathParams); } /** * Perform a OPTIONS request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. E.g. if path is "/book/{hotelId}/{roomNumber}" you can do head("/book/{hotelName}/{roomNumber}", "Hotels R Us", 22);. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response options(String path, Object... pathParams) { return given().options(path, pathParams); } /** * Perform a OPTIONS request to a path. Normally the path doesn't have to be fully-qualified e.g. you don't need to * specify the path as http://localhost:8080/path. In this case it's enough to use /path. * * @param path The path to send the request to. * @param pathParams The path parameters. * @return The response of the request. The response can only be returned if you don't use any REST Assured response expectations. */ public static Response options(String path, Map pathParams) { return given().options(path, pathParams); } /** * Create a http basic authentication scheme. * * @param userName The user name. * @param password The password. * @return The authentication scheme */ public static AuthenticationScheme basic(String userName, String password) { final BasicAuthScheme scheme = new BasicAuthScheme(); scheme.setUserName(userName); scheme.setPassword(password); return scheme; } /** * Use form authentication. Rest Assured will try to parse the response * login page and determine and try find the action, username and password input * field automatically. *

* Note that the request will be much faster if you also supply a form auth configuration. *

* * @param userName The user name. * @param password The password. * @return The authentication scheme * @see #form(String, String, com.jayway.restassured.authentication.FormAuthConfig) */ public static AuthenticationScheme form(String userName, String password) { return form(userName, password, null); } /** * Use form authentication with the supplied configuration. * * @param userName The user name. * @param password The password. * @param config The form authentication config * @return The authentication scheme */ public static AuthenticationScheme form(String userName, String password, FormAuthConfig config) { if (userName == null) { throw new IllegalArgumentException("Username cannot be null"); } if (password == null) { throw new IllegalArgumentException("Password cannot be null"); } final FormAuthScheme scheme = new FormAuthScheme(); scheme.setUserName(userName); scheme.setPassword(password); scheme.setConfig(config); return scheme; } /** * Return the http preemptive authentication specification for setting up preemptive authentication requests. * This means that the authentication details are sent in the request header regardless if the server challenged * for authentication or not. * * @return The authentication scheme */ public static PreemptiveAuthProvider preemptive() { return new PreemptiveAuthProvider(); } /** * Sets a certificate to be used for SSL authentication. See {@link java.lang.Class#getResource(String)} * for how to get a URL from a resource on the classpath. *

* Uses keystore: KeyStore.getDefaultType().
* Uses port: 443
* Uses keystore provider: none
*

* * @param certURL URL to a JKS keystore where the certificate is stored. * @return The request com.jayway.restassured.specification */ public static AuthenticationScheme certificate(String certURL, String password) { final CertAuthScheme scheme = new CertAuthScheme(); scheme.setCertURL(certURL); scheme.setPassword(password); return scheme; } /** * Sets a certificate to be used for SSL authentication. See {@link Class#getResource(String)} for how to get a URL from a resource * on the classpath. * * @param certURL URL to a JKS keystore where the certificate is stored. * @param password password to decrypt the keystore * @param certType The certificate type * @param port The SSL port * @param trustStoreProvider The provider */ public static AuthenticationScheme certificate(String certURL, String password, String certType, int port, KeystoreProvider trustStoreProvider) { final CertAuthScheme scheme = new CertAuthScheme(); scheme.setCertURL(certURL); scheme.setPassword(password); scheme.setCertType(certType); scheme.setPort(port); scheme.setTrustStoreProvider(trustStoreProvider); return scheme; } /** * Sets a certificate to be used for SSL authentication. See {@link Class#getResource(String)} for how to get a URL from a resource * on the classpath. * * @param certURL URL to a JKS keystore where the certificate is stored. * @param password password to decrypt the keystore * @param certType The certificate type * @param port The SSL port */ public static AuthenticationScheme certificate(String certURL, String password, String certType, int port) { return certificate(certURL, password, certType, port); } /** * Use http digest authentication. Note that you need to encode the password yourself. * * @param userName The user name. * @param password The password. * @return The authentication scheme */ public static AuthenticationScheme digest(String userName, String password) { return basic(userName, password); } /** * Excerpt from the HttpBuilder docs:
* OAuth sign the request. Note that this currently does not wait for a WWW-Authenticate challenge before sending the the OAuth header. * All requests to all domains will be signed for this instance. * This assumes you've already generated an accessToken and secretToken for the site you're targeting. * For More information on how to achieve this, see the Signpost documentation. * * @param consumerKey * @param consumerSecret * @param accessToken * @param secretToken * @return The authentication scheme */ public static AuthenticationScheme oauth(String consumerKey, String consumerSecret, String accessToken, String secretToken) { OAuthScheme scheme = new OAuthScheme(); scheme.setConsumerKey(consumerKey); scheme.setConsumerSecret(consumerSecret); scheme.setAccessToken(accessToken); scheme.setSecretToken(secretToken); return scheme; } /** * Register a custom content-type to be parsed using a predefined parser. E.g. let's say you want parse * content-type application/vnd.uoml+xml with the XML parser to be able to verify the response using the XML dot notations: *
     * expect().body("document.child", equalsTo("something"))..
     * 
* Since application/vnd.uoml+xml is not registered to be processed by the XML parser by default you need to explicitly * tell REST Assured to use this parser before making the request: *
     * RestAssured.registerParser("application/vnd.uoml+xml, Parser.XML");
     * 
* * @param contentType The content-type to register * @param parser The parser to use when verifying the response. */ public static void registerParser(String contentType, Parser parser) { RESPONSE_PARSER_REGISTRAR.registerParser(contentType, parser); } /** * Unregister the parser associated with the provided content-type * * @param contentType The content-type associated with the parser to unregister. */ public static void unregisterParser(String contentType) { RESPONSE_PARSER_REGISTRAR.unregisterParser(contentType); } /** * Resets the {@link #baseURI}, {@link #basePath}, {@link #port}, {@link #authentication} and {@link #rootPath}, {@link #requestContentType(com.jayway.restassured.http.ContentType)}, * {@link #responseContentType(com.jayway.restassured.http.ContentType)}, {@link #filters(java.util.List)}, {@link #requestSpecification}, {@link #responseSpecification}. {@link #keystore(String, String)}, * {@link #urlEncodingEnabled} , {@link #config} and {@link #sessionId} to their default values of {@value #DEFAULT_URI}, {@value #DEFAULT_PATH}, {@value #DEFAULT_PORT}, no authentication, "", null, null, * "empty list", null, null, none, true, null, null */ public static void reset() { baseURI = DEFAULT_URI; port = DEFAULT_PORT; basePath = DEFAULT_PATH; authentication = DEFAULT_AUTH; rootPath = DEFAULT_BODY_ROOT_PATH; filters = new LinkedList(); requestContentType = null; responseContentType = null; requestSpecification = null; responseSpecification = null; keystoreSpec = new NoKeystoreSpecImpl(); urlEncodingEnabled = DEFAULT_URL_ENCODING_ENABLED; RESPONSE_PARSER_REGISTRAR = new ResponseParserRegistrar(); defaultParser = null; config = null; sessionId = DEFAULT_SESSION_ID_VALUE; } private static TestSpecificationImpl createTestSpecification() { if (defaultParser != null) { RESPONSE_PARSER_REGISTRAR.registerDefaultParser(defaultParser); } final ResponseParserRegistrar responseParserRegistrar = new ResponseParserRegistrar(RESPONSE_PARSER_REGISTRAR); applySessionIdIfApplicable(); return new TestSpecificationImpl( new RequestSpecificationImpl(baseURI, port, basePath, authentication, filters, keystoreSpec, requestContentType, requestSpecification, urlEncodingEnabled, config), new ResponseSpecificationImpl(rootPath, responseContentType, responseSpecification, responseParserRegistrar, config())); } private static void applySessionIdIfApplicable() { if (!StringUtils.equals(sessionId, DEFAULT_SESSION_ID_VALUE)) { final RestAssuredConfig configToUse; if (config == null) { configToUse = new RestAssuredConfig(); } else { configToUse = config; } config = configToUse.sessionConfig(configToUse.getSessionConfig().sessionIdValue(sessionId)); } } private static KeystoreSpec setKeyStore(Object pathToJks, String password) { final KeystoreSpecImpl spec = new KeystoreSpecImpl(); spec.setPath(pathToJks); spec.setPassword(password); RestAssured.keystoreSpec = spec; return keystoreSpec; } private static RestAssuredConfig config() { return config == null ? new RestAssuredConfig() : config; } }