Sharp weapon | REST Assured practice: assert the realization of Hogwarts Testing Institute. I wish you a auspicious year of the ox!

Posted by Chips on Tue, 11 Jan 2022 03:43:21 +0100

In the last article, we preliminarily discussed the application practice of [REST Assured]( http://mp.weixin.qq.com/s?__biz=MzU3NDM4ODEzMg==&mid=2247486810&idx=1&sn=4aa41547a92e761699b99928bc132442&chksm=fd326f91ca45e68713627d612d29fecabf1e1f4c5657a19f72dce47c16b695c1dfbe16ce2a02&scene=21#wechat_redirect ), there are many rich usages that need to be explored and studied slowly. and
REST Assured provides complete assertion means, which is one of the most common and important functions for test engineers. How should assertions be used?

** 1. Jason assertion**

1.1 environmental preparation

Here is an example given by the official rest assured to demonstrate learning

{"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] }]}}

Temporarily set up a service using python -m CGIHTTPServer locally:

1.2 JsonPath(Groovy's GPath)

On Groovy's official website, although its use in json is not mentioned, in fact, as long as it is a tree hierarchical relationship, whether it is json or xml
Or other formats, you can use this simple syntax to help us find the value. Rest assured has also helped us implement the assertion method that supports GPath

Root node Child node
1) We can use the root node (point) find the child nodes layer by layer. For example, we need to assert that lottoId is equal to 5:

@Testvoid testGPath(){     given().     when().             log().all().get("http://127.0.0.1:8000/restAssured.json").     then().             log().all().body("lotto.lottoId",equalTo(5)); }

2) If we want to assert the winnerId under the winners array, check whether 23 and 54 are included, as shown in lotto winners. winnerId writing method

@Testvoid testGPath(){    given().    when().            log().all().get("http://127.0.0.1:8000/restAssured.json").    then().            log().all()            .body("lotto.winners.winnerId",hasItems(54,23));}

``

Index value

**
**

1) If we want to get one of the same fields, we can use an index like method. For example, if we want to assert whether the first value of winnerId under the winners array is 23, we can use lotto winners. winnerId [0], written as follows:

@Testvoid testGPath(){    given().    when().            log().all().get("http://127.0.0.1:8000/restAssured.json").    then().            log().all()            .body("lotto.winners.winnerId[0]",equalTo(23));}

2) If we want to get the last one in some of the same fields, we can use - 1 as the index. For example, we can assert whether the value of the last winnerId under the winners array is 54

@Testvoid testGPath(){    given().    when().            log().all().get("http://127.0.0.1:8000/restAssured.json").    then().            log().all()            .body("lotto.winners.winnerId[-1]",equalTo(54));}

findAll

Sometimes we need to obtain results that meet certain conditions for assertion. findAll can help us implement it. We can write filter conditions in findAll method, such as what we want to get
The value of winnerId is greater than or equal to 30 and less than 60. The specific writing method is as follows:

@Testvoid testGPath(){    given().    when().            log().all().get("http://127.0.0.1:8000/restAssured.json").    then().            log().all()            .body("lotto.winners.findAll{ winners -> winners.winnerId >= 30 && winners.winnerId < 60}.winnerId[0]",equalTo(54));}

find
The usage of find is basically the same as findAll, except that find takes the first matching by default:

@Testvoid testGPath(){    given().    when().            log().all().get("http://127.0.0.1:8000/restAssured.json").    then().            log().all()            .body("lotto.winners.find{ winners -> winners.winnerId >= 30 && winners.winnerId < 60}.winnerId",equalTo(54));    }

1.3 practical demonstration

Write the above assertion syntax together, and the actual running verification results are as follows:

** 2. XML assertion**

2.1 environmental preparation

As described above, GPath also supports assertions in XML format. Here we will use an example given by the official rest assured to demonstrate

<shopping> <category type="groceries"> <item> <name>Chocolate</name> <price>10</price> </item> <item> <name>Coffee</name> <price>20</price> </item> </category> <category type="supplies"> <item> <name>Paper</name> <price>5</price> </item> <item quantity="4"> <name>Pens</name> <price>15</price> </item> </category> <category type="present"> <item when="Aug 10"> <name>Kathryn's Birthday</name> <price>200</price> </item> </category> </shopping>

Set up a temporary service locally again:

2.2 XmlPath assertion syntax

If we want to assert the value Coffee of the second name, write it as follows:

@Testvoid testXML(){    when().            get("http://127.0.0.1:8000/restAssured.xml").    then().            log().all().            body("shopping.category[0].item[1].name",equalTo("Coffee"));}

size()
You can use the size() method to obtain the number of corresponding nodes. For example, the number of categories to be asserted here:

@Testvoid testXML(){    when().            get("http://127.0.0.1:8000/restAssured.xml").    then().            log().all()            .body("shopping.category.size()",equalTo(3));}

it.@type ,it.price

In xml interrupts, you can take advantage of it The value of attribute or node is used as the filter condition;
For example, here you need to get the name of the first item under the category of type supplies and the price is
10's trade name.

@Testvoid testXML(){     when().             get("http://127.0.0.1:8000/restAssured.xml").     then().             log().all()             .body("shopping.category.findAll{ it.@type == 'supplies' }.item[0].name",equalTo("Paper"))             .body("shopping.category.item.findAll{ it.price == 10 }.name",equalTo("Chocolate")); }

**.findAll
There is a special syntax in xml, * * findAll, you can directly ignore the previous nodes, directly match the filter criteria, and still get the commodity name name with price of 10, which is written as follows:

@Testvoid testXML(){    when().            get("http://127.0.0.1:8000/restAssured.xml").    then().            log().all()            .body("**.findAll{ it.price == 10 }.name",equalTo("Chocolate"));}

2.3 practical demonstration

Write the above assertion syntax together, and the actual running verification results are as follows:

** 3. JsonSchema assertion**

3.1 demand background

In practice, the assertion verification is performed on the interface return value. In addition to the assertion detection of common fields, the types of other fields are also detected. The reasons are as follows:

  • There are too many returned fields to ensure that each field can write assertions

  • Prevent the client from making null value verification judgment. If a return field that cannot receive null value is null due to version change or network reasons, it is likely to cause software crash

  • Some values cannot be negative

  • The decimal places are reserved. The accuracy of the decimal point has its practical value for stock trading and medical data analysis

It is obviously time-consuming to write assertions for the returned fields one by one. At this time, a template is needed to define the data types and matching conditions. Except for the key parameters, others can be asserted directly through this template. Please refer to the JsonSchema

3.2 application method

First, make some modifications to the above json example and add a winnername field of String type. You don't have to wonder why it is added here. It has its own demonstration function in the future

JsonSchema template generation

1) First, use the website of the Json schema tool https://www.jsonschema.net/ , copy the returned json string to the left of the page, and then click input shcema, which will be automatically converted to the schema json file type, and set the return value type of each sector to a default type; Regular matching can also be written in pattern

2) Click "set" to set more detailed assertion settings for return values of various types. This is the most common and practical function of schema. You can also check or assert the most detailed interval values of each type of field, such as length, value range, etc. if you are interested, you can learn more from the official website; I usually choose other assertions for the verification of important fields, such as hamcrest assertion

3) Select the copy function to save the generated schema template

Use with rest assured

**
**

4) Add maven dependency and complete support in rest assured

<dependency>    <groupId>io.rest-assured</groupId>    <artifactId>json-schema-validator</artifactId>    <version>4.0.0</version></dependency>

5) Use the matchsjsonschemainclasspath method to assert the schema of the response result

@Testvoid jsonSchemaTest(){    get("http://127.0.0.1:8000/restAssured.json").    then().log().all()            .body(matchesJsonSchemaInClasspath("jsonSchema.json"));}

Operation results:

Multi type verification - Combining schemas
  • The default value of String type is null. The back end is likely to return null when a field has no value. For example, we will return null to the winnername field we added earlier:

Run to view assertion results:

Obviously, the use case execution fails. When we define that winnername is of String type, it will assert failure if it returns null, which obviously does not meet our requirements and will lead to misjudgment of the use case execution result. At this time, we need to make winnername both of String type and null;

This requires the combining schemas method provided by jsonSchema. Combining schemas provides the following methods:

  • allOf

  • anyOf

  • oneOf

  • not

Here, we select anyof (any item can be satisfied) to complete the above example, and replace the original type with the type supported by either String or null:

Run the use case again to view the assertion results:

The use case passed perfectly, and that's it~

** 4. Recommended reading**

The syntax of assertion is more than those listed above, but most of the requirements in daily work can be met. If necessary, please refer to the official documents for research:
**
JsonPath:**
https://www.javadoc.io/doc/io.rest-assured/json-
path/latest/io/restassured/path/json/JsonPath.html
XmlPath:
https://www.javadoc.io/doc/io.rest-assured/xml-
path/latest/io/restassured/path/xml/XmlPath.html
JsonSchema:
https://json-schema.org/understanding-json-schema/

In addition, in our actual work, we often do not directly assert the response result. We may need to obtain some values in the response result, pass these values to the next interface or compare and assert with the responses of other interfaces, which involves the assertion of the response
The acquisition and processing of response are, which will be discussed in subsequent articles.

**
Come to Hogwarts test and development society to learn more advanced technologies of software testing and test development. The knowledge points include web automated testing, app automated testing, interface automated testing, test framework, performance testing, security testing, continuous integration / continuous delivery / DevOps, test left, test right, precision testing, test platform development, test management, etc, The course technology covers bash, pytest, junit, selenium, appium, postman, requests, httprunner, jmeter, jenkins, docker, k8s, elk, sonarqube, Jacobo, JVM sandbox and other related technologies, so as to comprehensively improve the technical strength of test and development engineers
QQ communication group: 484590337
The official account TestingStudio
Click for more information

**2021 holiday charging,
Come to Hogwarts test and development society to learn more advanced technologies of software testing and test development. The knowledge points include web automated testing, app automated testing, interface automated testing, test framework, performance testing, security testing, continuous integration / continuous delivery / DevOps, test left, test right, precision testing, test platform development, test management, etc, The course technology covers bash, pytest, junit, selenium, appium, postman, requests, httprunner, jmeter, jenkins, docker, k8s, elk, sonarqube, Jacobo, JVM sandbox and other related technologies, so as to comprehensively improve the technical strength of test and development engineers
QQ communication group: 484590337
The official account TestingStudio
Click for more information