Reputation: 79595
I have a bunch of modules and for each module I have a unittest
based test. I want to define the main in each module to run its tests, but I get import errors because of import loops (specifically when I use from mymodule import myclass
in the test.
I suspect this is a solved problem, so - what should I put in my module's main to run its corresponding test?
Upvotes: 2
Views: 67
Reputation: 19329
If I understand you correctly, you've got a file (lets call it mymodule.py) that looks like this:
import unittest
from mymoduletests import MyModuleTests
class myclass(object):
def somefunction(self, x):
return x*x
if __name__ == '__main__':
unittest.main()
and a separate file (lets call it mymoduletests.py) that looks something like this:
import unittest
from mymodule import myclass
class MyModuleTests(unittest.TestCase):
def test_somefunction(self):
m = myclass()
self.assertEqual(4, m.somefunction(2))
If you run mymodule.py you get the following result:
Traceback (most recent call last):
File "mymodule.py", line 2, in <module>
from mymoduletests import MyModuleTests
File "/Users/srgerg/Desktop/p/mymoduletests.py", line 2, in <module>
from mymodule import myclass
File "/Users/srgerg/Desktop/p/mymodule.py", line 2, in <module>
from mymoduletests import MyModuleTests
ImportError: cannot import name MyModuleTests
However, if you change mymodule.py to this:
class myclass(object):
def somefunction(self, x):
return x*x
if __name__ == '__main__':
import unittest
from mymoduletests import MyModuleTests
unittest.main()
and then run it, you get:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Have I understood you correctly?
Upvotes: 4