pytest详细介绍和使用
时间: 2023-10-26 14:23:39 浏览: 35
pytest是一种基于Python语言的测试框架,它提供了丰富的功能和易于使用的语法,使得编写、运行和管理测试变得更加简单和高效。pytest支持自动发现测试文件和测试函数,并自动执行它们,同时还支持参数化、fixture、插件等高级功能。
下面是pytest的详细介绍和使用方法:
一、安装pytest
可以使用pip命令来安装pytest:
```python
pip install -U pytest
```
二、编写测试用例
pytest的测试用例文件必须以test_开头或者以_test结尾,例如:
```python
# test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 4
```
这是一个简单的测试用例,它测试了一个函数的返回值是否正确。使用assert语句来判断函数返回值是否符合预期。
三、运行测试用例
可以使用pytest命令来运行测试用例:
```python
pytest
```
pytest会自动发现所有以test_开头或者以_test结尾的测试文件,并执行其中的测试函数。如果测试通过,pytest会输出一条绿色的消息,否则会输出一条红色的消息。
四、使用fixture
fixture是pytest的一个高级功能,它可以在测试函数运行之前执行一些准备工作,比如创建数据库连接、初始化测试数据等。可以使用@pytest.fixture装饰器定义一个fixture,例如:
```python
# conftest.py
import pytest
import smtplib
@pytest.fixture(scope="module")
def smtp_connection():
smtp_connection = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
yield smtp_connection
smtp_connection.close()
# test_smtplib.py
def test_ehlo(smtp_connection):
response, msg = smtp_connection.ehlo()
assert response == 250
```
这个例子定义了一个smtp_connection的fixture,它在测试函数运行之前创建一个SMTP连接,并在测试函数运行之后关闭连接。测试函数可以使用smtp_connection这个fixture来获取SMTP连接,并进行测试。
五、使用参数化
pytest支持参数化测试,可以使用@pytest.mark.parametrize装饰器来定义多组输入和输出,例如:
```python
# test_parametrize.py
import pytest
@pytest.mark.parametrize("test_input,expected_output", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_eval(test_input, expected_output):
assert eval(test_input) == expected_output
```
这个例子定义了一个test_eval的测试函数,它使用了@pytest.mark.parametrize装饰器来定义多组输入和输出。pytest会自动运行每组输入和输出,如果测试通过,则会输出一条绿色的消息。
六、使用插件
pytest支持插件,可以通过安装不同的插件来扩展pytest的功能。可以使用pytest --help命令查看所有可用的插件。
以pytest-html插件为例,它可以生成一个HTML格式的测试报告。可以使用pip命令安装pytest-html插件:
```python
pip install pytest-html
```
安装完成后,可以使用pytest --html=report.html命令来生成测试报告,例如:
```python
pytest --html=report.html
```
这个命令会生成一个名为report.html的HTML文件,包含了测试结果和统计信息。测试报告可以在浏览器中打开查看。