Postman+newman of interface Automation

Source: Internet
Author: User
Tags postman interceptor

Brief introduction

Postman makes it easy for us to call the API tools, through Postman and Newman we can also run the API in bulk to achieve the purpose of API automation testing.

Postman Installation

The Window system needs to install the Chrome browser first, then find the Postman plugin in the store and click Install directly: https://chrome.google.com/webstore/detail/postman/ Fhbjgbiflinjbdggehcddcbncdddomop?hl=cn

Testing the Get Type API to search the book API for a watercress example

The method for this interface is get,postman default to get, enter the tested interface in the URL bar

GET request


In the interface documentation, one of Q and tag is required, so configure the parameters here, click the params to the right of the URL, and enter the parameters

Clicking the Send button sends the request, below you can see the returned response, the status code of the response, and the response time

Response can also be viewed in different ways, and you can also see cookies,headers information

Each time with a different parameter or setting, the left-hand side of the history will help us record an interface test, so that the next recall

Test Post Type API

Take the interface of postman as an example
Select the method for the request is post and enter the interface address, because the POST request is mostly in JSON form, so you can open the Body option, and choose JSON (Application/json) Form, enter the request JSON, and the rest of the operation is the same as the Get interface.

Post

Setting of variables

The APIs that are written often need to be executed in multiple environments, and postman provides two types of variables: environment variables and global variables, which are a good way to solve this problem.
Environment variables are valid only for the environment you choose, and global variables are tested for all environments.

Environment variables

The API may need to run in a dial-up environment, so the server address requested by the API cannot be written to death, it is configurable, and there are several ways to create environment variables.

    1. Manually pre-Create environment variables

    1. Code automatically creates environment variables
      The auto-new environment variable can be created in two cases, but the same way is created using the method provided by postman:
      postman.setEnvironmentVariable("key", "value");

      1. Create before a request is initiated:
        Add code to the Pre-request script tag:

      2. Created after a request is initiated:
        Add the following in the Tests tab

Global variables

All variables are similar to the creation of environment variables, or they can be created manually or by code.

    1. Pre-created by hand

    1. Create from Code
      2.1 Create before request is initiated
      Add code to the Pre-request script tag:

      postman.setGlobalVariable("key", "value");

      2.2 Created after the request was initiated
      Add the following in the Tests tab:

      postman.setGlobalVariable("key", "value");
      A reference to a variable

      Add {{variable name}} where needed to

Random number

PostMan provides three random numbers in addition to environment variables and global variables.
{{$guid}}
: Add a V4 style GUID

{{$timestamp}}
: The current timestamp is accurate to the second

{{$RANDOMINT}}
: Add a random integer between 0 and 1000

Test

Postman can be inside the tests, with the script to test the interface, click the tests tag can see the right side of a snippets bar, which is the postman built-in test script, auxiliary interface testing.

Select one of the scripts, modify the parameters, click Send Again, then response's tests appeared a 1/1, instructions to perform a test and pass the test, Green pass instructions to verify through

Red fail means the test does not pass, an interface can write multiple scripts to test multiple times


Built-in script description:

1. Clear a global variable clear a global variable corresponding script: Postman.clearglobalvariable ("Variable_key"); Parameter: The key of the variable to be cleared2. Clear an environment variable clear an environment variable corresponding script: Postman.clearenvironmentvariable ("Variable_key"); Parameters: Key for environment variables to be cleared3.response contains content Response body:contains string corresponding script: tests["Body matches string"] =responsebody.has ("String_you_want_to_search"); Parameters: expected content4. Convert XML format Response to son format Response body:convert XML body to aJsonThe Object corresponds to the script:var jsonobject = Xml2json (responsebody); Parameters: (default does not need to set parameters, response for interface) need to convert XML5.response equals expected content Response Body:is equal to a string counterpart script: tests["Body is correct"] = Responsebody = = ="Response_body_string"; Parameters: Expected response6.json parse the value of key to verify Response body:JSON value Check counterpart script: tests["Args key contains argument passed as URL parameter"] =' Test 'In Responsejson.args parameter: Test replaces the measured value, args replaces the measured key7. Check if the header information for Response has been divination of Word segment Response Headers:content-type header Check script: tests["Content-type is present"] = Postman.getresponseheader ("Content-type"); Parameters: Expected Header8. Response time Judgment Response-is-less than200ms corresponding script: tests["Response time is less than 200ms"] = ResponseTime <200; Parameters: Response Time9. Setting Global variablesSet an global variable counterpart script: Postman.setglobalvariable ("Variable_key","Variable_value"); Parameters: Key values for global variables10. Setting Environment variablesSet an environment variable corresponding script: Postman.setenvironmentvariable ("Variable_key","Variable_value"); Parameters: Key values for environment variables11. Determine status code state Code:code is200 corresponding script: tests["Status code is $"] = responsecode.code! =400; Parameters: Status Code12. Check if the code name contains the content Status code:code name has string corresponding script: tests["Status code name has string"] = ResponseCode.name.has ("Created"); Parameter: Expected code name contains string13. Successful POST requests Status code:successful POST request corresponding script: tests["Successful POST request"] = Responsecode.code = = =201 | | Responsecode.code = = =202;14. Micro Validator Use Tiny ValidatorForJSON data corresponding script:var schema = {         "items": {    & nbsp    "type":  "boolean"             }        };        var data1 = [true, false";        var data2 = [true, 123";        console.log (tv4.error);        tests[ "Valid Data1"] = Tv4.validate (data1, schema);        tests[ "Valid Data2"] = Tv4.validate (data2, schema);     & nbsp   Parameters: You can modify the key value pairs in items to correspond to the parameters of the validation json           
Using runner features and external data

The Postman tool comes with the runner feature for running scripts in batches. You can also use an external CSV or JSON file to specify the data at run time.
For example, now two new external data is created, the first one is saved as a. json file, and the second is saved as a. csv file.


Create a new GET request API, which is managed in a separate folder. The {{host}} in the interface request is used to get data from the two new folders that were created in the previous step, and the name in {{}} corresponds to the key value of the JSON file, corresponding to the first row value in the CSV file.


Click the Runner button to open the Runner interface:


In the newly opened window, choose the name of the folder you want to create, select the environment you want to run, run the number of times and select the newly created external JSON or CSV file in the data file, choose the file type, click Start Test, and start reading the data from the external file to run.

Postman Interceptor

Interceptor can get the request directly from the browser and save it in Postman's history. This plugin can significantly shorten the time of the API configuration, as well as interceptor a feature that allows postman and chrome to share Chrome's cookies.

Installing Interceptor

Interceptor is also a plugin for chrome, so you can also find the plugin from the Chrome Web Store: https://chrome.google.com/webstore/detail/postman-interceptor/ AICMKGPGAKDDGNAPHHHPLIIFPCFHICFO/SUPPORT?HL=CN, click Install directly. The logo will be found in the Chrome plugin after the installation is complete.

Using Interceptor

Turn on the Interceptor plugin and set the site request you want to crawl

Also open interceptor on the postman

At this time in the Chrome browser to visit some Baidu related domain name will automatically be postman crawl, and in Postman's history Show

Newman

Official Help document Address: Https://www.npmjs.com/package/newman

Newman Installation

Well, it needs to be installed, because it's not a music player! Newman is intended for postman and is designed to run scripts written by postman. Newman installation Steps:

    1. Need to install Nodejs and configure the environment

    2. Open the console, run: NPM install-g Newman

Paste_image.png

    1. Verify the installation is successful, run: Newman--version

Newman Execute Script

Newman made a big change after the 3 release, but running the commands is becoming more and more simple as follows:

<collection-file-source> [options]

Run behind the JSON file or URL that you want to execute (both JSON and URL are generated by postman export), followed by parameters such as environment variables, test reports, interface request timeouts, and so on. Finally, two complete examples are given as a reference:
Example 1, run the postman exported Test1.json file by Newman and generate a variety of test reports (Json,junit xml,html):

newman run c:\test1.json --reporters cli,html,json,junit --reporter-json-export jsonOut.json --reporter-junit-export xmlOut.xml --reporter-html-export htmlOut.html

Example 2, run all the APIs in HTTPS://WWW.GETPOSTMAN.COM/COLLECTIONS/CB0CEA0AF1467C8008FB (postman generated), and uses Env.json as the environment variable and Globals.json as the global variable, and uses the external data.csv as external data, and finally sets the interface request time-out to 5 s.

newman run https://www.getpostman.com/collections/cb0cea0af1467c8008fb --environment env.json --iteration-data data.csv --globals globals.json --timeout-request 5000
Jenkins combined

Usually do interface automation, can not avoid the final build through Jenkins. Since Newman provides a way to execute console commands, it's much easier to build it like Jenkins.
Step One: Install Newman on the Jenkins machine
Step two: Build the Jenkins environment and create a free-style job
Step Three: Build the Select Execute Windows Batch command and enter the Newman Run command

Step four: Because the build in the above command generates JUNIT XML reports, you can use the Publish JUnit test Result report plug-in to generate test reports after the build.

?

Postman+newman of interface Automation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.