![](/img/trans.png)
[英]Pytest ImportError and ModuleNotFoundError when running test from a sub directory
[英]ModuleNotFoundError seen when running test
我有一个项目目录如下:
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'
我知道的唯一方法是改变import settings as settings
至
import.settings as settings
编码愉快!
使用 SO 链接解决了该问题: 从 Python 解释器运行时出现“ImportError:尝试使用没有已知父包的相对导入”
使用上述链接中的方法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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.