数据:
data.yml
success:
"正整数相加": [1,1,2]
"正负2位小数相加": [ -0.01,0.02,0.01 ]
"正整数小数相加": [ 10,0.02,10.02 ]
"边界值99先98.99": [ 99,98.99,197.99 ]
"边界值99后98.99": [ 98.99,99,197.99 ]
"边界值-99先-98.99": [ -99,-98.99,-197.99 ]
"边界值-99后-98.99": [ -98.99,-99,-197.99 ]
tips:
"边界值99.01先": [99.01,0,"参数大小超出范围"]
"边界值99.01后": [1,99.01,"参数大小超出范围"]
"边界值-99.01先": [-99.01,-10,"参数大小超出范围"]
"边界值-99.01后": [-2,-99.01,"参数大小超出范围"]
error:
"中文先": ["中文先",2,"TypeError"]
"中文后": [4,"中文后","TypeError"]
工具:
util.py
import os
import yaml
def getdata(filepath):
"""
当前目录的上一级目录(test目录),拼接test目录下的文件路径
:param filepath: test目录下的文件路径
:return: 返回嵌套数据字典
"""
dirpath = os.path.dirname(os.path.abspath(__file__))
finalpath = os.path.join(dirpath,"..",filepath)
print(finalpath)
with open(finalpath, "r", encoding="utf-8") as f:
add_data = yaml.safe_load(f)
return add_data
用例:
test_add.py
import logging
import allure
import pytest
from test.base.Base import Base
from test.utils.util import getdata
@allure.feature("计算器模块")
@allure.story("加法功能")
class TestAdd(Base):
logging.info("读取yaml数据:字典类型")
# 获取 yaml 的嵌套数据字典
add_data = getdata(r"datas\adddata.yml")
@allure.title("加法:成功")
@pytest.mark.success
@pytest.mark.run(order=1)
@pytest.mark.flaky(reruns=3,reruns_delay=2)
@pytest.mark.parametrize("add1,add2,expect",
add_data["success"].values(),
ids=add_data["success"].keys())
def test_add_success(self,add1,add2,expect):
logging.info(f"输入数据:{add1},{add2},期望结果:{expect}")
allure.attach.file(r"C:\workplace\PycharmProject\PytestCalculator\test\img\计算器.PNG",
name="计算器",attachment_type=allure.attachment_type.JPG)
with allure.step("step1:相加操作"):
result = self.cal.add(add1,add2)
logging.info(f"断言实际结果{result}=={expect}")
with allure.step("step2:断言"):
assert result == expect
@allure.title("加法:入参提示")
@pytest.mark.tips
@pytest.mark.run(order=2)
@pytest.mark.parametrize("add1,add2,expect",
add_data["tips"].values(),
ids=add_data["tips"].keys())
def test_add_tips(self, add1, add2, expect):
logging.info(f"输入数据:{add1},{add2},期望结果:{expect}")
with allure.step("step1:相加操作"):
result = self.cal.add(add1, add2)
logging.info(f"断言实际结果{result}=={expect}")
with allure.step("step2:断言"):
assert result == expect
@allure.title("加法:入参错误")
@pytest.mark.error
@pytest.mark.run(order=3)
@pytest.mark.parametrize("add1,add2,expect",
add_data["error"].values(),
ids=add_data["error"].keys())
def test_add_error(self, add1, add2, expect):
logging.info(f"输入数据:{add1},{add2},期望结果:{expect}")
with pytest.raises(TypeError):
with allure.step("step1:相加操作"):
result = self.cal.add(add1, add2)
logging.info(f"断言实际结果{result}=={expect}")
with allure.step("step2:断言"):
assert result == expect