python自动化测试之Pytest框架之YAML详解以及Parametrize数据驱动!

一、YAML详解

YAML是一种数据类型,它能够和JSON数据相互转化,它本身也是有很多数据类型可以满足我们接口 的参数类型,扩展名可以是.yml或.yaml

作用:

1.全局配置文件
基础路径,数据库信息,账号信息,日志格式,报告名称等。
2.编写测试用例
接口自动化测试用例

语法结构:

1.区分大小写 Name name
2.通过缩进来表示层级关系。使用空格。
3.可以使用#作为注释
4.字符串一般默认可以不使用引号,必须时才使用。

数据类型:

基本类型:

整数
浮点数
字符串(当有特殊字符时:双引号不会被转义,其它的都会加一个转义符\)
布尔值
null
日期时间

复杂类型:

对象(字典):键: (空格) 值

数组(列表):它是使用 一组横线"-" 开头。

数据类型强转:【鸡肋】

!!int
!!str

引用:

引用:&建立锚点(标记),*使用锚点,<<表示合并到当前数据。

二、YAML的读写和清空

安装:
pip install pyyaml
读写和清空

python 复制代码
#读取 
def read_yaml(yaml_path): 
 with open(yaml_path,encoding="utf-8",mode="r") as f: 
 value = yaml.safe_load(f) 
 return value 

#写入 
def write_yaml(yaml_path,data): 
 with open(yaml_path,encoding="utf-8",mode="w") as f: 
 yaml.safe_dump(data, stream=f,allow_unicode=True) 

# #清空 
def clear_yaml(yaml_path): 
 with open(yaml_path, encoding="utf-8", mode="w") as f: 
 pass

三、pytest的parametrize结合yaml实现数据驱动

python 复制代码
@pytest.mark.parametrize("参数名","参数值(可以是list或tuple)")

方法一:【不常用】

方法二:【常用】

python 复制代码
class TestApi:
    @pytest.mark.parametrize("caseinfo", read_yaml("../testcases/test_api.yaml"))
    def test_login2(self,caseinfo):
        print("登录测试用例:%s " % caseinfo)
python 复制代码
-
  username: admin
  password: "001"
-
  username: admin2
  password: "002"
-
  username: admin3
  password: "003"


多个用例

python 复制代码
-
  feature: 正例:接口所属模块
  story: 接口名称
  title: 用例标题
  request:
    method: get
    url: http://www.baidu.com
    headers: 请求头
    params: 请求参数
  validate: null

-
  feature: 反例:接口所属模块
  story: 接口名称
  title: 用例标题
  request:
    method: get
    url: http://www.baidu.com
    headers: 请求头
    params: 请求参数
  validate: null
相关推荐
春风又。2 天前
接口自动化——初识pytest
python·测试工具·自动化·pytest
南部余额2 天前
playwright解决重复登录问题,通过pytest夹具自动读取storage_state用户状态信息
前端·爬虫·python·ui·pytest·pylawright
小码哥说测试4 天前
接口自动化进阶 —— Pytest全局配置pytest.ini文件详解!
自动化测试·软件测试·测试工具·自动化·pytest·测试工程师
天才测试猿5 天前
Python常用自动化测试框架—Pytest
自动化测试·软件测试·python·功能测试·测试工具·测试用例·pytest
Rhys..5 天前
2、pytest核心功能(进阶用法)
开发语言·python·pytest
一只天蝎的晋升之路7 天前
Python中常用的测试框架-pytest和unittest
开发语言·python·pytest
明月与玄武7 天前
pytest-xdist 进行高效并行自动化测试
pytest·pytest-xdist·进行高效并行自动化测试
测试笔记(自看)7 天前
Python+Requests+Pytest+YAML+Allure接口自动化框架
python·自动化·pytest·allure
活跃家族7 天前
Jsonpath使用
python·pytest
Rhys..8 天前
4、pytest常用插件
pytest