43

My unittest folder is organized this way.

.
|-- import
|   |-- import.kc
|   |-- import.kh
|   `-- import_test.py
|-- module
|   |-- module.kc
|   |-- module.kh
|   `-- module_test.py
`-- test.py

I'd want to simply run test.py to run each of my *_test.py using the unittest Python module.

Currently, my test.py contains

#!/usr/bin/env python

import unittest

if __name__ == "__main__":
    suite = unittest.TestLoader().discover('.', pattern = "*_test.py")
    unittest.TextTestRunner(verbosity=2).run(suite)

The python documentation says that it should automatically discover my test in the subfolders. But it does not.

At the moment, it only outputs

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

I'm sure it is not a problem with my *_test.py file, because when I move them into the root directory, it works fine.. What am I doing wrong?

Zoe
  • 27,060
  • 21
  • 118
  • 148
tomahh
  • 13,441
  • 3
  • 49
  • 70

3 Answers3

55

Add __init__.py in the import and module directories.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • It worked by just touching the `__init__.py` file, thanks you. Can you explain me why I have to do this ? And is there another solution wich ? Because I am working with other people, and I would like tests to be the easiest way possible to create. – tomahh Oct 01 '12 at 13:37
  • 3
    This is an artifact of the way test discovery is implemented. Essentially, each directory that contains a test has to be importable as a Python module. See the [docs](http://docs.python.org/2/library/unittest.html#test-discovery) for more information. – Collin M Sep 28 '13 at 01:09
  • 1
    From [documentation](https://docs.python.org/3.7/library/unittest.html#test-discovery) it says that namespace packages should be supported since 3.4, but I found that `__init__.py` is still needed. Why? – Franklin Yu Aug 24 '19 at 14:53
  • Struggled for a while till I found this. Thank you. Another nuance of the Python world. – Sau001 Dec 27 '20 at 23:25
  • in my scenario, my test file (`test.py`) was also in a sub directory. I needed to add `__init__.py` into that folder as well as `import` and `module` folders and then it worked. – Paul P M Feb 08 '23 at 07:03
4

Consider using nose instead of the vanilla unittest module, if you are able to switch. You won't need to mess around with your own test.py file or anything; a run of nosetests will find and run all your tests.

jbowes
  • 4,062
  • 22
  • 38
-1

python -m unittest tests/**_test.py

Lane
  • 4,682
  • 1
  • 36
  • 20