序列化和反序列化、pytest-DDT数据驱动

序列化

序列化就是将对象转化成文件

python转成json

python 复制代码
import json


data = {
    "数字": [1, 1.1, -1],
    "字符串": ["aaaa", 'bbbb'],
    "布尔值": [True, False],
    "空值": None,
    "列表": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    "字典": [{"a": 1, "b": 2}, {"c": 3}]
}

with open("data.json", "w", encoding="utf-8") as f:
    s = json.dumps(data, ensure_ascii=False)
    f.write(s)

python转成yaml

python 复制代码
import yaml

data = {
    "数字": [1, 1.1, -1],
    "字符串": ["aaaa", 'bbbb'],
    "布尔值": [True, False],
    "空值": None,
    "列表": [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    "字典": [{"a": 1, "b": 2}, {"c": 3}]
}


with open("data.yaml", "w", encoding="utf-8") as f:
    s = yaml.safe_dump(data, allow_unicode=True)
    f.write(s)

反序列化

反序列化就是将文件转化成对象

json转成python

python 复制代码
import json

with open("data.json", "r", encoding="utf-8") as f:
    s = json.loads(f.read())
    print(s)

yaml转成python

python 复制代码
import yaml

with open("data.yaml", "r", encoding="utf-8") as f:
    s = yaml.safe_load(f.read())
    print(s)


# yaml可以完全兼容json
with open("data.json", "r", encoding="utf-8") as f:
    s = yaml.safe_load(f.read())
    print(s)

pytest的DDT数据驱动

**DDT:**数据驱动测试

**DDT数据驱动的本质:**测试框架根据数据文件的内容,来决定如何执行测试用例

实现思路:

(1)将用例参数的数据存放在(.json、.yaml等)文件中

(2)读取文件中的数据

(3)将数据传递给pytest(根据数据创建用例)

(4)在用例中使用数据

举例:

将从ddt_yaml.yaml文件中读取的数据内容打包成列表传递给@pytest.mark.parametrize()

yaml里面的内容(这里给出的数据不是纯yaml语法的格式):

python 复制代码
- [1, 2]
- [2, 3]
- [3, 4]
- [0, -1]

用例实现:

python 复制代码
mport pytest
import yaml


def add(a, b):
    return a + b


with open("ddt_yaml.yaml", "r", encoding="utf-8") as f:
    l = yaml.safe_load(f.read())
    print(l)


@pytest.mark.parametrize(
    "a, b",
    l,
)
def test_abc(a, b):
    c = add(a, b)
    assert c == a + b

优点

  1. 方便用例的增加和减少(只需要改变文件里面的数据组数就可以控制用例数量)

  2. 方便对用例内容的修改

相关推荐
测试开发Kevin16 小时前
从投入产出、效率、上手难易度等角度综合对比 pytest 和 unittest 框架
python·pytest
测试开发Kevin3 天前
以pytest_addoption 为例,讲解pytest框架中钩子函数的应用
python·pytest
川石教育9 天前
Pytest中的fixture装饰器详解
python自动化测试·pytest·pytest自动化测试框架·pytest测试框架·pytest单元测试框架
春风又。9 天前
接口自动化——参数化
python·测试工具·自动化·pytest
XTY0011 天前
mac电脑pytest生成测试报告
pytest
程序员的世界你不懂11 天前
pytest-前后置及fixture运用
pytest
天才测试猿13 天前
基于Pytest接口自动化的requests模块项目实战以及接口关联方法详解
自动化测试·软件测试·python·测试工具·单元测试·测试用例·pytest
HtwHUAT13 天前
五、UI自动化测试05--PyTest框架
经验分享·python·ui·pytest
程序员的世界你不懂14 天前
Pytest-mark使用详解(跳过、标记、参数 化)
pytest
fish_study_csdn16 天前
pytest 技术总结
开发语言·python·pytest