Python ImportError:使用pytest时无法导入名称

Python ImportError:使用pytest时无法导入名称,python,unit-testing,pytest,Python,Unit Testing,Pytest,我正在用python创建一个目录结构,类似于: module_root ├── __init__.py ├── module_a │   ├── __init__.py │   ├── local_module_a.py │   └── tests │   ├── context.py │   └── test_local_module_a.py ├── module_b │   └── tests │   └── context.py ├── tests │   ├──

我正在用python创建一个目录结构,类似于:

module_root
├── __init__.py
├── module_a
│   ├── __init__.py
│   ├── local_module_a.py
│   └── tests
│       ├── context.py
│       └── test_local_module_a.py
├── module_b
│   └── tests
│       └── context.py
├── tests
│   ├── context.py
│   └── test_this_module_will_be_exported.py
├── this_module_will_be_exported.py
└── this_module_will_not_be_exported.py
每个模块都有自己的测试文件夹和测试。一旦Python没有在调用文件
import
的目录中搜索模块,每个测试目录都有一个名为
context.py
的文件,该文件类似于:

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from this_module_will_be_exported import ThisClassWillBeExported
然后,在每个测试文件中,我使用以下导入语句:

from context import ThisClassWillBeExported
当我只有一个
test
目录和一个
context.py
时,一切正常,但当我添加更多测试时(如上面目录树中所述),
pytest
执行返回以下错误

ImportError while importing test module 'path/to/module_root/tests/test_this_module_will_be_exported.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
module_root/tests/test_this_module_will_be_exported.py:1: in <module>
    from context import ThisClassWillBeExported
E   ImportError: cannot import name 'ThisClassWillBeExported'
导入测试模块'path/to/module\u root/tests/test\u时导入错误此模块将被导出.py'。 提示:确保您的测试模块/包具有有效的Python名称。 回溯: 模块根/tests/test\u此模块将被导出。py:1:in 从上下文导入将导出此类 E ImportError:无法导入名称“ThisClassWillBeExported” 当我将
module\u root/module\u a/tests/context.py
的名称更改为
module\u root/module\u a/tests/\u context.py
(例如),测试工作得很好。因此,我知道我可以简单地将所有
context.py
更改为不同的名称,但我希望保留它们的名称以避免更多的工作

所以我需要社区的帮助,有没有办法保持
context.py
name并解决这个问题


谢谢。:)

首先,您只需将根目录添加到
PYTHONPATH
而不是所有上下文文件

其次,如果要从同一文件夹导入上下文文件,请尝试使用相对路径

from .context import ThisClassWillBeExported

第三,确保所有上下文文件都有要导入的变量。

这可能是因为您将具有相同名称的类导入到当前工作区。也许你应该试试完整的路径;导入module_a.tests.context,而不是从module import类导入。我在运行脚本之前设置了PYTHONPATH,它可以正常工作。谢谢你的回答。:)