在pytest下导入包时出错

时间:2018-02-07 11:16:07

标签: python pytest

在我的python代码中,我使用动态导入:

def load_class(path, class_str):
    """
    :param path: Function to load class dynamically
    :param class_str:
    :return:
    """
    module = importlib.import_module(path)
    return getattr(module, class_str)

我称这个函数为

class_name = "CL_ABC"
path = "test.test_framework.test_a_feature"
testclass = load_class(path, class_name)

我收到错误

ImportError: No module named test_framework.test_a_feature

我在具有unittest框架的文件中调用上面的代码。假设文件名是test1,如果我打电话为python test1它工作正常,但如果我将其称为pytest test1,我就会出错。

1 个答案:

答案 0 :(得分:0)

由于某些原因,pytest在sys.path中不包括当前目录。您可以看到,如果您在任何测试中打印该值。

这与普通的python会话(其中sys.path包含值'')不同。

要使导入工作在pytest中进行,您必须修改sys.path以包括模块的位置(但请确保仅在特定测试中进行此更改,以免产生副作用。