Class RestSpec

    • Constructor Detail

      • RestSpec

        public RestSpec​(CommonG spec)
    • Method Detail

      • setupApp

        @Given("^I( securely)? send requests to \'(.*)\'$")
        public void setupApp​(String isSecured,
                             String restHost)
        Set app host and port for Rest requests.

        This is an initialization step. This is used as the first step in rest features to configure the basepath url. This parameters will be used for all future requests in the same scenario. The rest request is build within the HookGSpec class, so, don't forget to use the @rest annotation at the beginning of your feature for a proper initialization.

         Example:
         
              Given I send requests to 'jsonplaceholder.typicode.com'       //If no port is specified, will default to 80 -> http://jsonplaceholder.typicode.com:80
              Given I send requests to 'jsonplaceholder.typicode.com:8080'  //Will use -> http:jsonplaceholder.typicode.com:8080
         
         Or su can use the keyword 'securely' to use https
         
              Given I securely send requests to 'jsonplaceholder.typicode.com'    //If no port is specified, will default to 443 -> https//:jsonplaceholder.typicode.com:443
         
         
        Parameters:
        isSecured - Indicates if https:// should be used (if false, defaults to http://)
        restHost - Port where the API is running. Defaults to 80 if null
      • matchWithExpresion

        @Then("^\'(.*)\' matches the following cases:$")
        public void matchWithExpresion​(String envVar,
                                       io.cucumber.datatable.DataTable table)
        Verifies the structure of a json document against a set of test cases defined in a datatable

        This step is typically used to verify the response body of a request. The json to verify must have been previously saved in a variable using for example saveElementEnvironment(String, String, String)

         Example: Assuming that 'response' contains a json document
         
              And 'response' matches the following cases:
               | $.title  | contains  | 2              |
               | $.body   | contains  | This is a test |
               | $.userId | not equal | 2              |
         
         First column: jsonpath of the element in the body to verify
         Second column: operator (equal|not equal|contains|does not contain|length|exists|does not exists|size)
         Third column: Value to match against
         
        Parameters:
        envVar - Environment variable where JSON is stored
        table - Data table in which each row stores one expression
        See Also:
        saveElementEnvironment(String, String, String)
      • sendRequestNoDataTable

        @When("^I send a \'(.+?)\' request to \'(.+?)\'( with user and password \'(.+:.+?)\')?( based on \'([^:]+?)\')?( as \'(json|string)\')?$")
        public void sendRequestNoDataTable​(String requestType,
                                           String endPoint,
                                           String loginInfo,
                                           String baseData,
                                           String type)
                                    throws Exception
        Generates a REST request of the type specified to the indicated endpoint

        The endpoint must be relative to the base path previously defined with setupApp(String, String)

         Example: Executing a simple GET request
         
              Given I securely send requests to 'jsonplaceholder.typicode.com:443'
              When I send a 'GET' request to '/posts'      //Executes a GET request to https://jsonplaceholder.typicode.com:443/posts
         
         Example: Using basic authentication:
         
              Given I securely send requests to 'jsonplaceholder.typicode.com:443'
              When I send a 'GET' request to '/posts' with user and password 'user:password'
         
         Example: Sending a POST request with body
         
              Given I securely send requests to 'jsonplaceholder.typicode.com:443'
              When I send a 'POST' request to '/posts' based on 'schemas/mytestdata.json' as 'json' //Executes a POST request with the content of mytestdata.json as body
         
         If you need to alter the content of the json document before sending you could use sendRequestDataTable(String, String, String, String, String, DataTable)
         
        Parameters:
        requestType - HTTP verb (type of request): POST, GET, PUT, PATCH, DELETE
        endPoint - Endpoint (i.e /user/1). The base path used is the one indicated in a previous step
        loginInfo - User and password to use if the endpoints requires basic authentication (user:password)
        baseData - If specified, the content of the file will be loaded in the body of the request (POST, PUT, PATCH operations)
        type - If the content of the file should be read as string or json
        Throws:
        Exception - Exception
        See Also:
        setupApp(String, String), sendRequestDataTable(String, String, String, String, String, DataTable)
      • sendRequestDataTable

        @When("^I send a \'(.+?)\' request to \'(.+?)\'( with user and password \'(.+:.+?)\')? based on \'([^:]+?)\'( as \'(json|string)\')? with:$")
        public void sendRequestDataTable​(String requestType,
                                         String endPoint,
                                         String loginInfo,
                                         String baseData,
                                         String type,
                                         io.cucumber.datatable.DataTable modifications)
                                  throws Exception
        Send a request of the type specified

        This function works in the same way as sendRequestNoDataTable(String, String, String, String, String) the difference is that this one accepts a datatable with a list of modification to be applied to the json body before the request is executed

         Example: Send a POST request with the content of schemas/mytestdata.json as body data
         
              Given I securely send requests to 'jsonplaceholder.typicode.com:443'
              When I send a 'POST' request to '/posts' based on 'schemas/mytestdata.json' as 'json' with:
                  | $.title | UPDATE | This is a test 2 |
         
         First column: Element in the json document to modify
         Second column: Operation to execute (DELETE|ADD|UPDATE)
         Third column: New value
         
        Parameters:
        requestType - type of request to be sent. Possible values: GET|DELETE|POST|PUT|PATCH
        endPoint - end point to be used
        baseData - path to file containing the schema to be used
        type - element to read from file (element should contain a json)
        loginInfo - credentials for basic auth (if required)
        modifications - DataTable containing the modifications to be done to the base schema element. Syntax will be: | <key path> | <type of modification> | <new value> | where: key path: path to the key to be modified type of modification: DELETE|ADD|UPDATE new value: in case of UPDATE or ADD, new value to be used for example: if the element read is {"key1": "value1", "key2": {"key3": "value3"}} and we want to modify the value in "key3" with "new value3" the modification will be: | key2.key3 | UPDATE | "new value3" | being the result of the modification: {"key1": "value1", "key2": {"key3": "new value3"}}
        Throws:
        Exception - Exception
        See Also:
        setupApp(String, String), sendRequestNoDataTable(String, String, String, String, String)
      • assertResponseStatusLength

        @Then("^the service response status must be \'(.*?)\'( (and its response length must be \'.*?\')| (and its response must contain the text \'.*?\')| (and its response matches the schema in \'.*?\'))?$")
        public void assertResponseStatusLength​(Integer expectedStatus,
                                               String responseAssert)
        Verifies the status response (HTTP response code) of a rest request.

        Additionally, the step can verify the response (body) length, and if the body contains a given character or matches a defined schema. For this step to work, a previous request must have been executed such as sendRequestNoDataTable(String, String, String, String, String) or sendRequestDataTable(String, String, String, String, String, DataTable)

         Example: Verify the response status code
         
              When I send a 'GET' request to '/posts'
              Then the service response status must be '200'
         
         Example: Checking the response body length
         
             When I send a 'GET' request to '/comments/1'
             Then the service response status must be '200' and its response length must be '268'
         
         Example: Verify the response body contains a specific text
         
             When I send a 'GET' request to '/posts'
             Then the service response status must be '200' and its response must contain the text 'body'
         
         Example: Verify that the response body matches a json schema
         
             When I send a 'GET' request to '/posts'
             Then the service response status must be '200' and its response matches the schema in 'schemas/responseSchema.json'
         
         * The file schemas/responseSchema.json must contains a valid json schema (http://json-schema.org/)
         
        Parameters:
        expectedStatus - Expected HTTP status code
        responseAssert - Expression to determine if assert length, text or schema
        See Also:
        sendRequestNoDataTable(String, String, String, String, String), sendRequestDataTable(String, String, String, String, String, DataTable), http://json-schema.org/
      • saveElementEnvironment

        @Given("^I save element (in position \'(.+?)\' in )?\'(.+?)\' in environment variable \'(.+?)\'$")
        public void saveElementEnvironment​(String position,
                                           String element,
                                           String envVar)
        Saves value of a json document for future use.

        This step is typically used to save the body response of a HTTP request (either the full body response or just an specific element). If this is the case, a previous HTTP request operation must have been performed (with sendRequestDataTable(String, String, String, String, String, DataTable) or with sendRequestNoDataTable(String, String, String, String, String))

         Example: If element is a jsonpath expression (i.e. $.fragments[0].id), it will be applied over the last httpResponse.
         
              When I send a 'GET' request to '/posts'
              And I save element '$' in environment variable 'response' //saves all body in variable response
              And I save element '$.[0].userId' in environment variable 'USER_ID' //Saves only the element $.[0].userId of the response
         
         Example: If element is a jsonpath expression preceded by some other string (i.e. ["a","b",,"c"].$.[0]), it will be applied over
         this string. This will help to save the result of a jsonpath expression evaluated over previous stored variable.
         
              And I save element '["a","b","c","d"].$.[0]' in environment variable 'letter' //Will save 'a' in variable 'letter'
         
         Or from a previous HTTP request:
         
              When I send a 'GET' request to '/users'                                             //returns an array of 'users' objects
              And I save element '$.[0]' in environment variable 'first_user'                     //stores the first user object in 'first_user'
              And I save element '!{first_user}.$.username' in environment variable 'username'    //get the field 'username' from 'first_user' and stores it in 'username'
              Then '!{username}' matches 'Bret'                                                   //Checks variable matches given value
         
         
        Parameters:
        position - position from a search result
        element - key in the json response to be saved
        envVar - thread environment variable where to store the value
        See Also:
        sendRequestNoDataTable(String, String, String, String, String), sendRequestDataTable(String, String, String, String, String, DataTable), http://json-schema.org/
      • setHeaders

        @Given("^I set headers:$")
        public void setHeaders​(io.cucumber.datatable.DataTable modifications)
        Specify a custom map of headers to be added to future requests

        The headers will be applied to all following requests in the same scenario unless you clear then using clearHeaders()

         Example: Set headers for following requests
         
              Given I send requests to 'dummy-test.com:80'
              Given I set headers:
                  | Authorization  | mySecretToken1234 |
                  | Content-Type   | application/json  |
              When I send a 'GET' request to '/api/v1/shipment/1' //this (and following) request(s) will contain those headers
         
         
        Parameters:
        modifications - DataTable containing the custom set of headers to be added to the requests. Syntax will be: | <key> | <value> | where: key: header key name value: value for tue key for example: if we want to add the header "token" with value "12345678", to the request header the modification will be: | token | 12345678 |
        See Also:
        clearHeaders(), setCookies(DataTable), clearCookies()
      • setCookies

        @Given("^I set cookies:$")
        public void setCookies​(io.cucumber.datatable.DataTable modifications)
        Specify a custom map of cookies to be added to future requests

        Works in a similar way that setHeaders(DataTable). The cookies will be applied to all following requests in the same scenario unless you clear then using clearCookies()

         Example: Set cookies for following requests
         
              Given I send requests to 'dummy-test.com:80'
              Given I set cookies:
                  | myCookieName  | myCookieValue |
              When I send a 'GET' request to '/api/v1/shipment/1' //this (and following) request(s) will contain those cookies
         
         
        Parameters:
        modifications - DataTable containing the custom set of cookies to be added to the requests. Syntax will be: | <key> | <value> | where: key: cookie key name value: cookie for tue key for example: if we want to add the cookie "token" with value "12345678", to the request cookie the modification will be: | token | 12345678 |
        See Also:
        setHeaders(DataTable), clearHeaders(), clearCookies()
      • clearHeaders

        @Then("^I clear headers from previous request$")
        public void clearHeaders()
        Clears the headers set by any previous request.

        A request will reuse the headers/cookies that were set in any previous call within the same scenario

         Example:
         
              Given I send requests to 'dummy-test.com:80'
              Given I set headers:
                  | Authorization  | mySecretToken1234 |
                  | Content-Type   | application/json  |
              When I send a 'GET' request to '/api/v1/shipment/1' //this (and following) request(s) will contain those headers
              Then I clear headers from previous request
              When I send a 'GET' request to '/api/v1/settings'   //This request will not contains previous set headers
         
         
        See Also:
        setHeaders(DataTable), setCookies(DataTable), clearCookies()
      • clearCookies

        @Then("^I clear cookies from previous request$")
        public void clearCookies()
        Clears the cookies set by any previous request.

        A request will reuse the headers/cookies that were set in any previous call within the same scenario

         Example:
         
              Given I send requests to 'dummy-test.com:80'
              Given I set cookies:
                  | myCookieName  | myCookieValue |
              When I send a 'GET' request to '/api/v1/shipment/1' //this (and following) request(s) will contain those cookies
              Then I clear cookies from previous request
              When I send a 'GET' request to '/api/v1/shipment/1' //this request will not contain the cookies
         
         
        See Also:
        setCookies(DataTable), setHeaders(DataTable), clearHeaders()
      • sendRequestTimeout

        @Deprecated
        @When("^in less than \'(\\d+)\' seconds, checking each \'(\\d+)\' seconds, I send a \'(.*)\' request to \'(.*)\' so that the response( does not)? contains \'(.*)\'$")
        public void sendRequestTimeout​(Integer timeout,
                                       Integer wait,
                                       String requestType,
                                       String endPoint,
                                       String contains,
                                       String responseVal)
                                throws InterruptedException
        Deprecated.
        Executes the given request to the REST endpont for the specified amount of time in regular intervals, until the response body contains the specified text
        Parameters:
        timeout - Maximum time to wait for the text to be present in the response body
        wait - Time between retries
        requestType - Type of request (POST, GET, PATCH, DELETE, PUT)
        endPoint - Endpoint (i.e /user/1)
        responseVal - Expected value to evaluate in the response body
        contains - parameter generated by cucumber because of the optional expression
        Throws:
        InterruptedException - InterruptedException
      • checkHeaders

        @And("^the service response headers match the following cases:$")
        public void checkHeaders​(io.cucumber.datatable.DataTable table)
        Checks if the headers in the response matches the specified values

        A previous HTTP request operation must have been executed, such as sendRequestNoDataTable(String, String, String, String, String) or sendRequestDataTable(String, String, String, String, String, DataTable)

         Example:
         
             When I send a 'GET' request to '/api/v1/shipment/1' as 'json'
             Then the service response status must be '200'
             And the service response headers match the following cases:
               | Server           | equal           | nginx |
               | Content-Encoding | equal           | gzip  |
         
         
        Parameters:
        table - DataTable containing the custom set of headers to be added to the requests. Syntax will be: | <header name> | <condition> | <expected value> where: header name: Header name condition: Condition that is going to be evaluated (available: equal, not equal, exists, does not exists, contains, does not contain, length, size) expected value: Value used to verify the condition for example: If we want to verify that the header "Content-Encoding" is equal to "application/json" we would do | Content-Encoding | equal | application/json |
        See Also:
        sendRequestDataTable(String, String, String, String, String, DataTable), sendRequestNoDataTable(String, String, String, String, String)
      • saveCookieValue

        @And("^I save the response cookie \'(.*)\' in environment variable \'(.*)\'$")
        public void saveCookieValue​(String cookieName,
                                    String varName)
                             throws Throwable
        Saves the cookie value for future use

        Similar to saveHeaderValue(String, String)

        Parameters:
        cookieName - Cookie name
        varName - Name of the environmental variable
        Throws:
        Throwable - Throwable
      • iSetUrlQueryParameters

        @Given("^I set url parameters:$")
        public void iSetUrlQueryParameters​(io.cucumber.datatable.DataTable modifications)
        Specify a custom map of url query parameters to be added to future requests
         Example:
         
              Given I securely send requests to 'jsonplaceholder.typicode.com:443'
              Given I set url parameters:
                   | userId | 3 |
              When I send a 'GET' request to '/posts'     //will execute https://jsonplaceholder.typicode.com:443/posts?userId=3
         
         
        Parameters:
        modifications - DataTable containing the custom set of url query parameters to be added to the requests. Syntax will be: | <key> | <value> | where: key: parameters name value: parameters value for example: if we want to add the parameter "id" with value "1", to the request url the modification will be: Given I set url parameters | id | 1 | When I send a 'GET' request to '/posts' This will produce the request '/posts?id=1'
        See Also:
        setupApp(String, String), sendRequestDataTable(String, String, String, String, String, DataTable), sendRequestNoDataTable(String, String, String, String, String)
      • iClearTheUrlParametersFromPreviousRequest

        @Then("^I clear the url parameters from previous request$")
        public void iClearTheUrlParametersFromPreviousRequest()
        Clears the url query parameters that were configured in a previous step.

        Once the user uses the step to set url query parameters (Given I set url parameters), the parameters are automatically added to all future requests in the same scenario. This step allows to delete this parameters from the system, so new requests are created without any url query parameters

         Example:
         
              Given I securely send requests to 'jsonplaceholder.typicode.com:443'
              Given I set url parameters:
                   | userId | 3 |
              When I send a 'GET' request to '/posts'                 //will execute https://jsonplaceholder.typicode.com:443/posts?userId=3
              Then I clear the url parameters from previous request
              Given I set url parameters:
               | userId | 4 |
             When I send a 'GET' request to '/posts'                  //will execute https://jsonplaceholder.typicode.com:443/posts?userId=4
         
         
        See Also:
        iSetUrlQueryParameters(DataTable)
      • iAddTheFileToTheRequest

        @And("^I add the file in \'(.*)\' to the request$")
        public void iAddTheFileToTheRequest​(String filePath)
                                     throws URISyntaxException
        Adds the specified file to the request as a form-params parameter (the request contentType must be changed to 'multipart/form-data')
        Parameters:
        filePath - file path
        Throws:
        URISyntaxException - URISyntaxException