用python+pytest 写一段 excel驱动结合yaml参数化
时间: 2024-03-09 13:11:10 浏览: 22
当然可以!下面是一个示例代码,演示了如何使用 Python 和 pytest 进行 Excel 驱动的测试,并结合 YAML 参数化。
首先,确保已经安装了以下库:
- `openpyxl` 用于读取 Excel 文件
- `pytest` 用于运行测试用例
- `PyYAML` 用于解析 YAML 文件
接下来,我们需要准备一个 Excel 文件,其中包含测试数据和预期结果。假设 Excel 文件名为 `testdata.xlsx`,工作表名为 `TestCases`,数据如下:
| Test Case | Input 1 | Input 2 | Expected Result |
|-----------|---------|---------|-----------------|
| Test 1 | 2 | 3 | 5 |
| Test 2 | 4 | 6 | 10 |
然后,创建一个名为 `test_excel.py` 的 Python 文件,其中包含以下代码:
```python
import openpyxl
import pytest
import yaml
def read_test_data(file_name, sheet_name):
workbook = openpyxl.load_workbook(file_name)
sheet = workbook[sheet_name]
test_data = []
for row in sheet.iter_rows(min_row=2, values_only=True):
test_data.append(row)
workbook.close()
return test_data
def test_excel_data():
test_data = read_test_data('testdata.xlsx', 'TestCases')
for data in test_data:
input_1, input_2, expected_result = data
# 在这里执行你的测试逻辑
result = int(input_1) + int(input_2)
assert result == expected_result
def load_yaml(file_name):
with open(file_name, 'r') as file:
yaml_data = yaml.safe_load(file)
return yaml_data
@pytest.mark.parametrize('test_input', load_yaml('parameters.yaml'))
def test_yaml_parameterization(test_input):
# 在这里执行你的测试逻辑
result = test_input * 2
assert result == test_input * 2
```
在这个示例代码中,我们定义了两个测试函数:`test_excel_data` 和 `test_yaml_parameterization`。其中,`test_excel_data` 函数从 Excel 文件中读取测试数据,并使用这些数据执行测试逻辑。`test_yaml_parameterization` 函数从 YAML 文件中加载参数化数据,并使用这些数据执行测试逻辑。
最后,我们还需要创建一个名为 `parameters.yaml` 的 YAML 文件,其中包含参数化的数据:
```yaml
- 2
- 4
- 6
- 8
```
接下来,在命令行中运行以下命令来运行测试:
```shell
pytest test_excel.py
```
这样,pytest 将会自动运行测试用例,并根据 Excel 文件和 YAML 文件中的数据进行参数化。
希望这个示例代码对你有帮助!如果你有任何问题,请随时提问。