简体   繁体   中英

ModuleNotFoundError seen when running test

I have a project directory as below:

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 has below contents:

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*'])
)

I am using pytest.

When I run test_module1.py , which refers bin/module1/helpers.py using pytest markers and bin/module1/helpers.py does not have import to bin/module1/settings.py . The test run perfectly fine.

But, when I run bin/tests/test_module2.py using pytest markers, and bin/module2/helpers.py has import to bin/module2/settings.py , when this test runs I see the ModuleNotFoundError: No module named 'settings' error

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

The only method i know is to change
import settings as settings
to
import.settings as settings Happy coding!

The issue was resolved using SO link: Getting "ImportError: attempted relative import with no known parent package" when running from Python Interpreter

Used Approach 1 from above link which is as below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM