unittest.TestCase, lambda and __getitem__

Roy Smith roy at panix.com
Mon Sep 13 15:51:46 CEST 2004


Steven Bethard <steven.bethard at gmail.com> wrote:
> self.assertRaises(ValueError, lambda: obj[index])
> 
> Presumably, I could write this as:
> 
> self.assertRaises(ValueError, obj.__getitem__, index)

I'm with you, I don't like the idea of calling __getitem__ directly, 
because you're not testing what you want to test; you're testing 
something one step removed.  Yes, it's a small step, but the idea in 
unit testing is to test as small a thing as possible.

I think you need to just create a little function and call it:

def tryIndex (object, index):
   return obj [index]

self.assertRaises (ValueError, tryIndex, object, index)

Another possibility would be:

self.assertRaises (ValueError, eval ("object [index]"))

>From a readability/understandability standpoint, I think I like the eval 
version better.



More information about the Python-list mailing list