函数的注册和使用

如果要在用例中使用动态的内容(例如:当前时间、SQL查询、加密解密等),就需要调用函数来进行实现,这个听起来比变量更加棘手。

好在Python中一切皆对象,函数和变量在某种层面是一类的,区别只是函数支持在名字后使用 () 符合进行 调用


下面是一个简单的例子:

a = print  # 创建a变量
a(123)  # 对a变量进行调用

如果我们将Python函数看作是变量,添加到全局变量中,再加上 () 符号调用,那么就可以实现在用例 调用Python函数

pytest-yaml-sanmu支持在在yaml用例中注册和使用Python变量,也支持在使用Python函数。

注册Python类型变量

通过pytest.ini注册

pytest-yaml-samu 在指定全局变量文件时,也支持py文件。

只不过对py文件中有一个特殊要求: 变量应该定义在指定的类 ``PytestYaml`` 中

此类名可通过配置进行自定义

先创建创建包含 类名 PytestYaml 的python文件:

# yaml_funcs.py
import time


class PytestYaml:
    a = 100   # 数字型变量
    b = "abc" # 字符型变量

    def time(self):  # 可调用型变量
        return time.time()

接着修改配置

[pyetst]

yaml_global_variable_paths =
  ; 加载python格式全局变量
  yaml_funcs.py

这样就添加了三个Python类型变量到pytest-yaml-samu中:

  • a:数字

  • b:字符串

  • time:函数(可调用对象)

通过conftest.py注册

此外,pytest-yaml-samu提供了 add_globals 函数和对应的 item.add_globals() item.add_locals() 方法:

  • add_globals() / item.add_globals() — 添加全局变量或函数

  • item.add_locals() — 在步骤中向当前用例动态注入变量,供后续步骤使用


我们以 添加全局变量 为例,代码示例如下

# confetst.py
import time
from pytest_yaml import add_globals  # 导入便捷

# 也支持在 hook 中通过 item.add_globals() 添加
# 也支持通过 item.add_locals() 向当前用例注入变量

add_globals(abc="123", bbc=321) # 关键字参数的方式添加

add_globals(**{    # 字典解包的方式添加
    "print": print,
    "len": len,
})

代码执行之后,会添加4个对象,分别是:

  • abc:字符串"123"

  • bbc:数字 123

  • print:函数

  • len: 函数

自 2.0.0 版本弃用: add_locals() 已弃用。用例级变量请直接在 YAML 中声明 vars 字段,或通过 fixture 提供。

注意:

  1. 变量的优先级比fixture低,变量名与fixture名相同时无法使用

使用Python类型变量

对象的使用方式,取决于对象的类型:例如函数可以加括号调用,列表可以通过索引取值

使用字符串和数字

字符串和数字属于字面量,可以直接用输出,所以通过 ${变量名} 语法即可直接使用:

name: 在yaml中使用变量

steps:
  - request:
      method: get
      url: https://www.baidu.com/?abc=${abc}

  - request:
      method: get
      url: https://www.baidu.com/?abc=${abc}

执行结果:略

使用函数和方法

函数、方法属于可调用类型,在变量名后加 () 即可。

如果函数有参数,可以在 () 中传递参数

# test_globals_functions.yaml

name: 在yaml中使用函数

steps:
  - request:
      method: get
      url: https://www.baidu.com/?time=${time()}

  - request:
      method: get
      url: https://www.baidu.com/?len=${len([1,2,3])}

执行结果如下:

(.venv) C:\demo\pytest-yaml-demo>pytest -vs
============================= test session starts ==============================
platform win32 -- Python 3.12.0, pytest-8.2.2, pluggy-1.5.0
cachedir: .pytest_cache
rootdir: C:\demo\pytest-yaml-demo
configfile: pytest.ini
plugins: yaml-1.1.0
collected 1 item

tests/function/test_globals_functions.yaml::在yaml中使用函数 url=https://www.baidu.com/?time=1735198928.925052
url=https://www.baidu.com/?len=3
PASSED

============================== 1 passed in 0.20s ===============================

函数的返回值会填充yaml文件中 ${} 符号所在的位置 ,务必根据需要为函数设置正确的返回值。