How to parameterize unittests
Steven D'Aprano
steve at pearwood.info
Fri Apr 15 05:10:20 EDT 2016
On Fri, 15 Apr 2016 06:20 pm, Antoon Pardon wrote:
>>>> class Test_MySubclassTree(Test_AVLTree):
>>>> tree = My_Subclass_Tree
>>> I see, that's going to be a lot of cut & pastes.
>>> Thanks.
>> Not really; the first class has all the tests, and the second one is
>> literally just those two lines. It overrides 'tree' (accessed inside
>> methods as 'self.tree'), and since all the tests are written to
>> instantiate self.tree, they are effectively parameterized.
>
> But the tests, at this moment, are not written to instantiate self.tree
> but to call avltree directly. So I have to rewrite these tests. That
> will IMO involve a lot of cut and paste.
*shrug*
I feel your pain, because I've had to go through exactly the same process.
If you have code which is not parameterized, and you want to parameterize
it, you have to refactor. Unit tests are no different from anything else.
I suggest that you handle it this way:
(1) Start with all your tests passing. If they're not passing, that will
make the process a lot harder. If there are any failing tests, temporarily
re-name them so that they don't run (test_foo to FIXME_test_foo, say), or
use the @unittest.skip decorator.
(2) Go through each TestCase class, and add a simple "tree = avltree" class
attribute to the class. Confirm that the tests still pass.
(3) In your editor, run a global Find and Replace "avltree -> self.tree".
You will need to inspect each one rather than do it automatically.
Obviously you need to avoid changing the "tree = avltree" class attribute,
and any import lines, but probably everything else should change.
(4) Run the tests again. Hopefully everything will work perfectly, and all
the tests will pass, but if not, fix any that have been broken by the
refactoring.
(5) Once all the tests pass again, the refactoring is complete, and you can
start subclassing your test classes with the new parameterized tree.
--
Steven
More information about the Python-list
mailing list