1 pytest测试专题 - 1.3 测试用例发现规则
执行pytest
命令时,可以不输入参数,或者只输入文件名或者目录名,pytest
会自己扫描测试用例。那pytest
基于什么规则找到用例呢?
文件名
:满足文件名称为test_<something>.py
或 <something>_test.py
函数
:满足函数名为test_<something>
类
:满足类名为Test<Something>
测试用例的组织可以是:
- 文件 -> 函数(测试用例)
- 文件 -> 类 -> 函数(测试用例)
选择哪种组织方式,需要看用户的业务情况,如果测试用例很集中,且有公共的预置条件,可以尝试使用类封装的方式。
- 异常情况1:如果类名不满足规范,但成员函数满足规范,是否可以发现用例?
不可以!
文件:test_ch1_003.py
class TesClass():
def test_class_001(self):
assert 1 == 1
执行结果:
============================= test session starts =============================
platform win32 -- Python 3.13.1, pytest-8.3.4, pluggy-1.5.0 -- C:\Program Files\Python313\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.13.1', 'Platform': 'Windows-10-10.0.19045-SP0', 'Packages': {'pytest': '8.3.4', 'pluggy': '1.5.0'}, 'Plugins': {'check': '2.4.1', 'html': '4.1.1', 'metadata': '3.1.1', 'timeout': '2.3.1', 'xdist': '3.6.1'}}
rootdir: D:\TYYSOFT\Study\Python\pytest
configfile: pytest.ini
plugins: check-2.4.1, html-4.1.1, metadata-3.1.1, timeout-2.3.1, xdist-3.6.1
collecting ... collected 0 items
- Generated html report: file:///D:/TYYSOFT/Study/Python/pytest/tasks/report.html -
============================ no tests ran in 0.02s ============================
- 异常情况2:类名满足规范,但成员函数不满足规范,是否可以发现用例?
不可以!最终执行测试用例的本质是函数,函数名不满足规范无法执行。
对命名规范的总结:
作者声明:本文用于记录和分享作者的学习心得,可能有部分文字或示例来源自豆包AI,由于本人水平有限,难免存在表达错误,欢迎留言交流和指教!
Copyright © 2022~2025 All rights reserved.