Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Unit test module throws "ModuleNotFoundError: No module named 'tests.test_file'"

I'm trying to execute a test case for a project I've been working on. I used to successfully execute the unit tests earlier but it errors out now. I know for sure that there have been no updates to any libraries or change in the Path. I tried to look at the source code and figure out why it's erroring out but no luck yet. Any help on this would be appreciated.

Python version - 3.7.1

Sample Code below

import unittest

class MyTestCase(unittest.TestCase):

def test_dummy(self):
    self.assertEqual(2+2,4)

I used the following command in cmd to execute the test.

C:\Users\Yadada\Desktop\repo\mwe\mwe>python -m unittest tests\test_file.py

My folder structure is

 MWE -|
      |_tests - |
                |_test_file.py

The expected output is the test being executing successfully because it's a straightforward one. But I end up getting the following error

strclass
ERROR: test_file (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_file
Traceback (most recent call last):
  File "C:\Users\yadada\AppData\Local\Continuum\anaconda3\lib\unittest\loader.py", line 156, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'tests.test_file'


----------------------------------------------------------------------
Ran 1 test in 0.001s
like image 660
Bee Avatar asked Jun 26 '19 21:06

Bee


Video Answer


3 Answers

The issue got resolved after placing an empty __init__.py file in the tests folder.

For a better explanation about why it worked, refer to What is __init__.py for?

Thanks, @aws_apprentice for the help.

like image 94
Bee Avatar answered Oct 09 '22 01:10

Bee


With PyCharm 2020.2 the "ModuleNotFoundError: No module named" error can also happen when running a unit test in a sub folder which imports a module from a parent folder under test. PyCharm is taking by default the script path for executing the test which fails e.g. with this error:

ModuleNotFoundError: No module named '/home/foobar/projects/foo/mypythonproject/moduleundertest'

The solution is to edit the run configuration of the unit test and change the Unittests Target from "Script path" to "Module name".

like image 22
k_o_ Avatar answered Oct 09 '22 02:10

k_o_


The solution for me was to add:

if __name__ == '__main__':
    unittest.main()

to the bottom of my test file.

I was then able to run:

python -m <test-file>

Removing the .py suffix from my python -m command was also required:

See this answer for details.

like image 1
tjheslin1 Avatar answered Oct 09 '22 00:10

tjheslin1