pytest + yaml 框架 -25.参数化数据支持读取外部文件txt/csv/json/yaml

前言

v1.2.2版本开始,参数化数据支持读取外部文件,文件格式可以支持:txt/csv/json/yaml

参数化的实现

用例参数化的实现,我设计了2种实现方式

参数化方式1:

  config:
     name: post示例
     fixtures: username, password
     parameters:
       - [test1, '123456']
       - [test2, '123456']

参数化方式2:

  config:
     name: post示例
     parameters:
       - {"username": "test1", "password": "123456"}
       - {"username": "test2", "password": "1234562"}

详情参看前面参数化的介绍https://www.cnblogs.com/yoyoketang/p/16932156.html

内置 p 函数

内置 p 函数(也可以使用大写P)可以支持读取外部文件数据,文件格式可以支持:txt/csv/json/yaml
可以传2个参数

  • 参数1,传文件的路径,可以是相对路径,如:data/yoyo.txt
  • 参数2,布尔值,是否需要读取第一行title数据,默认是,针对txt/csv文件

读取json、yaml文件示例

data/x2.json 文件内容

[
  {"username": "test1", "password": "123456"},
  {"username": "test2中文", "password": "1234562"}
]

data/x3.yml 文件内容

- {"username": "test1", "password": "123456"}
- {"username": "test2中文", "password": "1234562"}

test_json_yaml.yml

config:
    name: 参数化读取文件json和yaml


test_p1:
    print: ${username}
    parameters: ${p('data/x2.json', False)}


test_p2:
    print: ${username}
    parameters: ${p('data/x3.yml')}

如果不需要title,在用例中使用fixtures关键字显示声明参数名称
data/y2.json 文件内容

[
  ["test1", "123456"],
  ["test2中文", "1234562"]
]

data/y4.yml 文件内容

- ["test1", "123456"]
- ["test2中文", "1234562"]

test_json_yaml2.yml

config:
    name: 参数化json和yaml


test_p1:
    print: ${username}
    fixtures: username,password
    parameters: ${p('data/y2.json', False)}


test_p2:
    print: ${username}
    fixtures: username,password
    parameters: ${p('data/y4.yml')}

读取txt文件示例

data/x1.txt 文件内容

test1,123456
test2,1234562

data/x2.txt 文件内容 带第一行title

username,password
test1,123456
test2,1234562

test_text.yml

config:
    name: 参数化读取文件txt


test_p1:
    print: ${username}
    fixtures: username, password
    parameters: ${p('data/x1.txt', False)}


test_p2:
    print: ${username}
    parameters: ${p('data/x2.txt')}

读取csv 文件示例

data/xx.csv 文件内容

test1中文,123456
test2,1234562

data/yy.csv 文件内容

username,password
test1中文,123456
test2,1234562

test_csv.yml

config:
    name: 参数化读取文件csv


test_p1:
    print: ${username}
    fixtures: username, password
    parameters: ${p('data/xx.csv', False)}


test_p2:
    print: ${username}
    parameters: ${p('data/yy.csv')}

网易云完整视频课程https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338
报名咨询wx:283340479 (已报名的同学学习过程中有问题,都可以协助解决)

posted @ 2023-04-19 09:23  上海-悠悠  阅读(503)  评论(0编辑  收藏  举报