1

I know this should be easy and I know that other people online have asked this question, but I feel like I understand all of their answers and the concepts, yet my import is still throwing errors.

I have this directory structure

root/myPackage/
root/tests/test_1.py

in test_1.py I have:

import myPackage
...

I am running on the command line from the root:

$ pytest tests OR python tests/test_1.py

...just anything to get this script to run really. I've used pytest and have run python scripts before

and I keep getting the

No module named 'myPackage' error

I thought if I run the test from the root I would still be able to access myPackage... this is really contradicting my previous understanding and the internet... send help if you know why I'm getting importing errors.

ALSO, when I take the test_1.py out of the tests directory and run it from the root it works without errors. So this structure works

root/myPackage/
root/test_1.py
11
  • Is this Python 2? If so, myPackage/__init__.py must exist. Commented Aug 27, 2019 at 17:27
  • @JohnGordon it's python3 and it myPackage/__init__.py exists Commented Aug 27, 2019 at 17:27
  • How about root/tests/__init__.py? Commented Aug 27, 2019 at 17:32
  • @Beethoven's7th why would tests need an init. It's just a folder. I eventually want to just be able to call pytest tests from the root Commented Aug 27, 2019 at 17:33
  • 1
    Would you be able to share the contents of your setup.py file? (and setup.cfg if exists) Commented Aug 27, 2019 at 17:44

1 Answer 1

1

Recreating your project from the information provided, I was able to reproduce your error and fixed it by including an __init__.py file under the tests directory.

Here's my project structure:

root/myPackage

  • __init__.py

  • module.py

root/tests

  • __init__.py

  • test_1.py

That should allow you to run pytest tests successfully.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm confused on why this works. What does putting an _init_.py in the tests folder do exactly? Tests isn't a package, so why put the _init_.py?
Without the init file, pytest just thinks your test file is a script and it will run it in isolation. In that context, it isn't really relevant that myPackage and tests share the root directory because pytest doesn't know it exists inside a package. Including the setup.py and using setuptools to register your package with your python environment made it possible to import your package from anywhere regardless of directory context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.