import pytest from common.osyaml import read_yaml db = read_yaml("./db.yaml") @pytest.mark.parametrize("db",db) def test_db(db): print(db)
时间: 2024-04-15 09:30:27 浏览: 22
你的代码看起来很不错!你使用了 pytest 库来运行测试,并使用了 read_yaml 函数从 db.yaml 文件中读取参数。然后,你使用 pytest.mark.parametrize 装饰器来为测试函数提供参数化的功能。
注意,在使用 pytest.mark.parametrize 装饰器时,你需要确保参数的名称与测试函数中的参数名称一致。在你的代码中,你将参数名称都设置为了 "db",因此在测试函数中也需要使用相同的参数名称。
当你运行这个测试时,pytest 会为每个从 db.yaml 文件中读取的参数值执行一次测试函数。每次测试运行时,该参数的值将传递给测试函数,并打印出来。
如果你的 db.yaml 文件类似于以下格式:
```yaml
- db_value1
- db_value2
- db_value3
```
那么你的测试函数将会被执行三次,分别传入 db_value1、db_value2 和 db_value3 作为参数。每次执行测试函数时,都会打印出相应的参数值。
希望这可以帮助你进行基于 YAML 文件的参数化测试!如果你还有其他问题,请随时提问。
相关问题
@pytest.mark.parametrize("caseinfo", YamlUtil('./requestdata/login.yaml').read_yaml()) 这样写对吗
这是一个使用 pytest.mark.parametrize 装饰器的 Python 代码片段,它从 './requestdata/login.yaml' 文件中读取 YAML 格式的数据并将其传递给测试用例。根据提供的信息,这段代码看起来是正确的。
pytest.mark.parametrize与yaml如何使用
pytest.mark.parametrize 和 YAML 都可以用于参数化测试,下面分别介绍它们的使用方法:
1. pytest.mark.parametrize
`pytest.mark.parametrize` 可以用于为测试函数提供参数化输入,其语法如下:
```python
import pytest
@pytest.mark.parametrize("arg1, arg2, expected_output", [
(1, 2, 3),
(10, 20, 30),
(-1, 1, 0),
])
def test_addition(arg1, arg2, expected_output):
assert arg1 + arg2 == expected_output
```
在上面的例子中,`test_addition` 函数被参数化了三次,每次传入的参数分别是 `(1, 2, 3)`,`(10, 20, 30)` 和 `(-1, 1, 0)`。 pytest 会自动运行这个函数三次,并检查每次运行的结果是否符合预期。
2. YAML
YAML 是一种轻量级的数据序列化格式,可以用于存储测试数据。下面是一个使用 YAML 的例子:
```yaml
- name: addition_test
args:
arg1: 1
arg2: 2
expected_output: 3
- name: subtraction_test
args:
arg1: 10
arg2: 5
expected_output: 5
```
在上面的例子中,我们定义了两个测试用例,一个是加法测试,一个是减法测试。每个测试用例包含一个名称和一组参数,这些参数会被传递给测试函数进行测试。
在测试函数中,我们可以使用 PyYAML 库读取 YAML 文件,并将其转换为 Python 对象,然后遍历每个测试用例并运行测试函数。下面是一个示例代码:
```python
import yaml
import pytest
def load_test_data(file_path):
with open(file_path) as f:
test_data = yaml.safe_load(f)
return test_data
def test_addition():
test_data = load_test_data("test_data.yaml")
for test_case in test_data:
args = test_case["args"]
expected_output = args.pop("expected_output")
assert sum(args.values()) == expected_output
def test_subtraction():
test_data = load_test_data("test_data.yaml")
for test_case in test_data:
args = test_case["args"]
expected_output = args.pop("expected_output")
assert args["arg1"] - args["arg2"] == expected_output
```
在上面的代码中,`load_test_data` 函数用于读取 YAML 文件并将其转换为 Python 对象,`test_addition` 和 `test_subtraction` 函数分别用于测试加法和减法。在每个测试函数中,我们先调用 `load_test_data` 函数加载测试数据,然后遍历每个测试用例并运行测试函数。