Reprinted: Variables and built-in scripts in postman implement interface preprocessing and response assertions

Variables and built-in scripts in postman implement interface preprocessing and response assertions

Fun with Postman: Advanced

In the last post Chat "Playing with Postman: Basics" , we introduced the main functions of the Postman tool and some basic usage. In fact, Postman is currently the most widely used interface testing tool. In addition to providing a well-interacted UI interface and completing basic http protocol authentication, header, body settings, and basic functions such as request submission and response analysis, it also provides Has a very rich test assistance capabilities. In this article, we will give you a detailed introduction to Postman's advanced scripting features.

Postman's variables

In interface testing tools, variables are of great significance to the reuse and flexible matching of interface messages. As a professional interface testing tool, the support for variables is a must.

And Postman provides a wealth of variable support. In Postman, five variable types with different scopes are defined, which is more flexible and targeted in the use and management of variables. The following figure shows the official scope of different types of variables.

image

The scope gradually becomes smaller from the outside to the inside, and the effective priority is higher, that is, when the same variable name exists, the variable of the inner variable type will take priority. Below we combine examples to illustrate the scope of these variable types:

Global variables

Global variables are global variables, and they are the variable type with the largest scope. After setting the Global variable, it can take effect in all the places where the variable can be used in the Postman tool.

Let's take a look at the setting of the Global variable in the Postman tool. Open the environment management interface in the upper right corner of the tool: image

Select Global variable management: image

Add the Global variable: image

In this example, we set a Global variable name with a value of 1. In Postman, double curly braces are used to denote variables, as in the form  { { variable }}. Take the Github API as an example. For example, we get the user information whose user name is the value of the variable name.

https://api.github.com/users/{ {name}}

After entering the double curly braces in the URL, it will automatically think of the variable type we need.

image

After sending the request, check the Postman response area, you can see that we have obtained the user information with username 1.

Collection and collection variables

Let's look at another variable type Collection variable. First understand the concept of Collection. Collection is a collection unit for organizing interfaces in Postman, and Collection is also a basic unit for configuration storage in Postman. We can think of Collection as the concept of a set of test cases in software testing.

Collection variables are the types of variables whose scope is on the Collection. Such variables will only take effect on the Collection where the variable is set. Setting method: select Edit Collection image

Add a Collection variable to the variable page. In this example, we add a variable named name to the Github Collection. image

Save the user interface in the above example to the Github Collection (we can create another sub-directory under the Collection. Note that the directory does not support setting directory-level variables. The interface of the Collection variable in the sub-directory will still take effect. ), let's submit this interface again. image

At this point, you can see that the Collection variable we set has taken effect, and the user information with name 2 is obtained. Note that at this time we also set a Global variable with a name of 1. You can see that the priority of the Collection variable is higher than that of the Global variable.

Environment and environment variables

Environment is a very useful concept in Postman. Students who have done software testing know that we will be exposed to different software environments in actual work. Corresponding to different operating scenarios of our tested system. For example, general Internet companies will have the following different environments in R&D:

  • Development environment
  • Integrated environment (joint debugging environment)
  • System test environment
  • Pilot production environment
  • Production Environment
  • Performance test environment
  • Safe testing environment

Different environments often have big differences in access methods, network topologies, access rights, and hardware configurations. The concept of Environment is introduced in Postman, and a group of environment configurations are managed through Environment variables, which is convenient for us to switch between different environments.

In the environment management interface, you can add an environment and related variables corresponding to the environment. In this example, we add a GitChat environment and set an environment variable with name = 3. image

After setting up the environment, we select the corresponding GitChat environment on the user interface interface just now, and then resubmit the request. You can see that the environment variable has taken effect, and the user information whose name is 3 has been obtained. It can also be seen that the priority of the environment variable is higher than that of Collection. image

data variable

Another variable type in Postman is the data variable. The data variable can only be used in Postman Runner, that is, it will take effect when the Runner is running. The data variable can provide multiple sets of test data for interface testing, providing an interface for Postman Batch data verification capability. To use the data variable, open Postman Runner, as shown in the figure below, select the data variable definition file to load the data variable file.

image

The data variable supports json or txt/csv data format, the json definition format is as follows,

The format of txt/csv is as follows:

On the runner interface, you can view the values ​​of variables loaded in different iterations at runtime through preview, as follows:

image

In this example, clicking Run variables will execute 3 different iterations. Viewing the run log through the Postman Console, you can see that the corresponding variable values ​​defined in the data variable are used each time. Similarly, although we choose environment, we can see that the data variable has a higher priority when the runner is running.

image

Local variables

Local variables are not clearly defined in the official Postman documentation. Generally, it can be understood as the JS variable supported in the Postman script. Its scope will only take effect in the script. At this time, the { {variable}} referenced in the Postman interface will not get the value of the Local variable.

The variable name directly quoted in the script will be the Local variable, and other data types will be obtained through the value statement corresponding to Postman.

For example, we define and execute the following script in Pre-Request: image

Check the results in the Console as follows, you can clearly see the current values ​​of different variables in the pre-execution script each time it is executed. image

Through the above examples, we can see that Postman supports a wealth of variable types for different interface scopes, so that we can be more flexible when applying variable functions.

Postman scripts and their execution order

In addition to supporting rich variable functions, Postman also supports powerful scripting functions. When performing interface tests, testers can dynamically customize the interface test logic through scripts, and combine variables to achieve some complex scenarios.

The script function of Postman is based on the Node.js language. The mature syntax and rich extension library of Node.js provide Postman with great flexibility and powerful expansion capabilities.

In Postman, the test script can be executed before the interface is sent and after the response is received, corresponding to Pre-request Script and Test Script respectively, as shown in the following figure: image

For example, the example when we introduced variables in the previous article is actually a pre-request script image

In addition to the interface itself, you can set pre-request and Test Script. When we edit Collection and Folder under Collection, we can see that both Collection and Folder also support setting pre-request and test scripts. What is the execution priority or order of these types of scripts? The following figure shows the call execution sequence of these scripts at different locations: image

Students who are familiar with test frameworks such as TestNG or Junit should know that these test frameworks also have similar runtime concepts, namely Setup and teardown methods, and there are also levels such as case, class, and suite. However, these methods at different levels appear in pairs, that is, the setup and teardown of the case will be executed before and after the case is executed. The execution order of Postman's Script is slightly different from this one. It is arranged in a hierarchical order, rather than appearing in pairs. Please refer to the picture to understand the difference.

You can also verify the execution order yourself, and define relevant scripts in the requests under Collection, folder, and folder, such as: image

Execute, check the console output: It  image can be seen that Postman's execution order of different scripts is the same as the above.

Postman script-PreRequest

The Pre-request script, as the name implies, actually performs some pre-processing actions before the interface message is sent, similar to the Setup method in test frameworks such as Junit or TestNG. Using Pre-Script scripts, we can complete some actions that require dynamic processing before sending interface requests, such as adjusting the value of a variable, or performing some special processing on some dynamic parameters.

Let's take an example in the GitHub API to see the main role of Pre-Script scripts. (For some specific instructions about the GitHub API, you can first read my introduction in the previous Chat  "Playing with Postman: Basics" )

A frequently used interface in the GitHub API is the query interface.

According to the definition on the official GitHub API website, the interface for querying repositories is defined as follows:

GET /search/repositories

image

The parameter q is the main query parameter. For specific definitions, please refer to https://help.github.com/articles/searching-for-repositories/

For example, we want to query the repository information that was created after the specified date 2018-11-11 and contains the keyword automation. image It can be seen that there are more than 7,000 such repos on GitHub.

In this example, because the query condition contains a date parameter, and in the actual test work scenario, many times we hope that the date is dynamically generated, such as taking one year ago as the query parameter value according to the current date, then we need to adjust the parameter Do some preprocessing, and this is where Pre-Script comes in.

At this time, we can first set an environment variable created, and then dynamically preprocess the date in the pre-script script to accomplish the purpose of dynamic date setting.

Execute in Postman as shown in the figure to obtain the information of repositories created one year from the current date. image

In Pre-Script, preprocessing is mainly around Postman's variables, so some encapsulation methods of Postman's variable fields are mainly used.

  • pm.globals.has(variableName:String)

    Whether there is a global variable

  • pm.globals.get(variableName:String)

    Get global variables

  • pm.globals.set(variableName:String, variableValue:String)

    Set global variables

  • pm.globals.unset(variableName:String)

    Cancel the current global variable setting

  • pm.globals.clear()

    Clear global variables

  • pm.environment.has(variableName:String)

    Whether there is an environment variable

  • pm.environment.get(variableName:String)

    Get environment variables

  • pm.environment.set(variableName:String, variableValue:String)

    Set environment variables

  • pm.environment.unset(variableName:String)

    Cancel the current environment variable settings

  • pm.environment.clear()

    Clear environment variables

  • pm.variables.get(variableName:String)

    Get the variable based on the variable name

  • pm.sendRequest()

    send request

Postman script-Test script

Postman’s Test script is another commendable feature of Postman. In the Test script, Postman encapsulates a lot of rich verification logic, combined with the flexibility of the language of the JS script, to give testers judgement, checksums on the interface Response processing brings great convenience.

Below we focus on some main verification methods encapsulated in the Test script.

Determine the interface response status code

The verification of the interface response status code is a common method for interface testing and verification. For a detailed description of the status code, please refer to my previous Chat   "Playing with Postman: Basics"  . Let's look at a code for interface verification code verification in Postman:

Or you can use the expect method of the third-party verification library chaijs for verification. Chaijs has encapsulated the commonly used verification methods in accordance with the behavior-driven development (BDD) description method, which makes it much easier to write the verification code.

Or we can directly use Postman to judge the encapsulation method of the return status code

Common return status verification methods are directly encapsulated in Postman:

  • pm.response.to.be.info

    Check 1XX information status code

  • pm.response.to.be.success

    Verify 2XX success status code

  • pm.response.to.be.redirection

    Verify 3XX redirect status code

  • pm.response.to.be.clientError

    Verify 4XX client error status code

  • pm.response.to.be.serverError

    Verify 5XX server error status code

  • pm.response.to.be.error

    Verify 4XX or 5XX error status code

  • pm.response.to.be.ok

    Check 200 for OK return

  • pm.response.to.be.accepted

    Check the acceptance and return of status code 202

  • pm.response.to.be.badRequest

    The request message of the verification status code 400 is wrong

  • pm.response.to.be.unauthorized

    Verify the authentication error of status code 401

  • pm.response.to.be.forbidden

    Access restricted to verify status code 403

  • pm.response.to.be.notFound

    Check that the resource with status code 404 has no errors

  • pm.response.to.be.rateLimited

    Check the access frequency limit error of status code 429

Check response time

In addition to the verification of the return code, a response indicator that we will often verify is the response time. Postman's verification of response time is also very simple

Verify message content

The verification of the content returned by the interface is a necessary means for us to judge the correctness of the business logic. Message header or message body content of the response that we can  pm.response.header or  pm.response.text ,  pm.response.jsonacquired. In the corresponding verification code, we can further judge the correctness of the response based on the obtained content.

Perform the above verification in Postman, you can see the verification result in the Test Results of Response image

Postman script-interface association

In interface testing, a situation that often occurs is that we need to obtain certain values ​​from the response of another interface as the input of the current test interface to use. Combined with Postman's Pre-Script and Test script and variable functions, we can easily complete the scenes of content acquisition and parameter transfer.

Take the following scenario as an example:

Obtain the creation time of the repo from the interface information of the Junit5 repo, and then query the information of all repo created after this time that contains the word Junit5 to determine whether the number of repo exceeds 1000.

method one

  1. Set an environment variable created;
  2. Get the creation time of the Junit5 repo in the Test script of GetRepo to get the repo interface;
  3. Assign the obtained creation time to the environment variable created in the Test script;
  4. Use the environment variable created in the query repo interface;
  5. Add a check code to determine the returned quantity in the query repo interface;
  6. These two interfaces are executed in sequence through the Runner executor to complete the associated execution.

As shown in the figure: image

image

Execute the result in the Runner executor image

Method Two

In method one, we use environment variables to pass parameters. This method needs to rely on the execution order of the interface of the runner executor to ensure that the GetRepo interface is executed before the SearchRepo interface.

We can also use the request sending method provided by Postman pm.sendRequestto directly send  the pre-request and obtain the parameters in the pre-Script script of SearchRepo.

At this time, you don’t need to use the runner executor and directly execute the SearchRepo interface to get the same result. image

Postman script-code reuse

As an interface testing tool rather than a professional code editing IDE, Postman does not provide functions such as script reuse, code slices, and module definitions. But with the help of Postman's powerful variables and good support of js syntax, we can achieve code reuse flexibly.

We can save some commonly used code snippets into global variables, and call this global variable directly when we need to use them.

For example, the above check code for judging whether the number of returned repo exceeds 1000:

We set it in the global variable checkRepoCount, and replace it with the following code where it needs to be called:

As shown in Postman: image

Postman script-a complex scenario case combined with third-party libraries

In order to facilitate the writing of interface scripts, Postman has built-in support for a wealth of third-party libraries, and a detailed list is listed in the official documentation. image

In addition to the aforementioned BDD verification library chai, let's combine the third-party time processing library moment to complete a relatively complex scenario case implementation:

The related interfaces are as follows:

  • Query interface, query keyword junit5, number of stars>1, within 6 months of creation time, query in descending order of number of stars

/search/repositories?q=junit5+stars:>1+created:>{ {created}}&sort=stars

  • Query whether a repo has been stared

GET /user/starred/:owner/:repo

204 has been returned to star, 404 is returned if not

  • Perform star repo operation

PUT /user/starred/:owner/:repo

Return 204 if successful

Introducing the event processing library moment into the Pre-Script script of the query repo interface, you can see that the moment library is more flexible in processing dates than the date method of js itself. The subtract method can be used to easily obtain the date half a year ago without consideration. The code is as follows:

Write the checksum follow-up logic code in the Test script of the query repo interface:

The execution effect in Postman is as follows:

image

Conclusion and preview

The above is an introduction to the advanced use of Postman scripts. To summarize briefly:

  • Postman provides 5 different variable types, which correspond to different scopes. Flexible use of these variables can help us realize scenarios such as dynamic matching, parameter transfer, and code reuse.

  • Postman provides two script sandboxes on the three layers of Collection, Folder, and the interface itself: Pre-Script and Test. Pre-Script is executed before the interface request, and Test is executed after the interface response. Note the different execution order on the three-level objects.

  • Postman script is based on Node.js, with built-in support for rich third-party libraries, and Postman itself also encapsulates many upper-level methods, you can refer to  Postman official sandbox method reference

Therefore, Postman can flexibly help us to better complete some complex scenarios in interface testing through rich variables and powerful js script support.

Although the current two Chats mainly introduce the main functions and usage skills of Postman in manual interface testing, Postman can actually be easily applied in automated testing. Welcome everyone to continue to pay attention to the next Chat "Playing with Postman: Automation" ", we will learn together:

  • Detailed explanation of Postman's batch execution tool Runner
  • Postman implements the flow control of the interface
  • Postman's command line automation tool NewMan detailed
  • Combined with the continuous integration tool Jenkins to realize the automatic scheduling and execution of Postman interface scripts

Guess you like

Origin blog.csdn.net/weixin_40734030/article/details/114090244