Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2019-06-26 21:06:11

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
Questioner
Bee
Viewed
0
Bee 2021-02-06 04:21:31

The issue got solved 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.