繁体   English   中英

如何从__init__.py或conftest.py自动获取模块名称?

[英]How can I get module name automatically from __init__.py or conftest.py?

我在测试包中运行多个测试,我想在包中打印每个模块名称,而不重复代码。 所以,我想在__init__.pyconftest.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作为参数。

让它工作的最佳方法是什么?

编辑:

最后,我在这里解释了:

conftest.py

@pytest.fixture(scope='module', autouse=True)
def module_name(request):
    return request.node.name

带有测试函数的测试文件的示例。 同样需要添加到每个文件和每个功能:

checker1.py

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。

  • expected_resactual_res从excel文件熊猫Dataframes。
  • loglogging包中的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM