[TIP] Functions for tests instead of classes

Pekka Klärck peke at iki.fi
Mon Mar 15 10:46:06 PDT 2010


2010/3/4 Mark Sienkiewicz <sienkiew at stsci.edu>:
>
> 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.

I've never understood this either. It has always annoyed to me to
write `self.assertEquals` when `assert_equals` would be shorter (and
PEP-8 compatible but that's another story). The biggest reason for
having asserts as a function in a separate module is that the same
asserts could be used by different testing tools. I know everyone can
implement simple `assert_equals`, but implementing cool features like
showing only diffs when comparing large strings or nicely formatting
differences in dicts is much harder. It would be awesome if we had
"de-facto asserts" in a separate module, preferably in the standard
library.

I've never understood what was the original design decision to add
asserts as methods of the unittest.TestCase. Python's unittest is a
direct port of JUnit 3, which actually has a separate Assert class,
with static assert methods, that is then extended by TestCase.
Combining these two classes in the Python port is, IMHO, a design
smell because it adds too much responsibilities for a single class. A
Pythonic solution would have been implementing those static methods as
functions from the beginning.

> 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)

Yep, keeping backwards compatibility would be trivial. Are there any
good reasons not to do this?

Cheers,
    .peke
-- 
Agile Tester/Developer/Consultant :: http://eliga.fi
Lead Developer of Robot Framework :: http://robotframework.org



More information about the testing-in-python mailing list