接口自动化测试中的yaml的数据驱动

该代码示例展示了如何使用Python的pytest框架进行数据驱动测试,参数化来自yaml文件的数据。Test_Login类中包含了三个测试方法,分别使用了直接传入的参数、硬编码的参数对以及从yaml文件读取的测试用例数据。Yamlutil类提供了读取和写入yaml文件的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pytest
from api_pytest.common.yaml_util import Yamlutil
class Test_Login:

    @pytest.mark.parametrize('args',['肖战','王一博','陈情令'])
    def test_login(self,args):
        print(args)

    @pytest.mark.parametrize('name,age',[['肖战',30],['路飞',16]])
    def test_plan(self,name,age):
        print(name,age)

    @pytest.mark.parametrize('caseinfo',Yamlutil().read_testcases_yaml('../data_yaml/user_pas.yaml'))
    def test_get_usr(self,caseinfo):
        print(caseinfo)

if __name__=="__main__":
    pytest.Test_Login()

其中yaml文件读取代码:

import os
import yaml
from api_pytest.controller.log import loger

class Yamlutil():
    def read_extract_yaml(self,key):
        # 打开当前工作目录下的extract.yaml文件,以只读模式打开
        with open(os.getcwd()+'/extract.yaml', mode='r', encoding='utf-8') as file:
            value = yaml.load(stream=file,Loader=yaml.FullLoader)
            loger.info("读取yaml文件中"+key)
            return value[key];

    def write_extra_yaml(self,data):
        with open(os.getcwd()+'/extract.yaml', mode='a',encoding='utf-8') as file:
            yaml.dump(data=data,stream=file,allow_unicode=True)
            loger.info("写入yaml文件中"+data)


    def clear_extract_yaml(self):
        with open(os.getcwd()+'/extract.yaml', mode='w',encoding='utf-8') as file:
            file.truncate()
            loger.info("清空yaml数据")

    def read_testcases_yaml(self,yaml_name):
        # 打开当前工作目录下的extract.yaml文件,以只读模式打开
        with open(yaml_name, mode='r', encoding='utf-8') as file:
            value = yaml.load(stream=file,Loader=yaml.FullLoader)
            loger.info("读取yaml文件中")
            return value;



if __name__=="__main__":
    data={"key8n":"肖战"}
    Yamlutil().write_extra_yaml(data)
    a=Yamlutil().read_extract_yaml("key5n")
    print(a)

注意哦:读取文件的路径不要搞错了。后续还可能会修改。

数据驱动还有Excel文件,后续更新

补昨天的代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值