0

Trying to write tests in Python3 with the folder structure

package/
    __init.py__
    Foo.py
    Bar.py
test/
    __init.py__
    test_Foo.py

Foo.py

import Bar

test_Foo.py

import Foo

Running python3 -m unittest results in No module named Foo

If I changed it to

from package import Foo

It will resolve, but in Foo.py it'll have the error No module named 'Bar'

If I change Foo.py to

from package import Bar

The test will run without error, but running python3 Foo.py will result in No module named 'package'

I've gone through various answers about this kind of problems, like this one

Running unittest with typical test directory structure

and this

Python3 import modules from folder to another folder

and none of them address this issue

1 Answer 1

0

your project root (and also the working directory!) need to be the parent of package.

Then every import will be in the form import package.module or from package import module.

if you run python packgae/Foo.py or python -m package.Foo it should work.

Also take a look at pypa - sample project to see the recommended Python project structure.

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

2 Comments

What makes a folder the project root? There's a parent folder to package and test but it just includes those two folders.
a project root is the folder below all your project related exists. it usually has file like setup.py, setup.cfg, requirments.txt and more. importing inside a project is easy and natural while outside requires installing like 3rd party packages or pythonpath manipulation.

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.