2

Short question

I can find many resources and instructions on how to get unittest to work, and I can reproduce them on my computer. However, they all are "dummy" examples in the sense that they have a flat file tree instead of the file tree typically found in actual python projects. I can't seem to find a satisfactory solution for unit testing in an actual python project.

My problem boils down to : how do I run the test cases? Should I put a main (as in __main__) testing script somewhere? Do I call python3 myPackage/test/test_aModule.py? Do I call python3 -m myPackage.test.test_aModule?


More details

From what I understand from this answer, this is what my file tree should look like:

MyProject
├── myPackage
│   ├── aModule.py
│   ├── anotherModule.py
│   ├── __init__.py
│   └── test
│       ├── __init__.py
│       ├── test_aModule.py
│       └── test_anotherModule.py
├── README.md
└── setup.py

I have two modules, the first called "aModule"

# aModule.py
class MyClass:
    def methodToTest(self, a, b):
        return a + b

and the second called "anotherModule"

# anotherModule.py
def functionToTest(a, b):
    return a * b

Both modules are being unit-tested. "aModule" is unit-tested by "test_aModule"

# test_aModule.py
import unittest
from aModule import MyClass

myObject = MyClass()
print( "myObject(a,b) = ", myObject.methodToTest(1,2) )
print( "myObject(a,b) = ", functionToTest(1,2) )

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

and "anotherModule" is unit-tested by "test_anotherModule"

# test_anotherModule.py
import unittest
from anotherModule import functionToTest

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

What is the best way to run those tests?

Besides, following this answer, invoking python -m myPackage.test.test_aModule from MyProject/ outputs No module named 'aModule'. This question suggests to add the current directory to sys.path. However I find this solution quite surprising: am I supposed to add all python projects that I have on my computer to sys.path just so that I can unittest them?!

Community
  • 1
  • 1
Gael Lorieul
  • 3,006
  • 4
  • 25
  • 50
  • 2
    Take a look at nosetests http://nose.readthedocs.io/en/latest/ – gipsy May 16 '17 at 19:05
  • @gipsy what is the stage of [adoption](https://en.wikipedia.org/wiki/Early_adopter) of nose? Is it the new standard? Or is it still on the rise? – Gael Lorieul May 16 '17 at 19:17
  • I believe nose is pretty widely used. We use it at work. – gipsy May 16 '17 at 20:13
  • I believe you need to be more explicit in your importing within your unittest. `from aModule import MyClass` should be `from myPackage.aModule import MyClass`. – greggmi May 22 '17 at 19:29

0 Answers0