pytest 参数化和confest
时间: 2023-12-01 12:41:50 浏览: 41
pytest是一个功能强大的Python测试框架,支持参数化测试和共享fixture。其中,参数化测试可以通过pytest.mark.parametrize装饰器实现,而共享fixture可以通过conftest.py文件实现。
参数化测试可以让我们在一次测试中运行多个测试用例,而不必编写多个测试函数。具体实现方法如下:
1.在测试函数上使用@pytest.mark.parametrize装饰器,指定参数名和参数值列表。
2.在测试函数中使用参数名作为参数,运行测试用例。
示例代码如下:
```python
import pytest
@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 54)])
def test_eval(test_input, expected):
assert eval(test_input) == expected
```
上述代码中,我们使用@pytest.mark.parametrize装饰器指定了两个参数test_input和expected,并传入了三组参数值。在测试函数test_eval中,我们使用这两个参数运行了三个测试用例。
共享fixture可以让我们在多个测试函数中共享相同的测试数据和测试环境。具体实现方法如下:
1.在conftest.py文件中定义fixture函数。
2.在测试函数中使用@pytest.fixture装饰器,指定fixture函数名称。
示例代码如下:
```python
# conftest.py
import pytest
@pytest.fixture
def login():
username = "testuser"
password = "123456"
print("登录成功")
return username, password
# test_sample.py
def test_case1(login):
print(f"测试用例1使用账号{login[0]}登录")
def test_case2(login):
print(f"测试用例2使用账号{login[0]}登录")
```
上述代码中,我们在conftest.py文件中定义了一个名为login的fixture函数,用于模拟用户登录操作。在测试函数test_case1和test_case2中,我们使用@pytest.fixture装饰器指定了login函数,并在测试函数中使用login参数获取登录账号信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)