Excel+pytest
转自:https://www.cnblogs.com/liangjt/p/12865713.html
这是我们写的测试用例:
这里主要关注第七列,假设已经拿到了其它参数发送请求出去,根据响应内容获取到响应消息体的retcode,与表中的code进行断言判断通过与否(比如0通过,2不通过)
以下是代码实现:
1 import pytest
2 import xlrd
3 import json
4
5
6 lines = [] # 创建空表用来存Excel每一行内容
7 worksheet = xlrd.open_workbook('../data/教管系统-测试用例V1.2.xls').sheet_by_index(2)
8 rows = worksheet.nrows # 获取行数
9 for i in range(1, rows):
10 line = worksheet.row_values(i)
11 lines.append(line)
12
13
14 @pytest.fixture(params=lines) # pytest工厂函数,默认方法级别
15 def init_x(request):
16 return request.param # 固定格式,每一次取出params的一个元素
17
18
19 class Test_x:
20 def test_x(self, init_x):
21 code = json.loads(init_x[6]) # 把第七列内容json格式的字符串转成字典格式
22 code = code['code'] # 拿到code的值
23 assert code != 0 # 断言是否通过
或者使用参数化:
1 import pytest
2 import xlrd
3 import json
4
5
6 def get_data():
7 lines = []
8 worksheet = xlrd.open_workbook('../data/教管系统-测试用例V1.2.xls').sheet_by_index(2)
9 rows = worksheet.nrows
10 for i in range(1, rows):
11 line = worksheet.row_values(i)
12 lines.append(line)
13 return lines
14
15
16 class Test_x:
17 @pytest.mark.parametrize("code", get_data()) # pytest参数化装饰器,第一个参数写自定义的参数名,第二个参数传取到的数据
18 def test_x(self, code): # 上面的参数名是什么,这里也要写什么
19 retcode = json.loads(code[6])
20 retcode = retcode['code']
21 assert retcode != 0
运行结果:

共45个测试,显示34个通过11个不通过,不通过的原因也能看到:0 != 0。
当然,实际的接口测试并不是规定0代表通过,2代表不通过,而是根据实际响应得到的retcode与code是否相等来判断。
这里只是简单的实践一下,肯定有更好的实现方式。
等待你的评论。

浙公网安备 33010602011771号