当前位置:网站首页>Technology sharing | do you know the functions of the server interface automated testing and requests library?
Technology sharing | do you know the functions of the server interface automated testing and requests library?
2022-07-26 21:42:00 【The elegance of testing】
If you want to design a powerful interface testing framework , First of all, we need a good enough HTTP The third Library , Carry out secondary development on its basis . And the best choice for this third library is Requests,Requests Is an elegant and simple python HTTP library , And the built-in function in addition to the basic send request , Return outside the response information , There are also very practical and powerful agent functions 、auth Certification, etc , Next, the actual practice of interface automation testing , And all requests Is closely linked .
Interface test framework installation
pip Command to install requests.
pip install requests
Requests Official documents :
https://2.python-requests.org/en/master/
Next, use the most popular Requests Conduct interface test .Requests Provides almost everything HTTP Request construction method , And the method of passing in parameters , Customize the configuration of the sent request . It can be used to deal with various request scenarios . common HTTP The request construction methods are get、post、put、delete、head、options etc. .
Interface request construction
http Request construct
send out get request
import requests
r = requests.get('https://api.github.com/events')
Add... To the request data Parameters , And send the post request
import requests
r = requests.post('https://httpbin.ceshiren.com/post',
data = {'key':'value'})
Add... To the request data Parameters , And send the put request
import requests
r = requests.put('https://httpbin.ceshiren.com/put',
data = {'key':'value'})
send out delete request
import requests
r = requests.delete(
‘https://httpbin.ceshiren.com/delete’)
send out head request
import requests
r = requests.head('https://httpbin.ceshiren.com/get')
send out options request
import requests
r = requests.options('https://httpbin.ceshiren.com/get')
It can also be used directly request function , Introduce different method, For example, use this method to send get request
import requests
requests.request("get", "http://www.baidu.com")
Other important parameters
The following parameters are not required , But if additional customization of the request is needed , The following parameters are required .
header Parameters
By passing in dict Custom request header
import requests
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
data Parameters
Send a data sheet encoded as a form
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("https://httpbin.ceshiren.com/post"
, data=payload)
>>> r.text
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
timeout Parameters
Set the timeout ( second ), When this time is reached, it will stop waiting for a response :
>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout:\
HTTPConnectionPool(host='github.com', port=80):\
Request timed out. (timeout=0.001)
allow_redirects Parameters
If in the process of interface automation testing , The tested interface itself will trigger redirection in some scenarios , If you don't want it to trigger redirection , This interface is required to reset the forward response content , You can use allow_redirects The parameter directly gets the response content before its reset . Controls whether redirection is enabled , The default is True Is enabled , choice False To disable .
>>> import requests
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
proxies Parameters
If you want the request data to pass through the specified port , You can use the proxies Parameter setting proxy . After setting , This data is in the process of request , Will go through agent tools . This parameter can be used to obtain the corresponding request data information by the packet capturing tool . The parameter requirements are dict Format ,key The value is the selected protocol , It can be set separately http Request and https The requested agent .
>>> import requests
>>> proxies = {
... 'http': 'http://127.0.0.1:8080',
... 'https': 'http://127.0.0.1:8080',
... }
>>> r = requests.get('https://httpbin.ceshiren.com/get',
proxies=proxies, verify=False)
>>> r.text
After the code is written like this , Can be in Charles Configure proxy settings in ( Configuration method reference HTTP、HTTPS Caught analysis ), Then run the code , Then you can clearly capture the request information .
Be careful : A proxy tool needs to listen to the relevant ports ( This example is 8080), Otherwise, the code fails

verify Parameters
If in the process of using agents ,https The data information of the protocol needs to verify the certificate information by default , If you do not pass in the certificate information , Or turn off certificate verification , Then in the process of request requests An error message will be returned .verify Parameters can be passed in bool Value or string, The default is True. If set to False To ignore is to ignore SSL Certificate verification ; On the contrary, verification is needed ; If the pass in value is string Words , Specifies the local certificate as the client certificate .
Don't use verify Parameters or verify The parameter defaults to True
>>> import requests
>>> proxies = {
'http': 'http://127.0.0.1:8080',
'https': 'http://127.0.0.1:8080'
}
>>> r = requests.get('https://httpbin.ceshiren.com/get',
proxies=proxies, verify=True)
The result is certificate verification failure information
File "/usr/local/lib/python3.7/site-packages/requests/adapters.py", line 514, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='httpbin.ceshiren.com', port=443): Max retries exceeded with url: /get (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)')))
Ignore right SSL Certificate verification
>>> import requests
>>> proxies = {
... 'http': 'http://127.0.0.1:8080',
... 'https': 'http://127.0.0.1:8080',
... }
>>>
>>> r = requests.get('https://httpbin.ceshiren.com/get',
... proxies=proxies, verify=False)
>>> r.text
The result is a normal response message , But with warning Warning , The warning message is normal , You can ignore .
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:1020: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning,
{
"args": {},
"headers": {
... The middle is omitted ...
},
"origin": "10.7.152.0",
"url": "https://httpbin.ceshiren.com/get"
}
Incoming from local charles certificate
>>> import requests
>>> proxies = {
'http': 'http://127.0.0.1:8080',
'https': 'http://127.0.0.1:8080',
}
>>> r = requests.get('https://httpbin.ceshiren.com/get',
proxies=proxies,
verify="charles-ssl-proxying-certificate.pem")
>>> r.text
The result is a normal response message , And there's no warning Warning
{
"args": {},
"headers": {
... The middle is omitted ...
},
"origin": "10.7.152.0",
"url": "https://httpbin.ceshiren.com/get"
}
Three other important parameters json、cookies、auth It will be introduced in detail in the following chapters .
Last : It can be in the official account : Sad spicy bar ! Get one by yourself 216 Page software testing engineer interview guide document information 【 Free of charge 】. And the corresponding video learning tutorial is free to share !, It includes basic knowledge 、Linux necessary 、Shell、 The principles of the Internet 、Mysql database 、 Special topic of bag capturing tools 、 Interface testing tool 、 Test advanced -Python Programming 、Web automated testing 、APP automated testing 、 Interface automation testing 、 Testing advanced continuous integration 、 Test architecture development test framework 、 Performance testing 、 Safety test, etc. .
Now I invite you to join our software testing learning exchange group :【746506216】, remarks “ The group of ”, We can discuss communication software testing together , Learn software testing together 、 Interview and other aspects of software testing , There will also be free live classes , Gain more testing skills , Let's advance together Python automated testing / Test Development , On the road to high pay .
Friends who like software testing , If my blog helps you 、 If you like my blog content , please “ give the thumbs-up ” “ Comment on ” “ Collection ” One Key triple connection !
Software Test Engineer self-study tutorial :
Interface performance test — Software testers will 618 Analysis of actual combat scenes
Jmeter Explain the case in practice — Software testers will

边栏推荐
- 技术分享 | 服务端接口自动化测试, Requests 库的这些功能你了解吗?
- 谈谈 TCP 的 TIME_WAIT
- word-break: break-all VS word-wrap: break-word
- 浏览器主页被篡改怎么办,主页被篡改恢复方法
- 伟创力回应“扣押华为物料”事件:深感遗憾,期待继续合作!
- Thorough load balancing
- 美国再次发难:禁止承包商采购这5家中国公司的设备与技术
- It is said that Samsung obtained EUV photoresist from Belgium
- FreeRTOS个人笔记-软件定时器
- What to do if the browser home page is tampered with, and how to recover if the home page is tampered with
猜你喜欢

1-《PyTorch深度学习实践》-线性模型

5、 Applet error: message:error: system error, error code: 80058, desc of scope userLocation is empty

五、小程序报错:message:Error: 系统错误,错误码:80058,desc of scope.userLocation is empty

TypeScript中的类型断言

内容管理工具,用蓝色书签就足够

Type assertion in typescript

6、 Wechat applet release process

VI and VIM text editors

浏览器主页被篡改怎么办,主页被篡改恢复方法

(C语言)文件的基本操作
随机推荐
七、微信小程序运行报错:Error: AppID 不合法,invalid appid
Pinduoduo gets search term recommendation API
LeetCode 练习——剑指 Offer II 005. 单词长度的最大乘积
Registration conditions for information system project managers in the second half of 2022 (soft examination advanced)
谈谈 TCP 的 TIME_WAIT
2022年简历石沉大海,别投了,软件测试岗位饱和了....
(C language) a brief introduction to define
FreeRTOS personal notes - Software Timer
Flextronics responded to the "seizure of Huawei materials" incident: deeply regretted, looking forward to continuing cooperation!
京东一面:Redis 如何实现库存扣减操作?如何防止商品被超卖?
Happens-Before原则深入解读
Type assertion in typescript
Japan approves the export of EUV photoresist to South Korea, and the crisis of Samsung and SK Hynix may be alleviated
仅需一个依赖给Swagger换上新皮肤,既简单又炫酷
平滑滚动到元素
:active vs :focus
织梦文档关键词维护不管用
MySQL的JDBC操作及入门案例
event.preventDefault VS return false
Six instructions of Memcache based caching mechanism
