Python Unittest2 - avoid including a TestCase in discover()
I'm using unittest2
on Python2.5
to discover tests with unittest.TestLoader.discover
, like this:
suite = unittest2.loader.TestLoader().discover(test_path)
unittest2.TextTestRunner(verbosity=2,
resultclass=ColorTestResult).run(suite)
for some test_path
at the base of my project.
I've a base class that's extended and overloaded by numerous others, but I'd like to test that those derivatives do not have regressions. Let's call that base class A
and its derivates A1
, A2
, etc.
I'd like to create a unittest2.TestCase
base class that can be overloaded for each of the derivatives of A
. In other words, I'd like to have a hierarchy something like this:
class A:
pass
class A1(A):
pass
class UT(unittest2.TestCase):
target = A
class UT2(UT):
target = A1
Now the trick is that I'm making A
into an abstract class, and UT
will fail on virtually all of the test cases that would appropriately pass for UT2
, etc.
The simplest solution to me s开发者_StackOverflow社区eems to be to have unittest2's discover
somehow "skip" UT
. I would think this would be possible by putting it into a file other than one matching patter 'test*.py', though this seems not to be the case.
Are there any solutions to the above scenario that might be appropriate?
I'd be grateful for any thoughts and suggestions.
I'm guessing that the problem is that UT2 inherits from UT, so the module where UT2 is defined imports UT - and therefore makes it available in the module namespace. So even though discovery is not looking at the module where UT is defined, it can still find the TestCase in the UT2 module.
This is a general problem with having base TestCases that themselves define tests.
There are a few possibilities. One would be to expose UT via a function, so your module containing UT2 imports the function instead of UT directly:
class UT2(get_base_class()):
target = A1
Attributes on UT can be accessed using super().
Another, perhaps better, solution would be to make UT more abstract as well. You could omit the target on UT (as it seems to serve no purpose?) and have setUp call skipTest if there is no target (or if the target is A).
A third solution would be to have UT not inherit from TestCase, but use it as a mixin:
class UT2(TestCase, UT):
target = A1
精彩评论