【问题标题】:ModuleNotFoundError seen when running test运行测试时看到 ModuleNotFoundError
【发布时间】:2020-08-05 12:36:38
【问题描述】:

我有一个项目目录如下:

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'

【问题讨论】:

    标签: python pytest


    【解决方案1】:

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

    import .settings as settings 编码愉快!

    【讨论】:

    • 谢谢,但import .settings as settings 抛出错误。所以,我改成from .settings import *,它起作用了。这在作为测试运行时工作正常,即bin/tests/test_module2.py 但是,当我运行 python 模块bin/module2/module2.py 我得到ImportError: attempted relative import with no known parent package
    【解决方案2】:

    问题已通过 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
    

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 2020-06-04
      • 1970-01-01
      相关资源
      最近更新 更多