zl程序教程

您现在的位置是:首页 >  其他

当前栏目

pytest + yaml 框架 -8.一个yaml 文件可以支持多个用例了

2023-02-19 12:20:25 时间

前言

一个yaml 文件中可以写多个用例,yaml 文件相当于py模块,每个用例相当于模块里面定义 pytest 的一个函数, 用例名称最好是test开头,如果不是test开头,也会帮你自动拼接成test开头的

pip 安装插件

pip install pytest-yaml-yoyo

yaml 文件写多个用例功能在 v1.0.6 版本上实现

基本用例执行

在pytest 用例中,我们可以在一个模块写多个函数式的用例,每个用例test开头,如下

import pytest

def test1():
    """用例1"""
    print("hello 111")

def test2():
    """用例2"""
    print("hello 222")

def test3():
    """用例3"""
    print("hello 333")

if __name__ == '__main__':
    pytest.main(['-s', 'test_sample.py'])

执行后会看到3个用例

collected 3 items

test_sample.py hello 111
.hello 222
.hello 333
.

=============== 3 passed in 0.01s ===========

根据以上pytest的基本运行原理,于是我们也可以在yaml文件中写出同等的效果

    test1:
        name: 用例1
        print: hello 11111

    test2:
        name: 用例2
        print: hello 22222

    test3:
        name: 用例3
        print: hello 3333

输入pytest 运行yaml 用例文件

(venv) D:\demo>pytest test_case.yml -s
=================================== test session starts ===================================
platform win32 -- Python 3.8.5, pytest-7.2.0, pluggy-1.0.0
collected 3 items                                                                          

test_case.yml hello 11111
.hello 22222
.hello 3333
.

==================================== 3 passed in 0.15s ====================================

可以看出执行效果是完全一样的

重新定义了yaml用例格式

为了框架的可扩展性,config 和 teststeps 都不是必须的了,当然以前的格式还是会兼容

    config:
        name: demo

    teststeps:
    -
      name: GET请求示例
      request:
        method: GET
        url: http://httpbin.org/get
      validate:
        - eq: [status_code, 200]

    test1:
        name: 用例1
        print: hello 11111

    test2:
        name: 用例2
        print: hello 22222

用例部分支持2种格式,可以是一个键值对格式

    test1:
        name: 用例1
        print: hello 11111

也可以是一个list


    test1:
     -
        name: 用例1
        print: hello 11111

如果一个用例有多个步骤需要执行,那么用例应该是一个list,会按顺序去执行

    config:
        name: demo


    test1:
        name: 用例1
        print: hello 11111

    test2:
    -
        name: get
        request:
            method: GET
            url: http://httpbin.org/get
        validate:
          - eq: [status_code, 200]

    -
        name: post
        request:
            method: POST
            url: http://httpbin.org/post
            json:
              username: test
              password: "123456"
        validate:
          - eq: [status_code, 200]

支持中文命名

用例的函数名称也可以使用中文命名了,这样更直观

config:
    name: demo

用例演示1:
    name: 用例1
    print: hello 11111

用例是多个步骤2:
-
    name: get
    request:
        method: GET
        url: http://httpbin.org/get
    validate:
      - eq: [status_code, 200]

-
    name: post
    request:
        method: POST
        url: http://httpbin.org/post
        json:
          username: test
          password: "123456"
    validate:
      - eq: [status_code, 200]

原有的用例规则不变,只是teststeps 不是必须的关键字,可以用其它的名称,也可以继续使用teststeps (为了兼容大家的使用习惯)