pytest - ModuleNotFoundError - python 3.6.4
Asked Answered
B

0

3

I have a project with this layout:

├── MANIFEST.in
├── README.md
├── __init__.py
├── company
│   ├── __init__.py
│   ├── api
│   │   ├── __init__.py
│   │   ├── auth.py
│   │   ├── debug.py
│   │   ├── exceptions.py
│   │   ├── reporting.py
│   │   ├── rest.py
│   │   ├── soap.py
│   │   └── utils.py
│   ├── jinjaEnvironment.py
│   ├── sql
│   │   ├── __init__.py
│   │   ├── connection.py
│   │   └── sql_helper.py
│   └── templates
│       ├── __init__.py
│       ├── getUser.xml
│       ├── rest_write_custom_field.xml
│       └── setUser.xml
├── company.egg-info
├── requirements.txt
├── setup.py
└── tests
    ├── __init__.py
    └── test_api.py

with python -m unittest -v (launched from the project root folder), tests runs fine. I tried to install and use pytest, so far without success. As of nwo I tried:

  • pytest
  • python -m pytest -v

but I get the same error:

ImportError while importing test module '/Users/my.user/PycharmProjects/company/tests/test_api.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_api.py:22: in <module>
    from company.api import auth, reporting, exceptions as api_exceptions
E   ModuleNotFoundError: No module named 'company.api'

I also tried to modify sys.path with:

import sys

print(os.path.abspath("."))
sys.path.insert(0, os.path.abspath("."))
print(sys.path)

but I got the same results. Any help on this?

I'm using python 3.6.4 on OS X 10.13.4

Beulahbeuthel answered 8/4, 2018 at 22:13 Comment(11)
try adding a .. in front of the import module: from ..company.api .......Unprepared
it works but breaks python -m unittest: ValueError: attempted relative import beyond top-level packageBeulahbeuthel
more of the traceback available?Unprepared
Use pip install --editable . and then pytest (both from the directory which contains the setup.py file).Mawkish
@Mawkish same result: ValueError: attempted relative import beyond top-level packageBeulahbeuthel
@hoefling done. Same error as before. At the moment I solved it with this nasty thing: dpaste.com/11V5S1MBeulahbeuthel
Try removing company.egg-info dir.Forelady
@Forelady different exception this time: ImportError: attempted relative import with no known parent packageBeulahbeuthel
Delete the __init__.py file from tests subdir, it shouldn't be there. And wherever you put this sys.path.insert garbage, delete all that too. The correct command is simply pytest and the correct import path is company.api, as already seen in your traceback. Make sure pytest is installed in the same environment as your package ('.') and you are not accidentally using a pytest installed in the system site-packages.Mawkish
You might want to try to set the PYTHONPATH like PYTHONPATH=root_dir pytest ...Encrinite
@Mawkish has the right answer. Struggled with this for longer than I'd like to admit.Patrizia

© 2022 - 2024 — McMap. All rights reserved.