This answer explains how to create test cases dynamically.
The answer's code:
class Tests(unittest.TestCase):
def check(self, i, j):
self.assertNotEquals(0, i-j)
for i in xrange(1, 4):
for j in xrange(2, 6):
def ch(i, j):
return lambda self: self.check(i, j)
setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))
I've tested and it works, but I can't just figure out how?
I have trouble understanding the lambda self:
magic in play here, mainly:
- Is the lambda used here to perform the exact opposite of
functools.partial()
(i.e. to create a wrapper function with one extra parameter that is not yet known) - Is
self
a meaningful keyword or wouldlambda spam
would work just as well? - What point is that lambda evaluated?
- How come the
.check()
is perfectly fine outside theclass
es scope? - How do you do this without lambda? - if I understand correctly, you should be able to do without
lambda
(not to mention that I agree with Guido and Alex that it is an eyesore and I want to do without :)