我正在测试包中运行多个测试,并且我想在不重复代码的情况下打印包中的每个模块名称。
因此,我想向__init__.py
或conftest.py
插入一些代码,这些代码将为我提供执行模块的名称。
假设我的测试模块称为:checker1,checker2等...
我的目录结构是这样的:
tests_dir/
├── __init__.py
├── conftest.py
├── checker1
├── checker2
└── checker3
因此,我在__init__.py
内尝试插入:
def module_name():
return os.path.splitext(__file__)[0]
但是当我调用它时,它仍然会从每个文件中给我__init__.py
。
我还尝试在conftest.py中使用固定装置,例如:
@pytest.fixture(scope='module')
def module_name(request):
return request.node.name
但是似乎我仍然需要在每个模块中定义一个函数来获取module_name
作为参数。
使它生效的最佳方法是什么?
最后,我的解释如下:
@pytest.fixture(scope='module', autouse=True)
def module_name(request):
return request.node.name
具有测试功能的测试文件的示例。需要向每个文件和每个功能添加相同的内容:
from conftest import *
def test_columns(expected_res, actual_res, module_name):
expected_cols = expected_res.columns
actual_cols = actual_res.columns
val = expected_cols.difference(actual_cols) # verify all expected cols are in actual_cols
if not val.empty:
log.error('[{}]: Expected columns are missing: {}'.format(module_name, val.values))
assert val.empty
请注意我在函数参数中添加的module_name
固定装置。
Logger
包中的logging
对象答案 0 :(得分:0)
在每个模块(checker1,checker2,checker3,conftest.py)的主要功能中,执行
print(__name__)
__init__.py
文件导入这些程序包时,应打印模块名称。
根据您的评论,您也许可以修改__init__.py
文件中的行为以进行本地导入。
__init.py__
import sys, os
sys.path.append(os.path.split(__file__)[0])
def my_import(module):
print("Module name is {}".format(module))
exec("import {}".format(module))
testerfn.py
print(__name__)
print("Test")
目录结构
tests_dir/
├── __init__.py
└── testerfn.py
测试命令
import tests_dir
tests_dir.my_import("testerfn")