统一使用json格式数据,将数据存放在 jsondatas 目录中

创建测试数据
image.png
jsondatas/useraction/register.json

  1. [
  2. {
  3. "bodydata": {"loginName": "17088889999","password": "123456"},
  4. "expect": {"resultCode":500,"message":"用户名已存在!","data":null}
  5. },
  6. {
  7. "bodydata": {"loginName": "","password": "123456"},
  8. "expect": {"resultCode":510,"message":"登录名不能为空","data":null}
  9. },
  10. {
  11. "bodydata": {"loginName": "13211123333","password": ""},
  12. "expect": {"resultCode":510,"message":"密码不能为空","data":null}
  13. },
  14. {
  15. "bodydata": {"loginName": "","password": ""},
  16. "expect": {"resultCode":510,"message":"密码不能为空","data":null}
  17. }
  18. ]

封装处理json文件

utils/filehandler.py

  1. """
  2. 处理json文件
  3. """
  4. import os
  5. import json
  6. jsondir = os.path.join(os.path.dirname(os.path.dirname(__file__)),"jsondatas")
  7. def parse_json(filepath):
  8. """
  9. 默认从jsondatas 目录中读取文件。传的文件路经
  10. useraction/register.json
  11. :param filepath:
  12. :return:
  13. """
  14. jsonpath = os.path.join(jsondir,filepath)
  15. print(jsonpath)
  16. with open(jsonpath,encoding='utf8') as file:
  17. testdata = json.load(file)
  18. return testdata
  19. if __name__ == '__main__':
  20. data = parse_json(r'useraction\register.json')
  21. print(data)

创建测试用例

在测试用例中,通过读取json文件中的数据进行对应的测试。

testcases/test_ddt/test_user_actions.py

  1. """
  2. 用户操作相关
  3. """
  4. import pytest
  5. from utils.myrequests import MyRequests
  6. from utils.filehandler import parse_json
  7. myreq = MyRequests()
  8. testdata = parse_json('useraction/register.json')
  9. class TestUserActions:
  10. @pytest.mark.parametrize("data",testdata)
  11. def test_register(self,data):
  12. """
  13. 测试注册功能
  14. :return:
  15. """
  16. url = "/api/v1/user/register"
  17. bodydata = data["bodydata"]
  18. r = myreq.do_requests(method='post', url=url, json=bodydata)
  19. print(r.json())
  20. assert r.json() == data["expect"] # 使用数据驱动中的断言

执行

  1. pytest -s -v testcases\test_ddt\test_user_actions.py

image.png