New submission from Éric Piel:

Since Python 2.6 there is the notion if abstract class (ABC). It could be 
useful to use it for test cases, but unittest doesn't support it. Typically, 
I'd like to test a bunch of classes which all should behave similarly (at least 
for some cases). So I'd like to have one abstract class containing many test 
cases, and a separate real tests classes which inherit from this abstract class.

Unfortunately, for now unittest tries to instantiate the abstract class, which 
fails. 

Note that I'm not the only one thinking of this, here is a mention of the same 
idea on stack overflow:
http://stackoverflow.com/questions/4566910/abstract-test-case-using-python-unittest

Attached are two small examples of test cases. test_abs.py shows what I think 
is a good usage of ABC, with unittest. It fails to run with this error:
TypeError: Can't instantiate abstract class VirtualTest with abstract methods 
important_num
fake_abc.py is typically what people end up doing for using abstract classes 
with unittests (that's what people used to do before ABC exists). It does work, 
but it's not really beautiful as VirtualTest uses self.assertGreater() and 
self.important_num which are not explicitly part of the class.

My guess is that the following patch to Lib/unittest/loader.py should be enough 
(but it's untested):
diff -r a2128cb22372 Lib/unittest/loader.py
--- a/Lib/unittest/loader.py    Thu Mar 21 23:04:45 2013 -0500
+++ b/Lib/unittest/loader.py    Fri Mar 22 12:22:46 2013 +0100
@@ -6,6 +6,7 @@
 import traceback
 import types
 import functools
+import inspect
 
 from fnmatch import fnmatch
 
@@ -74,7 +75,8 @@
         tests = []
         for name in dir(module):
             obj = getattr(module, name)
-            if isinstance(obj, type) and issubclass(obj, case.TestCase):
+            if (isinstance(obj, type) and issubclass(obj, case.TestCase) and
+                not inspect.isabstract(test_class)):
                 tests.append(self.loadTestsFromTestCase(obj))
 
         load_tests = getattr(module, 'load_tests', None)

----------
components: Library (Lib)
files: test_abc.py
messages: 184959
nosy: Éric.Piel
priority: normal
severity: normal
status: open
title: unittest should not try to run abstract classes
type: behavior
versions: Python 2.7, Python 3.3, Python 3.4
Added file: http://bugs.python.org/file29544/test_abc.py

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue17519>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to