[TIP] Functions for tests instead of classes

Michael Foord fuzzyman at voidspace.org.uk
Thu Mar 4 11:38:44 PST 2010

On 04/03/2010 19:31, Mark Sienkiewicz wrote:
> Michael Foord wrote:
>> Hello all,
>> Some of you are *really* keen to use functions instead of classes for 
>> testing.
>> Attached is an example of one way of doing that using unittest2 and 
>> the load_tests protocol.
> Perhaps you could make this an intrinsic capability of unittest2, much 
> like nose and py.test recognize test functions natively.  If I 
> understand it correctly, the whole point of unittest2 is to implement 
> the operation "run all the tests in this file", so natively 
> recognizing test functions would be a nice idea.

I don't think it will get into core unittest, sorry. :-) The point of 
the exercise was to show how easy it is to provide using the new 
load_tests protocol.

> ( b.t.w.  I like that nose and py.test recognize test functions, but I 
> don't want their integrated test discovery.  I think it is an 
> _excellent_ design choice to separate discover (which finds files that 
> contain tests) from unittest2 (which runs the tests in a file). )
Unfortunately test discovery is already now in core unittest (and 
unittest2). You certainly don't have to use it though.

>> At the moment there are no assert functions (I may expand simpletest 
>> to include these at some point) so you can use assert statements, 
>> with the cost of the useful failure messages unless you construct 
>> them yourself.
> It never made sense to me that the assert functions in unittest are 
> attached to the TestCase object.  You could have a more generally 
> usable interface to the module if they were all free standing functions.
> Then, to retain compatibility with older versions of unittest, the 
> TestCase object can contain a bunch of trivial methods like:
>    def assertEqual(self, a, b) :
>       return assertEqual(a,b)
> This keeps all the capabilities that are in the current 
> implementation, but your[1] test functions get to the friendly 
> assertions for free.
I'm likely to do it the other way round - make the functions available 
in simpletest by providing bound methods from a TestCase instance...

All the best,


> Mark S.
> [1]  Ok, not _your_ test functions -- _my_ test functions. :)


READ CAREFULLY. By accepting and reading this email you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies (”BOGUS AGREEMENTS”) that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer.

More information about the testing-in-python mailing list