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?!