一、requests使用方式
1、requests.get()
import requests
def test_get():
//请求地址
url = ‘xxx’
//requests库发出GET请求
r = requests.get(url = url)
//输出响应类
print(r)
//输出响应结果(json格式)
print(r.json())
#注意:当响应出错,如响应码为404,是无法转换为json格式。
//输出请求地址
print(r.url)
//输出状态码
print(r.status_code)
//输出请求头
print(r.request.headers)
2、requests.post()
import requests
def test_post():
//请求地址
url = ‘xxx’
post_data = {
'name' = 'guo',
'age' = '23'
'sex' ='girl'
}
//requests库发出POST请求
r = requests.post(url = url, data = post_data)
//输出状态码
print(r.status_code)
print(r.json())
//输出请求头
print(r.request.headers)
def post(url, data=None, json=None, **kwargs);
使用post(url, data)
请求头中数据格式
Content_type : application/x-www-form-urlencodes
使用post(url, json)
请求头中数据格式
Content_type : application/json
二、pytest编写测试用例及aseert使用
/testcases/test_page.py
下面展示一些 aseert的使用方式
import requests
def test_post():
//请求地址
url = ‘xxx’
post_data = {
'name' = 'guo',
'age' = '23'
'sex' ='girl'
}
//requests库发出POST请求
r = requests.post(url = url, data = post_data)
# 使用断言对比期望结果和实际结果
//assert断言判断状态码
assert r.status_code == 200
//assert断言判断输出状态
assert r.json()['success'] == True
下面展示pytest的运行方式
//方式1:指定路径
>pytest testcases
//方式2:指定文件
>pytest testcases\test_page.py
//方式2:指定函数
>pytest testcases\test_page.py::test_post
pytest当执行通过时,默认不会输出print()结果的。如果想输出的话,添加参数-s。
//方式1:指定路径
>pytest testcases -s
//方式2:指定文件
>pytest testcases\test_page.py::test_post -s