简介:当需要执行的测试用例达到一定的量后,存储和管理测试用例直接放在test_case显然是不合理的,需要将测试用例存储在测试用例文件。综合来看,主要有3种方式存储,即:excel、csv、yaml。
Excel: 提供了丰富的格式和功能,可以方便地进行编辑和维护。图形界面使得用户可以直观地看到数据。但不是纯文本格式,不适合版本控制,也不易于自动化测试工具的集成。
CSV: 纯文本格式,易于版本控制,也易于自动化工具处理。缺乏Excel的直观性和功能,不适合存储复杂的测试用例数据。
YAML:可读性高,可读取的数据序列化格式,易于维护和阅读。它支持复杂的数据结构,如列表和字典。YAML不提供Excel那样的可视化界面。
小记:萝卜青菜各有所爱,如果需要设计比较复杂的业务场景,个人更倾向于yaml。
历史攻略:
安装依赖:
pip install pyyaml
测试用例文件:yaml
test_demo:
test_demo_01:
before_cmd_list: ["ls -al", "hostnamect"]
cmd_list: ["free -h"]
assert: ["Mem:"]
after_cmd_list: ["date", "who"]
test_demo_02:
before_cmd_list: ["pwd"]
cmd_list: ["date"]
assert: ["2023"]
after_cmd_list: ["echo python2"]
test_demo_03:
before_cmd_list: ["pwd"]
cmd_list: ["date"]
assert: ["2024"]
after_cmd_list: ["echo python3"]
编写读取yaml测试用例的方法 read_yaml.py
# -*- coding: utf-8 -*-
# time: 2024/3/29 1:19
# file: read_ym.py
# 公众号: 玩转测试开发
import yaml
def read_yaml(yaml_path, node_name):
with open(yaml_path, "r", encoding="utf8")as f:
data = yaml.safe_load(f)
print(data[node_name])
return list(data[node_name].values())
if __name__ == '__main__':
yaml_path = r"../data/demo.yaml"
data = read_yaml(yaml_path, "test_demo")
test_demo.py解析参数化
# -*- coding: utf-8 -*-
# time: 2024/3/31 10:34
# file: test_demo.py
# 公众号: 玩转测试开发
import time
import pytest
from lib.read_ym import read_yaml
from logger import log
class TestDemo:
@pytest.mark.parametrize("case_info", read_yaml("./data/demo.yaml", "test_demo"))
def test_demo(self, case_info):
log.info(case_info["before_cmd_list"])
log.info(case_info["cmd_list"])
log.info(case_info["assert"])
log.info(case_info["after_cmd_list"])
执行main.py
# -*- coding: utf-8 -*-
# time: 2024/03/24 10:30
# file: main.py
# 公众号: 玩转测试开发
import os
import pytest
if __name__ == "__main__":
# step-1:use pytest run test_case
pytest.main(["-s", "test_case/test_demo.py", '-n', 'auto', "--alluredir", "./report"])
# step-2:auto report json data,zip to allure-html
os.system("allure serve report")
运行结果: