当前位置:网站首页>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

边栏推荐
- It is said that Samsung obtained EUV photoresist from Belgium
- Highlight the secondary and tertiary columns under the primary column of pbootcms
- 从手动测试,到自动化测试老司机,只用了几个月,我的薪资翻了一倍
- 单机部署flink,创建oracle19c rac的连接表时报错 ORA-12505,有哪位大佬帮忙
- 一种用于实体关系抽取的统一标签空间
- Valley segment coverage - (summary of interval sequencing problem)
- Jd.com: how does redis realize inventory deduction? How to prevent goods from being oversold?
- 月薪5万的朋友告诉我,你只是在打杂
- 分布式 session 的4个解决方案
- Is it safe for Huishang futures to open an account? What should Huishang futures pay attention to when opening an account?
猜你喜欢

功能尝鲜 | 解密 Doris 复杂数据类型 ARRAY

FreeRTOS个人笔记-软件定时器

Difference between redis hash and string

京东一面:Redis 如何实现库存扣减操作?如何防止商品被超卖?

攻防世界----ics-07

LDAP -- realize unified login management of users

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

CMake 的使用

Deepfake pinches his face. It's hard to tell whether it's true or false. Tom Cruise is more like himself than himself!
![[MySql]substr用法-查询表的某个字段的具体位数的值](/img/d5/68658ff15f204dc97abfe7c9e6b354.png)
[MySql]substr用法-查询表的某个字段的具体位数的值
随机推荐
Selenium自动化测试面试题全家桶
cmake编译obs-studio-27.2.0
力扣每日一题-第43天-168. Excel表列名称
补充—非线性规划
仅需一个依赖给Swagger换上新皮肤,既简单又炫酷
六、微信小程序发布流程
Uncover the secrets of Xiaomi 100million pixel camera: 1/1.3 inch COMS sensor, resolution 12032 × nine thousand and twenty-four
Highlight the secondary and tertiary columns under the primary column of pbootcms
Supplement - nonlinear programming
日本批准向韩出口EUV光刻胶,三星、SK海力士危机或将缓解
FreeRTOS个人笔记-软件定时器
MySQL -count: the difference between count (1), count (*), and count (column name)
Shrimp Shope takes the commodity list API according to keywords
Content management tools, blue bookmarks are enough
Thorough load balancing
五、小程序报错:message:Error: 系统错误,错误码:80058,desc of scope.userLocation is empty
Summary of common interview questions of operating system, including answers
A new technical director asked me to do an IP territorial function~
Props with type Object/Array must...
TCP的粘包拆包问题解决方案
