#16835: update PEP 399 idiom to make it compatible with unittest test discovery.

This commit is contained in:
Ezio Melotti 2013-01-04 22:23:50 +02:00
parent facc0c00cc
commit b5b2b3f196
1 changed files with 18 additions and 17 deletions

View File

@ -8,7 +8,7 @@ Type: Informational
Content-Type: text/x-rst Content-Type: text/x-rst
Created: 04-Apr-2011 Created: 04-Apr-2011
Python-Version: 3.3 Python-Version: 3.3
Post-History: 04-Apr-2011, 12-Apr-2011, 17-Jul-2011, 15-Aug-2011 Post-History: 04-Apr-2011, 12-Apr-2011, 17-Jul-2011, 15-Aug-2011, 01-Jan-2013
Abstract Abstract
======== ========
@ -124,7 +124,7 @@ C accelerated versions of a module, a basic idiom can be followed::
py_heapq = import_fresh_module('heapq', blocked=['_heapq']) py_heapq = import_fresh_module('heapq', blocked=['_heapq'])
class ExampleTest(unittest.TestCase): class ExampleTest:
def test_heappop_exc_for_non_MutableSequence(self): def test_heappop_exc_for_non_MutableSequence(self):
# Raise TypeError when heap is not a # Raise TypeError when heap is not a
@ -136,34 +136,35 @@ C accelerated versions of a module, a basic idiom can be followed::
return 0 return 0
heap = Spam() heap = Spam()
self.assertFalse(isinstance(heap, self.assertIsInstance(heap, collections.abc.MutableSequence)
collections.abc.MutableSequence))
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
self.heapq.heappop(heap) self.heapq.heappop(heap)
class AcceleratedExampleTest(ExampleTest): class PyExampleTest(ExampleTest, unittest.TestCase):
"""Test using the accelerated code."""
heapq = c_heapq
class PyExampleTest(ExampleTest):
"""Test with just the pure Python code.""" """Test with just the pure Python code."""
heapq = py_heapq heapq = py_heapq
def test_main(): @unittest.skipUnless(c_heapq, 'requires the C _heapq module')
run_unittest(AcceleratedExampleTest, PyExampleTest) class CExampleTest(ExampleTest, unittest.TestCase):
"""Test using the accelerated code."""
heapq = c_heapq
if __name__ == '__main__': if __name__ == '__main__':
test_main() unittest.main()
The test module defines a base class (``ExampleTest``) with test methods
that access the ``heapq`` module through a ``self.heapq`` class attribute,
and two subclasses that set this attribute to either the Python or the C
version of the module. Note that only the two subclasses inherit from
``unittest.TestCase`` -- this prevents the ``ExampleTest`` class from
being detected as a ``TestCase`` subclass by ``unittest`` test discovery.
A ``skipUnless`` decorator can be added to the class that tests the C code
in order to have these tests skipped when the C module is not available.
If this test were to provide extensive coverage for If this test were to provide extensive coverage for
``heapq.heappop()`` in the pure Python implementation then the ``heapq.heappop()`` in the pure Python implementation then the
accelerated C code would be allowed to be added to CPython's standard accelerated C code would be allowed to be added to CPython's standard