使用pytest时候,我们知道要遵循一定命名规则,以 test_ 开头的函数名或者以 test_*.py 命名的文件会被默认收集,但这个原理你知道吗
见代码
pytest 自动收集测试函数的功能:
```python
import os
import importlib
import inspect
def collect_tests(start_dir):
test_functions = []
for root, dirs, files in os.walk(start_dir):
for file in files:
if file.startswith("test_") and file.endswith(".py"):
module_name = file[:-3] # Remove the .py extension
module_path = os.path.join(root, file)
# Dynamically import the module
module = importlib.import_module(module_name)
# Inspect all attributes in the module
for name, obj in inspect.getmembers(module):
if inspect.isfunction(obj) and name.startswith("test_"):
test_functions.append(obj)
return test_functions
# Example usage
test_functions = collect_tests("/path/to/tests_directory")
for test_func in test_functions:
print(f"Found test function: {test_func.__name__}")
# You can now execute the test functions as needed
```
在这个示例中,`collect_tests` 函数接受一个起始目录作为参数,递归搜索该目录及子目录下的以 `test_*.py` 命名的文件,并导入这些文件中的模块。然后,通过检查模块中的所有成员,筛选出以 `test_` 开头的函数,并将其存储在 `test_functions` 列表中。
最后,可以遍历 `test_functions` 列表,获取到所有收集到的测试函数,并执行相应的测试。
看代码os.walk和file.startswith("test_") and file.endswith(".py"):
这个示例代码展示了如何使用 importlib 模块和反射机制来实现测试函数的自动收集,并可以根据实际需求进行扩展和修改