简体   繁体   中英

ImportError with unittest and multiples modules

I have a project with the following structure:

/
├── test
│   ├── __init__.py
│   └── test_do_stuff.py
└── my_package
    ├── do_stuff.py
    ├── helpers
    │   ├── my_helper.py
    │   └── __init__.py
    ├── __init__.py
    └── main_do_stuff.py

When running the tests I get ImportError: No module named 'helpers'

When the test imports my_package.do_stuff , it tries to import helpers.my_helper

  • The command to run the tests is python3 -m unittest (Is this a correct way?)

  • All the __init__.py are empty.

test_do_stuff.py:

import unittest
import my_package.do_stuff
# ...

do_stuff.py:

import helpers.my_helper
# ...

main_do_stuff.py:

import do_stuff

python3 my_package/main_do_stuff.py works. The main calls the same functions as the test.

Does the problem comes from the way I launch the tests?

Or my structure?

I'm trying to find a solution that doesn't involve messing too much with the path or writing a lot of code just to run the tests. (There should be a simple way to have the tests separated from the code doesn't it?)

The problem is the use of implicit relative imports:

import helpers.my_helper

should be

import my_package.helpers.my_helper

Your problem is that python doesn't accept your directory hieracy. Just put the test files under a root directory ( /everything for example ) and it will work fine. Your directorys could look like this:

/
└── everything
    ├── __init__.py
    ├── test_do_stuff.py
    └── my_package
        ├── do_stuff.py
        ├── helpers
        │   ├── my_helper.py
        │   └── __init__.py
        ├── __init__.py
        └── main_do_stuff.py

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