Class RestSpec
- java.lang.Object
-
- com.privalia.qa.specs.BaseGSpec
-
- com.privalia.qa.specs.RestSpec
-
public class RestSpec extends BaseGSpec
Steps definitions for testing REST services- Author:
- Jose Fernandez
- See Also:
- https://github.com/rest-assured/rest-assured
-
-
Field Summary
-
Fields inherited from class com.privalia.qa.specs.BaseGSpec
commonspec
-
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
assertResponseMessage(String expectedText)
Verifies if the response body contains an specific stringvoid
assertResponseStatusLength(Integer expectedStatus, String responseAssert)
Verifies the status response (HTTP response code) of a rest request.void
checkCookies(io.cucumber.datatable.DataTable table)
Checks if the cookies in the response matches the specified valuesvoid
checkHeaders(io.cucumber.datatable.DataTable table)
Checks if the headers in the response matches the specified valuesvoid
clearCookies()
Clears the cookies set by any previous request.void
clearHeaders()
Clears the headers set by any previous request.void
iAddTheFileToTheRequest(String filePath)
Adds the specified file to the request as a form-params parameter (the request contentType must be changed to 'multipart/form-data')void
iClearTheUrlParametersFromPreviousRequest()
Clears the url query parameters that were configured in a previous step.void
iSetUrlQueryParameters(io.cucumber.datatable.DataTable modifications)
Specify a custom map of url query parameters to be added to future requestsvoid
matchWithExpresion(String envVar, io.cucumber.datatable.DataTable table)
Verifies the structure of a json document against a set of test cases defined in a datatablevoid
saveCookieValue(String cookieName, String varName)
Saves the cookie value for future usevoid
saveElementEnvironment(String position, String element, String envVar)
Saves value of a json document for future use.void
saveHeaderValue(String headerName, String varName)
Saves the header value for future usevoid
sendRequestDataTable(String requestType, String endPoint, String loginInfo, String baseData, String type, io.cucumber.datatable.DataTable modifications)
Send a request of the type specifiedvoid
sendRequestNoDataTable(String requestType, String endPoint, String loginInfo, String baseData, String type)
Generates a REST request of the type specified to the indicated endpointvoid
sendRequestTimeout(Integer timeout, Integer wait, String requestType, String endPoint, String contains, String responseVal)
Deprecated.void
setCookies(io.cucumber.datatable.DataTable modifications)
Specify a custom map of cookies to be added to future requestsvoid
setHeaders(io.cucumber.datatable.DataTable modifications)
Specify a custom map of headers to be added to future requestsvoid
setupApp(String isSecured, String restHost)
Set app host and port for Rest requests.-
Methods inherited from class com.privalia.qa.specs.BaseGSpec
getCommonSpec
-
-
-
-
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 httpsGiven 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 datatableThis 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 storedtable
- 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 endpointThe 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 bodyGiven 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 usesendRequestDataTable(String, String, String, String, String, DataTable)
- Parameters:
requestType
- HTTP verb (type of request): POST, GET, PUT, PATCH, DELETEendPoint
- Endpoint (i.e /user/1). The base path used is the one indicated in a previous steploginInfo
- 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 specifiedThis 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 executedExample: 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|PATCHendPoint
- end point to be usedbaseData
- path to file containing the schema to be usedtype
- 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)
orsendRequestDataTable(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 lengthWhen 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 textWhen 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 schemaWhen 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 coderesponseAssert
- 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/
-
assertResponseMessage
@Then("^the service response must contain the text \'(.*)\'$") public void assertResponseMessage(String expectedText)
Verifies if the response body contains an specific stringFor this step to work, a previous request must have been executed such as
sendRequestNoDataTable(String, String, String, String, String)
orsendRequestDataTable(String, String, String, String, String, DataTable)
Example:
When I send a 'GET' request to '/posts' And the service response must contain the text 'body'
- Parameters:
expectedText
- String to find in the response body- See Also:
sendRequestDataTable(String, String, String, String, String, DataTable)
,sendRequestNoDataTable(String, String, String, String, String)
,assertResponseStatusLength(Integer, String)
-
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 withsendRequestNoDataTable(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 resultelement
- key in the json response to be savedenvVar
- 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 requestsThe 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 requestsWorks in a similar way that
setHeaders(DataTable)
. The cookies will be applied to all following requests in the same scenario unless you clear then usingclearCookies()
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 bodywait
- Time between retriesrequestType
- Type of request (POST, GET, PATCH, DELETE, PUT)endPoint
- Endpoint (i.e /user/1)responseVal
- Expected value to evaluate in the response bodycontains
- 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 valuesA previous HTTP request operation must have been executed, such as
sendRequestNoDataTable(String, String, String, String, String)
orsendRequestDataTable(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)
-
checkCookies
@And("^the service response cookies match the following cases:$") public void checkCookies(io.cucumber.datatable.DataTable table)
Checks if the cookies in the response matches the specified valuesWorks in a similar way that
checkHeaders(DataTable)
. A previous HTTP request operation must have been executed such assendRequestNoDataTable(String, String, String, String, String)
orsendRequestDataTable(String, String, String, String, String, DataTable)
- Parameters:
table
- DataTable containing the custom set of cookies to be added to the requests. Syntax will be:| <cookies name> | <condition> | <expected value>
where: cookies 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 cookies "Content-Encoding" is equal to "application/json" we would do | Content-Encoding | equal | application/json |- See Also:
checkHeaders(DataTable)
,sendRequestDataTable(String, String, String, String, String, DataTable)
,sendRequestNoDataTable(String, String, String, String, String)
-
saveHeaderValue
@And("^I save the response header \'(.*)\' in environment variable \'(.*)\'$") public void saveHeaderValue(String headerName, String varName)
Saves the header value for future useExample:
Given I securely send requests to 'jsonplaceholder.typicode.com:443' When I send a 'GET' request to '/users' And I save the response header 'Content-Type' in environment variable 'content-type' Then '!{content-type}' matches 'application/json; charset=utf-8'
- Parameters:
headerName
- Header namevarName
- Name of the environmental variable- 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 useSimilar to
saveHeaderValue(String, String)
- Parameters:
cookieName
- Cookie namevarName
- 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 requestsExample:
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
-
-