pytest使用yaml驱动参数的案例
时间: 2023-10-12 08:13:59 浏览: 107
以下是一个使用pytest和yaml驱动参数的简单测试案例:
假设我们要测试一个简单的计算器函数,接收两个参数并返回它们的和,我们可以使用yaml文件来定义测试数据和期望结果,如下所示:
```yaml
- args: [1, 2]
expected: 3
- args: [2, 3]
expected: 5
- args: [10, -5]
expected: 5
```
接下来,我们编写pytest测试用例,使用pyyaml库解析yaml文件中的数据,并将它们作为参数传递给测试函数,如下所示:
```python
import pytest
import yaml
from calculator import add # 假设计算器函数在calculator.py文件中定义
# 使用pytest.mark.parametrize装饰器来驱动参数化测试
@pytest.mark.parametrize('args, expected', yaml.safe_load(open('test_data.yaml')))
def test_add(args, expected):
assert add(*args) == expected
```
在上面的代码中,我们通过pytest.mark.parametrize装饰器将yaml文件中的测试数据和期望结果传递给test_add函数。在test_add函数中,我们使用assert语句检查计算器函数的返回值是否与期望结果相等。
这样,我们就可以使用pytest和yaml文件来驱动参数化测试,简化测试用例的编写和维护。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)