Using Python as interface test request

1. What are requests

1.1 introduction to requests

Requests stands for requests. In python, it is a library for HTTP services

1.2 installation of requests Library

pip3 inshtall requests

1.3 handling get requests with Python code

import requests

api=requests.get(
 url='http://**.**.***.***: *****/login/auth/',
 params={"name":"jiachao"})
#Protocol status code
print('Protocol status code:',api.status_code) #Get request address
print(api.url) #Response data
print('Return string:',api.text)
print('Returns the contents of decimal:',api.content)
print('The dictionary data type is returned:',api.json())
#Response header
print('Response header:',api.headers)

In this, we need to note that the response data is generally API Text, if the response data is in JSON format, use API json()

1.4 telephone number inquiry practice

api=requests.get(
 url='http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo',
 params={"mobileCode":"1**********","userID":""})
print(api.url)
print(api.status_code)
print(api.text)
print(api.headers)

It should be noted that when making a get request, if the request data needs to fill in me, we need to enter params in parentheses and fill in the dictionary format (Key & value)

1.5 processing JSON data format with python code

import json
import requests
api=requests.post(
 url='http://**.**.***.***:****/login/auth/',
 json={"username":"1**********","password":"a*****8"},
 headers={"content-type":"application/json"})
print(json.dumps(api.json(),indent=True,ensure_ascii=False))

When outputting the results, we analyze the code

Parameter introduction

json.dumps is serialization

api.json is written as json

indent=true is used for initialization

ensure_ascii=False , no asker code coding (used to deal with Chinese random codes)

1.5.1 difference between data and json

When to use json?

JSON parameters are used when requesting JSON parameters

When the request parameter is json, but the parameter of data is used, the request parameter needs to be serialized

When to use data?

Use data when the request parameter is a form

When the request parameters are in json format, the request parameters should be serialized

1.6 processing form data format with python code

api=requests.post(
 url='http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo',
 data={"mobileCode":"1**********","userID":""},
 headers={"content-type":"application/x-www-form-urlencoded"})
print(api.text)

The difference between handling the form format and handling the json request is that when we write conetnt type, we just need to write the form data type

1.7 practical analysis of complex form format

api=requests.post(
 url='https://www.lagou.com/jobs/v2/positionAjax.json',
 data= {"data":"7Xx8%2BncjEMSVaVAgnRvUNTUE96%2BZQ2vPzFNSpQ88YRMH6wPSJ8i6Cprv9zK8LdkaMCryRC4KsX
IeYziVgSmqOpzWRJLTICaDRADfVKega8j0HtL4PbSKAbU2Bu%2BELgYZ9P0eVN9ha0eAJYfBfoMUbuAmQzuFErA
7fLqd2E56hwfw5%2BNRba2bvdD0Dh3cTl%2FIM4NkMRF%2FGcXEvDJWAVWGYKUh%2FSEpM0WJNhhSM0dXB6%2BR
51Ln0ngfo2LEYJKwjMJh"},
 headers={
 "content-type":"application/x-www-form-urlencoded; charset=UTF-8",
 "user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
 "cookie":"according to network obtain",
 "referer":"according to network obtain"})
print(api.status_code)
print(json.dumps(api.json(),indent=True,ensure_ascii=False))

The above individuals have written good code

1.7.1 code analysis

The test case is dragnet

In the above code, we can see that the form format is more complex than that in the past. In fact, it is nothing more than a few points to sum up

1. url address:

2. Request data: because we have obtained the request data through the network this time, we can directly copy and paste it

3. Request header: the request header that has been used in the singing operation. The four request headers that must be carried in the industry are conetnt type, user agent, cookie and referer. You can add them in turn

Then we output the protocol status code and response data of the request url

1.8 processing dynamic parameters with python

Because we have dynamic parameters when processing session requests

Imagine a scenario where we input the user name and password to the server. At this time, the server returns a random sessionID to us. Then we should deal with it as follows

def login():
 api=requests.post(
 url='http://**.**.***.***:****/login/auth/',
 json={"username":"13********","password":"*****8"},
 headers={"content-type":"application/json"})
 return api.json()['token']
def index():
 api=requests.get(
 url='http://47.95.142.233:8000/interface/index',
 headers={"Authorization":"JWT {token}".format(token=login())})
 print(api.text)
 assert api.json()['count']['api']==4

1.8.1 code analysis

1. We define two functions , login and index , where login is the login page and index is the page returned after successful login

2. After we enter the corresponding user name and password, click return api. JSON ["token"] to return the token to the login function to be called

3. When we write the index function, we need to write "authorization" in the request header: "JWT {token}" Format (token = login()) to call the value of the global variable token, so as to obtain the response data returned after successful login

. 4. At the end, we verify whether the returned data is correct according to the assertion assert r.json()["count"]["api"]==4 generated by python source. If it is correct, it can prove that we have obtained the returned response data

1.9 handling cookie requests with python code

In the request header, you need to bring the set cookie value returned in the response header of the server. The keyword used is cookies

1.9.1 actual case code

import requests

def login():
    api=requests.post(url="https://home.51cto.com/index?reback=https%3A%2F%2Fedu.51cto.com%2Fcenter%2Fuser%2Findex%2Flogin-success%3Fsign%3D0b8cAQcICQgAUwNSB1cKAwIKXFJUV1UAC1NTAlBcQRVIFwseGF1dTR5WAgFDXRxSDF8XV1IPFwNBHVRfEUZGBBcRQlRFF15dRE5AFkJWSxwAXU1GRARTBAtR%26client%3Dweb&iframe=0&is_go_to_user_set_mobile=1",
                      data={"_csrf":"b0tpNzY0NVIeAyNZG05dZCooP297eEMUBihcTw59QgUkezpPBV9GNQ==",
                            "LoginForm[username]":"1******",
                            "LoginForm[password]":"a******",
                            "show_qr":"0"},
                      headers={"content-Type":"application/x-www-form-urlencoded",
                               "cookie":"acw_tc=2760826216425816925208847e7858ddd405cdc867fa071cec17c576a4cb7a; PHPSESSID=1tm0ep6qmvavbtvc02edps63u3; _csrf=8bd4e0bb9d580c84ad72c0878787c487e915a6afdf434b9ab2121637ac6f6025a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22qHJn-zh6EcVXMLvFic5x8IwWK0Sx3ksg%22%3B%7D; _uab_collina=164258160896132940103325; _ourplusFirstTime=122-1-19-16-40-8; _ourplusReturnCount=1; _ourplusReturnTime=122-1-19-16-40-8; www51cto=C9BA92B0E626A5F0007CD254829BC978aiYz; sajssdk_2015_cross_new_user=1; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2217e717e4aec9-03a8b5f43617fb-f791b31-1440000-17e717e4aed998%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%2217e717e4aec9-03a8b5f43617fb-f791b31-1440000-17e717e4aed998%22%7D; login_from=edu.51cto.com; reg_from=edu.51cto.com; Hm_lvt_844390da7774b6a92b34d40f8e16f5ac=1642581609; Hm_lpvt_844390da7774b6a92b34d40f8e16f5ac=1642581609",
                               "referer":"https://home.51cto.com/index?reback=https%3A%2F%2Fedu.51cto.com%2Fcenter%2Fuser%2Findex%2Flogin-success%3Fsign%3D0b8cAQcICQgAUwNSB1cKAwIKXFJUV1UAC1NTAlBcQRVIFwseGF1dTR5WAgFDXRxSDF8XV1IPFwNBHVRfEUZGBBcRQlRFF15dRE5AFkJWSxwAXU1GRARTBAtR%26client%3Dweb&iframe=0&is_go_to_user_set_mobile=1",
                               "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
                               "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"})
    print(api.text)
    print(api.status_code)
    print(api.cookies)
    return api.cookies

def profile():
    api=requests.get(url="https://edu.51cto.com/center/user/info/get-user-info",
                     cookies=login())
    print(api.status_code)
    print(api.text)

profile()

Because the code is cumbersome, the logical relationship is shown in the figure below

 

1.10 meaning of timeout parameter of Python processing interface test

Sometimes the server responds to data very slowly and sometimes very fast, so you need to add timeout at this time

There is also a network request with requests exceptions. When the connecttimeout error occurs, you can add a timeout

1.10.1 code details demonstration

import requests
from requests.auth import HTTPBasicAuth


api=requests.get(url="http://***.***.***.*/v1/api/books",
                 auth=HTTPBasicAuth(username="ad***n",password="a****n"),
                 timeout=180)
print(api.status_code)
print(json.dumps(api.json(),indent=True,ensure_ascii=False))

In fact, for the UI automation test we learned before, timeout can be drawn with invisible waiting===

That is to limit the maximum waiting time. If the response data is not obtained after this time (seconds), a timeout will pop up and an error will be reported

1.11 auth parameter meaning of Python processing interface test

If the protocol status code is 403 when we conduct the test, it is proved that we have permission but access is prohibited. It can be understood that we need the user name and password to log in successfully before we can access

At this time, the HTTPBasicAuth method in the requests library will be used

The specific application methods are as follows

import requests
from requests.auth import HTTPBasicAuth
api=requests.get(
 url='http://1**.**.***.***: ****/v1/api/books',
 auth=HTTPBasicAuth(username="admin",password='admin'))
print(api.status_code)
print(api.json())

We define the user name and password through the auth parameter, so that we can obtain permission to access the content

1.12 meaning of verify parameter of pyhon processing interface test

In a realistic working scene

When our code has no problem, but the request is to return ssl and 403, so long means that we need to set the verify parameter

If an error is returned: requests exceptions. Sslerror , at this time, we need to bring the verify parameter

The specific application methods are as follows

api=requests.get(
 url='https://***.**.***.***: ****/v1/api/books',
 auth=HTTPBasicAuth(username="admin",password='admin'),
 timeout=180,verify=False)
print(api.status_code)
print(api.json())

We need to add the parameter verify=False

Added by saf on Thu, 20 Jan 2022 06:01:30 +0200