51

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
Bonifacio2
  • 3,405
  • 6
  • 34
  • 54
Bee
  • 1,187
  • 1
  • 8
  • 16
  • 3
    do you have an `__init__.py` file in the `tests` directory to make them discoverable as part of the module? – gold_cy Jun 26 '19 at 21:12
  • Nope I don't, I never had the `__init.py__` file earlier in the same `tests` directory but the tests worked fine. – Bee Jun 26 '19 at 21:20
  • 1
    @aws_apprentice - I put an empty `__init__.py` file in the tests folder and surprisingly the unit test works now. I wonder why? Can you give a brief explanation about this behavior if you could? If you post it as an answer, I will accept it. Thanks – Bee Jun 26 '19 at 21:25
  • 1
    https://stackoverflow.com/questions/448271/what-is-init-py-for will explain better than I can – gold_cy Jun 26 '19 at 21:30
  • 1
    I am having this error too, \_\_init\_\_.py is **not needed** in Python 3.3+ unless you need to run an installation script in that directory – boardtc Jan 29 '21 at 18:08

6 Answers6

54

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.

Bee
  • 1,187
  • 1
  • 8
  • 16
15

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".

k_o_
  • 5,143
  • 1
  • 34
  • 43
  • If running tests in a folder, for the target put the name of the folder, eg. `unit` – Voy Aug 14 '23 at 16:26
3

The reason is some library is using the package name already, see: this stack overflow question about reserved package names

To understand the poblem: rename the tests package to tests_package package. (test is also a reserved package name)

Before:

MWE -|
     |- tests -|
               |- test_file.py

After:

MWE -|
     |- tests_package -|
                       |- test_file.py

(Since python 3.3 the __init__.py is not required.)

Then running python -m unittest tests_package\test_file.py

Using a "venv" would solve it for tests package name but not for test

Probably an even more pythonic solution would be to not have your project run in "root" by giving it a unique module name, releasing you from the requirement to have a package name unused by python libraries for the tests directory. example:

GitFolderOfProject -|
                    |- MWE -|
                            |- tests -|
                                      |- test_file.py

Then running the tests from the "GitFolderOfProject" as python -m unittest MWE\tests\test_file.py

Eaton Emmerich
  • 452
  • 4
  • 17
2

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.

tjheslin1
  • 1,378
  • 6
  • 19
  • 36
0

This is a simple setup magic.

First things first - in PyCharm:

  1. Right-click on folder (in the project tree) with tests - mark this folder as "tests folder".

  2. Right-click on folder (in the project tree) with sources - mark this folder as "sources folder".

  3. Remove bad "Run configuration" (or don't remove, you choose).

  4. Right click on on folder with tests (already marked as the "tests folder") - choose "run".

This is all. Really simple. Logical. It took me about an hour to find it out.

0

I had a similar issue with Pycharm 2023.1 (detailed version below)

GitFolderOfProject -| |- src-| |- utests -| |- test_file.py

I could run the test from command line from the /src folder

python -m unittest discover  .\utest\ 

However on the IDE , I got ModuleNotFound.

In addition to changing Script path to Module Path I had to change the working directory of /utest folder to /src . I was able to run tests from the IDE.

PyCharm 2023.1.3 (Community Edition) Build #PC-231.9161.41, built on June 20, 2023 Runtime version: 17.0.7+10-b829.16 amd64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. Windows 10.0 GC: G1 Young Generation, G1 Old Generation Memory: 2012M Cores: 16 Non-Bundled Plugins: net.seesharpsoft.intellij.plugins.csv (3.2.0-231)

tguclu
  • 689
  • 3
  • 10
  • 25