运行测试时看到ModuleNotFoundError

时间:2020-08-05 12:36:38

标签: python pytest

我的项目目录如下:

bin/
bin/module1/module1.py
bin/module1/settings.py 
bin/module1/helpers.py  --> This module does not have reference to bin/module1/settings.py
bin/module2/module2.py
bin/module2/settings.py
bin/module2/helpers.py --> This module has reference to bin/module2/settings.py
bin/tests/test_module1.py --> This test imports helpers from bin/module1/helpers.py
bin/tests/test_module2.py --> This test imports helpers from bin/module2/helpers.py
bin/tox.ini
bin/conftest.py
bin/setup.py

setup.py具有以下内容:

from setuptools import setup, find_packages

setup(
    name='my_project',
    version='0.0.1',
    description='Implement my_project',
    long_description='Implement my_project',
    author='my_name',
    author_email='a.my_name@my_domain.com',
    packages=find_packages(exclude=['tests*'])
)

我正在使用pytest。

当我运行test_module1.py时,它使用pytest标记引用了bin/module1/helpers.py,而bin/module1/helpers.py却没有导入到bin/module1/settings.py中。该测试运行得很好。

但是,当我使用pytest标记运行bin/tests/test_module2.py,并且bin/module2/helpers.py已导入到bin/module2/settings.py时,运行此测试时,我看到了ModuleNotFoundError: No module named 'settings' error

    import settings as settings
E   ModuleNotFoundError: No module named 'settings'

2 个答案:

答案 0 :(得分:0)

我知道的唯一方法就是改变
import settings as settings

import .settings as settings 编码愉快!

答案 1 :(得分:0)

使用SO链接已解决问题:Getting "ImportError: attempted relative import with no known parent package" when running from Python Interpreter

上方链接使用的方法1如下:

try:
    # Assume we're a sub-module in a package.
    from . import models
except ImportError:
    # Apparently no higher-level package has been imported, fall back to a local import.
    import models