[TIP] Functions for tests instead of classes

Mark Sienkiewicz sienkiew at stsci.edu
Wed Mar 17 09:54:12 PDT 2010

Michael Foord wrote:
> On 15/03/2010 18:21, Mark Sienkiewicz wrote:
>> You could have a module full of friendly assert functions, but if you 
>> need a custom assert function for your object, you can still have 
>> one.  After all, if your test contains a special assertEqual, you are 
>> going to have to override the assertEqual in the base class -- i.e. 
>> you write your own anyway.
> What I mean is that the methods already access class (or instance) 
> state - so you would need extra parameters to your assert functions or 
> have to forgo that functionality.

It never occurred to me that anybody would do that.  Seriously, if you 
are comparing whether two things are equal, what _possible_ data could 
you need access to other than those two things? 

Well, the answer appears to be "other stuff that is defined in the test 
case object".  I would not design it that way, but I can see how you are 
constrained by backward compatibility.

> In terms of a programmers API I don't really see any win though. 
> Either you import *all* the assert functions, or you import the module 
> and use 'module.assert_equal'. You're not going to advocate "import *" 
> surely? :-)

If you also advocate against "import *", I then there will be at least 
two of us. :)

I generally value readability over speed, so I would use 
module.assert_equal(a,b).  Or, if I might call the module "assertions" 
and the function "equal" so you can write "assertions.equal(a,b)"

Using the "special object" that you mentioned some time ago, that could be

from unittest2 import assertions
# assertions is a TestCase object that contains no tests, but it is not 
in this namespace
# so no test runners will detect it when we run the tests in this file

def test() :

Mark S.

More information about the testing-in-python mailing list