Unittest testing assert*() calls rather than methods?

Roy Smith roy at panix.com
Wed Sep 28 20:49:24 EDT 2011


In article <4e83b8e0$0$29972$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> If you are writing loops inside tests, you might find this anecdote useful:
> 
> http://mail.python.org/pipermail/python-list/2011-April/1270640.html

On the other hand, the best test is one that gets written.  I will often 
write tests that I know do not meet the usual standards of purity and 
wholesomeness.  Here's a real-life example:

    for artist in artists:
        name = artist['name']
        self.assertIsInstance(name, unicode)
        name = name.lower()
        # Due to fuzzy matching, it's not strictly guaranteed that the 
        # following assertion is true, but it works in this case.  
        self.assertTrue(name.startswith(term), (name, term))

Could I have written the test without the loop?  Probably.  Would it 
have been a better test?  I guess, at some level, probably.  And, of 
course, the idea of a "not strictly guaranteed" assertion is probably 
enough to make me lose my Unit Tester's Guild Secret Decoder Ring 
forever :-)

But, the test was quick and easy to write, and provides value.  I could 
have spent twice as long writing a better test, and it would have 
provided a little more value, but certainly not double.  More 
importantly, had I spent the extra time writing the better test, I might 
have not had enough time to write all the other tests I wrote that day.

Sometimes good enough is good enough.



More information about the Python-list mailing list