pytest yaml文件随机值
时间: 2023-11-14 15:10:25 浏览: 104
可以使用 `pytest-randomly` 插件来生成随机值,并将其写入 yaml 文件中。
首先需要安装插件:
```
pip install pytest-randomly
```
然后在 `conftest.py` 文件中添加以下代码:
```python
import random
import yaml
import pytest
@pytest.fixture(scope="session")
def random_value():
return random.randint(1, 10)
@pytest.hookimpl(hookwrapper=True)
def pytest_generate_tests(metafunc):
if "random_value" in metafunc.fixturenames:
with open("test_data.yml", "r") as f:
data = yaml.safe_load(f)
metafunc.parametrize("random_value", [data["random_value"]])
yield
else:
yield
```
这里定义了一个 `random_value` 的 fixture,它会生成一个在 1 到 10 之间的随机整数。然后使用 `pytest_generate_tests` 钩子函数,读取 yaml 文件中的数据,并将 `random_value` 参数传递给测试函数。
最后在 yaml 文件中使用 `$random_value` 占位符来引用随机值:
```yaml
random_value: $random_value
```
在测试函数中就可以使用 `random_value` 参数了:
```python
def test_random_value(random_value):
assert random_value > 0 and random_value <= 10
```
阅读全文
相关推荐



















