In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how python+requests automates interfaces. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Interface Automation Test (python+requests) using python and third Party Library requests
A brief introduction to the third Party Library requests
Requests is a HTTP library written in Python language, based on urllib and using Apache2 Licensed open source protocol. It is more convenient than urllib, can save us a lot of work, and fully meet the needs of HTTP testing. More importantly, it supports Python3.
Approximate steps
Request is a third-party library, which needs to be installed manually: CMD can be installed-command: pip install requests
Import the requests third-party library first in pycharm, code-import requests
Send request-http.get request: requests.get ('https://api.github.com/events')
Send request-http.post request: requests.post ('http://httpbin.org/post', data = {' key':'value'})
Build URL parameters, etc.
Validate the returned parameters with Python.
Just run it (if the request fails, you can grab the packet to see if the sending parameters are incorrect)
Detailed introduction
The following mainly introduces two commonly used http requests: get and post, and delete
The following figure shows the use case for writing a code test.
Specific code:
Step 1: import requests directly after installation
# Import requests
Import requests
Step 2: write code to build the request using Python+requests
# Login API-post request
It should be noted here that in addition to returning the contents of the interface, you also need to return cookies, because the later operation needs to use the login ID.
Def Login (user,passw):
Payload = {
'username': test
'password': 123456
}
The # data parameter is used to construct the message body.
Response = requests.post ("http://localhost/XXXX",
Data=payload)
# get the result and return it to the caller
RetDict = response.json ()
# print the results in the console
Print (retDict)
# return result, which needs to be used when calling
Return retDict, response.cookies
# add course API-post request
It should be noted here that the request parameter needs to be added with cookies, because the login ID is needed for the later operation.
Def add_course (action,name,desc,dis,sessionid):
Re= {'action':action
'data':'''
{
"name": "% s"
"desc": "% s"
"display_idx": "% s"
}
''% (name,desc,dis)
}
Rs=requests.post ("http://localhost/XXXX",data=re,cookies={'sessionid': sessionid})
Re=rs.json ()
Print (re)
Return re
# list course APIs-get request
Def list_course (sessionid):
Parm= {
'action': 'list_course'
'pagenum':1
'pagesize':20
}
# he = {"Content-Type": "application/json"}
Rs=requests.get ("http://localhost/XXXX",params=parm,cookies={'sessionid': sessionid})
Liechu=rs.json ()
Print (liechu)
Return liechu
# Delete the course API-delete request
Def delete_course (courseid,sessionid):
Payload = {
'action': 'delete_course'
'id': f'{courseid}'
}
Response = requests.delete ("http://localhost/XXXX/",
Data=payload
Cookies= {'sessionid': sessionid})
R = response.json ()
Pprint.pprint (r)
Return r Wuxi Gynecology Hospital http://www.bhnfk.com
Step 3: use Python to verify the parameters returned by requests
# because this code is written in another Python file. So you need to import the above Python file before you can call the functions in it.
From jiakouzudonghua import aba
# Import random number functions
Import random
# use the written login interface to log in
# loginRet saves the parameter returned by the login API whether the login is successful, and cookies saves the cookie returned after a successful login
LoginRet,cookies = aba.Login ('auto','sdfsdfsdf')
# use if to determine whether the login is successful, and you can use assert verification directly
If loginRet ["retcode"] = = 0:
Print ('login successful')
Else:
Print ('login failed')
# record sessionid
Sessionid = cookies ['sessionid']
# here the course uses random numbers to ensure that each run will not create a course with the same name
Classname= ('course' + str (random.randint (099999999999)
# list the courses for the first time in preparation for later comparison
CoureListBefore = list_course (sessionid) ['retlist']
# add a course and use assert to verify it. If you make a mistake, you will not go back to it. If you make an error, you will return an error message.
RetDict = add_course ('classname',' php language', '2century journal sessionid)
Assert retDict ['retcode'] = = 0
# you can also use if for verification
# if retDict ['retcode'] = = 0:
# print ('add course successfully')
# else:
# raise Exception ('failed to add course')
# list the courses again for the second time
CoureListAfter = list_course (sessionid) ['retlist']
# use len to calculate the number of courses before and after adding courses, and then subtract it to equal to 1 to prove success, or you can directly take the number of courses returned total for verification
CreateCount = len (coureListAfter)-len (coureListBefore)
Assert createCount = = 1
# take out, an extra course object
Newcourse = None
For one in coureListAfter:
If one not in coureListBefore:
Newcourse = one
Break
# check to see if it is the course you just added
Assert newcomers started none
Assert newcourse ['name'] = =' classname'
Assert newcourse ['desc'] =' php language'
Assert newcourse ['display_idx'] = = 2
# clear the environment operation and delete the course you just added
Delete_course (newcourse ['id'], sessionid)
Print ('\ n = test case pass =')
The running results of the console are obtained.
Thank you for reading! This is the end of the article on "how to automate the interface in python+requests". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.