0

I am writing a small unittest for my method move(). The application is running but when I do python -m unittest app.test.test_move_items, it fails with the following error:

ImportError: Failed to import test module: test_move
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
  File "/Users/daniel/app/test/test_move.py", line 13, in <module>
    from app.move_items import move
  File "/Users/daniel/apps/app/move.py", line 29, in <module>
    from helpers.calculator import determine_move_amount
ModuleNotFoundError: No module named 'helpers'

If i do python app/move.py, the output is correct.

The folder structure is as follows:

  app
    helpers
      |-calculator.py
    move_items.py
    test
      |-test_move_items.py

move_items.py

from helpers.calculator import determine_move_amount

def move(list_of_items, move_by):
  pass

There is init.py file in app and the test directory as well.

Erick
  • 63
  • 4
  • You probably need to do a `from app.helpers.calculator import determine_move_amount`, as your top level namespace is called `app` based on what we can infer from the error message (as `app.move_items` could be imported, it follows that `app.helpers` could also be imported, along with everything underneath there). – metatoaster Jul 04 '22 at 07:23
  • Can you add the imports from calculator.py? It looks like you are trying to import helpers there which cannot be found. – Christian Jul 04 '22 at 07:24
  • Alternatively, you are trying to do a [relative import](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time?rq=1). In any case, you also don't appear to have a proper package set up for your project, which makes juggling imports rather difficult. You may wish to [package your project](https://packaging.python.org/en/latest/tutorials/packaging-projects/) so you will have proper package names that may then be imported correctly anywhere within the environment. – metatoaster Jul 04 '22 at 07:27
  • @metatoaster for your first input, yes doing app. import works for test but it fails on 'app' module not found when I run the code. Let me see the packaging solution. – Erick Jul 04 '22 at 07:34
  • Try taking the `test_move_items.py` file out of the `test` folder. – Alexander Jul 04 '22 at 08:19
  • @alexpdev i already tried but thanks. Time to give it up. – Erick Jul 04 '22 at 08:41
  • @Erick do you have an __init__.py both in your test directory and in your app directory? – jon doe Jul 04 '22 at 09:31

0 Answers0