要使用Python的pytest编写测试,首先确保已经安装了pytest库。如果尚未安装,可以使用以下命令进行安装:
pip install pytest
接下来,创建一个简单的Python项目结构,例如:
my_project/ ├── main.py └── test/ └── test_main.py
在main.py
中,编写一个简单的函数,我们将在测试文件中对其进行测试:
# main.py def add(a, b): return a + b
现在,在test/test_main.py
文件中编写测试用例。使用pytest
模块作为测试文件的名称前缀,并使用test_
作为函数名的前缀。在这个例子中,我们将编写一个测试函数test_add
来测试main.py
中的add
函数:
# test/test_main.py import pytest from main import add def test_add(): assert add(1, 2) == 3 assert add(-1, 1) == 0 assert add(0, 0) == 0
在这个测试函数中,我们使用了assert
语句来检查add
函数的输出是否与预期相符。如果输出不符合预期,测试将失败。
要运行测试,打开终端,导航到项目根目录(包含main.py
和test
文件夹的目录),然后运行以下命令:
pytest
pytest将自动发现并运行所有测试用例。如果所有测试都通过,你将看到类似以下的输出:
=========================== test session starts ============================ ... collected 1 item test/test_main.py . [100%] ============================ 1 passed in 0.03s =============================
这表明你已经成功地使用pytest编写并运行了一个简单的测试用例。你可以继续为main.py
中的其他函数编写更多的测试用例。