Pytest入门系列之pytest的安装和基本使用

Pytest入门系列之pytest的安装和基本使用

在 Python 生态中,pytest 是一个强大且流行的测试框架,提供简洁的语法和丰富的插件支持。

pytest 的安装

pytest 的安装方法

1
pip install pytest

安装完毕后,可以使用以下命令检查pytest版本:

1
pytest --version

pytest 入门案例

创建 test_sample.py 文件,并添加以下代码:

1
2
3
4
5
def test_addition():
assert 1 + 1 == 2

def test_subtraction():
assert 5 - 3 == 2

运行测试:

1
pytest test_sample.py

结果:

可以看到我们是运行了两个测试用例,目前均是通过的情况

pytest 命名规则

虽然我们看到可以正常的运行文件,但是如果你的文件或者函数亦或者类命名规则不符合要求,则无法运行到你想要的文件或者函数亦或者类,那么一起来看一下pytest 文件和函数以及类的命名规则吧!

pytest 文件夹命名规则

测试目录可以是任何名称,但推荐使用 tests/,test_cases/ 等常见命名方式。
如果目录包含 __init__.py,它会被当作 Python 包,可能会影响 pytest 的测试发现机制,因此 不推荐在 tests/ 目录下使用 __init__.py

示例的目录结构:

1
2
3
4
5
6
7
8
9
project_root/
├── src/
│ ├── app.py
│ ├── utils.py
├── tests/
│ ├── test_math.py
│ ├── test_utils.py
│ ├── sub_tests/
│ │ ├── test_submodule.py

pytest 文件命名规则

pytest 默认会识别以下命名格式的测试文件:

文件名必须以 test_ 开头,或以 _test 结尾,例如:
✅ test_example.py
✅ example_test.py
❌ example.py(不会被 pytest 识别为测试文件)

但是如果文件不符合默认规则,可以在 pytest.ini文件中自定义测试文件匹配规则,例如:

1
2
3
# pytest.ini
[pytest]
python_files = check_*.py test_*.py *_test.py

上述配置允许 pytest 识别 check_xxx.py 作为测试文件。

pytest 函数命名规则

pytest 默认识别的测试函数格式如下:

函数名必须以 test_ 开头,例如:
✅ def test_addition():
❌ def addition_test():(不会被 pytest 识别)

1
2
3
# test_math.py
def test_addition():
assert 1 + 1 == 2

pytest 类的命名规则

类名必须以 Test 开头,注意:但不能包含 __init__ 方法,否则 pytest 不会识别。

例如:
✅ class TestMathOperations:
❌ class MathTests:(不会被 pytest 识别)

1
2
3
4
# test_class.py
class TestMath:
def test_addition(self):
assert 2 + 2 == 4

pytest 自定义测试发现规则

如果想让 pytest 识别不同的文件或函数命名,可以在 pytest.ini 中配置:

1
2
3
4
[pytest]
python_files = check_*.py # 允许文件名以 check_ 开头
python_classes = Check* # 允许类名以 Check 开头
python_functions = verify_* # 允许函数名以 verify_ 开头

此时,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/ 无需特别配置

Pytest入门系列之pytest的安装和基本使用
https://dreamshao.github.io/2025/03/19/pytest入门系列1/
作者
Yun Shao
发布于
2025年3月19日
许可协议