Pytest入门系列之pytest的安装和基本使用
Pytest入门系列之pytest的安装和基本使用
在 Python 生态中,pytest 是一个强大且流行的测试框架,提供简洁的语法和丰富的插件支持。
pytest 的安装
pytest 的安装方法
1 |
|
安装完毕后,可以使用以下命令检查pytest版本:
1 |
|
pytest 入门案例
创建 test_sample.py 文件,并添加以下代码:
1 |
|
运行测试:
1 |
|
结果:

可以看到我们是运行了两个测试用例,目前均是通过的情况
pytest 命名规则
虽然我们看到可以正常的运行文件,但是如果你的文件或者函数亦或者类命名规则不符合要求,则无法运行到你想要的文件或者函数亦或者类,那么一起来看一下pytest 文件和函数以及类的命名规则吧!
pytest 文件夹命名规则
测试目录可以是任何名称,但推荐使用 tests/,test_cases/ 等常见命名方式。
如果目录包含 __init__.py
,它会被当作 Python 包,可能会影响 pytest 的测试发现机制,因此 不推荐在 tests/ 目录下使用 __init__.py
。
示例的目录结构:
1 |
|
pytest 文件命名规则
pytest 默认会识别以下命名格式的测试文件:
文件名必须以 test_ 开头,或以 _test 结尾,例如:
✅ test_example.py
✅ example_test.py
❌ example.py(不会被 pytest 识别为测试文件)
但是如果文件不符合默认规则,可以在 pytest.ini文件中自定义测试文件匹配规则,例如:
1 |
|
上述配置允许 pytest 识别 check_xxx.py 作为测试文件。
pytest 函数命名规则
pytest 默认识别的测试函数格式如下:
函数名必须以 test_ 开头,例如:
✅ def test_addition():
❌ def addition_test():(不会被 pytest 识别)
1 |
|
pytest 类的命名规则
类名必须以 Test 开头,注意:但不能包含 __init__
方法,否则 pytest 不会识别。
例如:
✅ class TestMathOperations:
❌ class MathTests:(不会被 pytest 识别)
1 |
|
pytest 自定义测试发现规则
如果想让 pytest 识别不同的文件或函数命名,可以在 pytest.ini 中配置:
1 |
|
此时,pytest 也会识别以下文件和函数:
check_example.py
class CheckOperations:
def verify_addition():
总结
pytest 文件命名规则总结
规则 | 默认格式 | 可自定义配置 |
---|---|---|
测试文件 | test_*.py 或 *_test.py |
python_files = check_*.py |
测试函数 | test_* |
python_functions = verify_* |
测试类 | Test* |
python_classes = Check* |
测试目录 | 任何名称(推荐 tests/ ) |
无需特别配置 |