-1

Hello Python Programmers

I'm getting a weird module import error during unittest. Not able to find the root cause. Here is how my directory structure looks like

Main_folder
   |
   |
   Module_x
       |  ABC.py
   |
   |
   Module_y
        | DEF.py
   |
   |
   test
       | unit_tests
             | test_ABC.py  

In test_ABC.py I'm importing the following

from Module_x import ABC

I get the error as "No module name Module_x"

I've created __init__.py file at each folder

I don't get any error if I use the same line from DEF.py

Please help if you're aware about why I am getting this issue?

I am using Python 3.5 Anaconda Distribution

Thanks

5
  • What is the working directory? print(os.getcwd()) Commented Jan 28, 2019 at 5:55
  • The cwd is main_folder Commented Jan 28, 2019 at 6:02
  • Try running the test from Main_folder like python test/unit_tests/test_ABC.py Commented Jan 28, 2019 at 7:11
  • @JRajan Did tried.. but same results Commented Jan 28, 2019 at 7:42
  • Then you need to add the working directory in the Python path, so that Python knows there are other modules that need to loaded. You can use the linked answer as a pointer to adding directories dynamically stackoverflow.com/a/8663119/690576 or use the below answer for adding it to global python path. Commented Jan 28, 2019 at 7:55

1 Answer 1

1

This is not a weird problem but a common one.

You can add your root into PYTHONPATH to solve this problem: PYTHONPATH=/path/to/project_root python test_ABC.py or something else similar.

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

3 Comments

Hi Sraw, I call it weird because I can access the same from DEF.py without coming to any path related issue? Any idea ?
The problem is how you run that DEF.py, I believe you run it under Main_folder while not run that test cases under Main_folder. It should be impossible that you can get Main_folder as os.getcwd() in your case. Or you should be able to find that module.
Yes you're right... The DEF.py called from a file in main_folder. If my tests are called from a file placed in main_folder it works

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.