安装request库
以火车的站站查询为例的post和get方法的接口测试
使用pytest测试接口
1、requests的请求机制
1、安装request库
2、以火车的站站查询为例的post和get请求方法
2.1get请求:
两种传参方式
1、_url = “网址+参数” = “网址?key1=value1&key2=value2”
response1 = request.get(url = _url)2、字典拼接
_params = {“key1” : “value1”,“key2” : “value2”,}response2 = requests.get(url=“网址”, params = _params)import requestsresponse = requests.get(url="https://api.binstd.com/train/station2s?start=北京&end=西安&ishigh=0&appkey=d737aad9a0d9dc97")print(response.text) #字符串格式print(response.json()) #json,前提需要确保返回内容为json格式,否则报错#字典方式拼接参数print("-------------字典方式拼接参数---------------")params = { "start" : "北京", "end" : "西安", "ishigh" : 0 , "appkey" : "d737aad9a0d9dc97"}response1 = requests.get(url="https://api.binstd.com/train/station2s", params = params)print(response1.text)print(response1.json())2.2post请求
拼接参数方式传参
常见的请求方法
请求方法 含义 requests.get() 获取html的主要方法 requests.head() 获取html头部信息的主要方法 requests.post() 向html网页提交post请求的方法 requests.put() 向html网页提交put请求的方法 requests.patch() 向html提交局部修改的请求 requests.delete() 向html提交删除请求
2、pytest测试接口
1、安装pytest
pip install pytest
2、使用pytest测试接口
在pytest框架中,有如下约束:
文件名要以test开头或者结尾(test_*.py / *_test.py),可以包含一个或多个test_开头的函数。
此时,在执行pytest命令时,会自动从当前目录及子目录中寻找符合上述约束的测试函数来执行。
4.1首先得到响应数据
import requestsdef request_ticket(): #返回接口响应结果 url = "https://api.binstd.com/train/ticket" payload = { "start": "北京", "end": "西安", "date": "2019-10-1", "appkey": "d737aad9a0d9dc97" } #response = requests.get(url = _url, parms = payload) response = requests.post(url = url, data = payload) print(response.text) return responserequest_ticket()4.2为了方便查看将响应结果格式化:由于太长,部分用省略号代替
{ "status": 0, "msg": "ok", "result": { "start": "北京", "end": "西安", "date": "2020-06-10", "list": [ { "trainno": "G667", "type": "G", "typename": "高铁", "station": "北京西", "endstation": "西安北", "departuretime": "11:19", ... "departstationcode": "BXP", "terminalstationcode": "EAY", "startdate": "20200610", ... }, { "trainno": "G659", "type": "G", "typename": "高铁", "station": "北京西", "endstation": "西安北", "departuretime": "11:53", ... "departstationcode": "BXP", "terminalstationcode": "EAY", "startdate": "20200610", ... }, {...}, {...}, ... ] }}4.3取出数据
出发站(station)和到达站(endstation)在result中的list下,怎么取到呢?----[“result”] [“list”]
---- request_ticket().json()[“result”][“list”]
4.4 运行
4.5 查看结果
如果该路径下有多个以test开头或者结尾的文件,则会一起检测两个文件中的接口
如果出现ERROR则在文件中找错误原因
总结
到此这篇关于pycharm中使用request和Pytest进行接口测试的文章就介绍到这了,更多相关pycharm使用request和Pytest接口测试内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!