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

Elle H
  • 11,837
  • 7
  • 39
  • 42

1 Answers1

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.

Lior Cohen
  • 5,570
  • 2
  • 14
  • 30
  • What makes a folder the project root? There's a parent folder to `package` and `test` but it just includes those two folders. – Elle H Oct 25 '19 at 17:15
  • 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. – Lior Cohen Oct 25 '19 at 19:13