common中存放的是整个项目中公共使用的封装方法
从工程目录上可以看到区分
datas中专门存放测试数据(yml文件)
cases中专门集中存放测试用例 ...
数据分离的第一步先找到工程项目路径
1 2 3 4 5 6 7 8 9 10 11 12 | # -*- encoding: utf-8 -*- """ @__Software__: PyCharm @__File__: osPath.py @__Date__: 2021/6/14 21:08 """ import os # 获取项目的根目录,apiTest层 FILE = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) # 获取存放测试数据的文件夹 DATAS = os.path.join( FILE , 'datas' ) print (DATAS) |
1 2 | F:\project_gitee\Test\apiTest\datas Process finished with exit code 0 |
运行结果可以清晰看到,已经找到存放数据的文件夹路径并拼接成功 ...
os模块不熟悉可参考菜鸟教程
数据分离的第二步封装一个读取yml文件的函数或类方法
这里就先写一个函数把
首先要先安装yml
再导入包,然后再进行封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # -*- encoding: utf-8 -*- """ @__Software__: PyCharm @__File__: readData.py @__Date__: 2021/6/14 21:07 """ import os import yaml from common import osPath as sp def read_yml( file ): with open ( file , mode = 'r' , encoding = 'utf-8' ) as read_data: results = yaml.load(read_data, Loader = yaml.FullLoader) return results print (read_yml(os.path.join(sp.DATAS, 'test_data.yml' ))) |
1 2 | { 'test_data' : [[{ 'type' : 1 }, { 'reason' : '查询成功!' }], [{ 'type' : 2 }, { 'reason' : '查询成功!' }], [{ 'type' : 3 }, { 'reason' : '查询成功!' }]]} Process finished with exit code 0 |
读取yml的函数写完以后,要记得测试下是否满足自己需要的功能;从结果来看满足我目前需要功能 ...
yaml语法不熟悉的也可以参考菜鸟教程
数据分离的第三步测试用例中引入数据并运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # -*- encoding: utf-8 -*- """ @__Software__: PyCharm @__File__: test_example.py @__Date__: 2021/6/13 19:00 """ import os import pytest import requests from common import osPath as sp from common.readData import read_yml class TestExample: s = requests.Session() data = read_yml(os.path.join(sp.DATAS, 'test_data.yml' )) @pytest .mark.parametrize( "test_data, expected" , data[ 'test_data' ]) def test_example( self , test_data, expected): with self .s as s: url = "http://apis.juhe.cn/fapig/euro2020/schedule?key=9d0dfd9dbaf51de283ee8a88e58e218b" response = s.get(url, params = test_data) print (response.json()) assert response.json()[ "reason" ] = = expected[ "reason" ] if __name__ = = '__main__' : pytest.main([ "-v" , "-s" , "test_example" ]) |
1 2 3 4 5 6 7 | Launching pytest with arguments F: / project_gitee / Test / apiTest / cases / test_example.py in F:\project_gitee\Test\apiTest\cases = = = = = = = = = = = = = = = = = = = = = = = = = = = = = test session starts = = = = = = = = = = = = = = = = = = = = = = = = = = = = collecting ... collected 3 items test_example.py::TestExample::test_example[test_data0 - expected0] test_example.py::TestExample::test_example[test_data1 - expected1] test_example.py::TestExample::test_example[test_data2 - expected2] = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 3 passed in 0.66s = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = |
data['test_data']是字典取值,取key为test_data的value值 ...
从返回的结果可以清晰看到,3 passed,且用时0.66s ...
至此,测试数据和代码分离完成 ...
最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走! 希望能帮助到你!【100%无套路免费领取】