[英]How can I get module name automatically from __init__.py or conftest.py?
我在測試包中運行多個測試,我想在包中打印每個模塊名稱,而不重復代碼。 所以,我想在__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中使用一個fixture,比如:
@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
fixture。
logging
包中的Logger
對象 在每個模塊(checker1,checker2,checker3,conftest.py)中,在main函數中執行
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.