如何使用Pytest结合yaml进行参数化测试?

2026-05-21 14:491阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计223个文字,预计阅读时间需要1分钟。

如何使用Pytest结合yaml进行参数化测试?

1. 读取YAML文件(文件路径在关键点)

2.单参数版本

3.多参数版本

如何使用Pytest结合yaml进行参数化测试?

一、读取yaml(关键点在于文件的路径)

1、单参数版,多参数版

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Pytest
@File :read_data.py
@IDE :PyCharm
@Author :zhou
@Date :2022/8/6 19:05
"""
import os

import yaml

path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "data.yaml")


def read_data():
# 获取文件
f = open(path, encoding="utf-8")
# 读取文件内容
data = yaml.safe_load(f)
return data


get_data = read_data()
print(get_data)

二、parametrize使用yaml文件中的数据

# 单参数版
@pytest.mark.parametrize("name", get_data['person'])
def test_parametrize_02(name):
print(name)

# 多参数版
@pytest.mark.parametrize("name,word", get_data['person'])
def test_parametrize_02(name,word):
print(f'{name}'的口头禅是{word}')


本文共计223个文字,预计阅读时间需要1分钟。

如何使用Pytest结合yaml进行参数化测试?

1. 读取YAML文件(文件路径在关键点)

2.单参数版本

3.多参数版本

如何使用Pytest结合yaml进行参数化测试?

一、读取yaml(关键点在于文件的路径)

1、单参数版,多参数版

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project :Pytest
@File :read_data.py
@IDE :PyCharm
@Author :zhou
@Date :2022/8/6 19:05
"""
import os

import yaml

path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "data.yaml")


def read_data():
# 获取文件
f = open(path, encoding="utf-8")
# 读取文件内容
data = yaml.safe_load(f)
return data


get_data = read_data()
print(get_data)

二、parametrize使用yaml文件中的数据

# 单参数版
@pytest.mark.parametrize("name", get_data['person'])
def test_parametrize_02(name):
print(name)

# 多参数版
@pytest.mark.parametrize("name,word", get_data['person'])
def test_parametrize_02(name,word):
print(f'{name}'的口头禅是{word}')