pytest测试框架3

pytest测试框架–yaml

yaml 文件使用

查看 yaml 文件
pycharm
txt 记事本
读取 yaml 文件
安装:pip install pyyaml
方法:yaml.safe_load(f)
方法:yaml.safe_dump(f)

import yaml
file_path = './my.yaml'
with open(file_path, 'r', encoding='utf-8') as f:
    data = yaml.safe_load(f)

目录结构

data 目录:存放 yaml 数据文件
func 目录:存放被测函数文件
testcase 目录:存放测试用例文件

被测对象:operation.py

# operation.py 文件内容
def my_add(x, y):
    result = x + y
    return result

测试用例:test_add.py

# test_add.py 文件内容
class TestWithYAML:
  @pytest.mark.parametrize('x,y,expected', [[1, 1, 2]])
  def test_add(self, x, y, expected):
    assert my_add(int(x), int(y)) == int(expected)

测试数据:data.yaml

# data.yaml 文件内容
-
  - 1
  - 1
  - 2
-
  - 3
  - 6
  - 9
-
  - 100
  - 200
  - 300

Pytest 数据驱动结合 yaml 文件

# 读取yaml文件
def get_yaml():
    """
    获取json数据
    :return: 返回数据的结构:[[1, 1, 2], [3, 6, 9], [100, 200, 300]]
    """
    with open('../datas/data.yaml', 'r') as f:
        data = yaml.safe_load(f)
        return data