1
votes

I'd like to be able to test a function with a tuple from a set of fringe cases and normal values. For example, in testing a function that returns true when given three lengths that form a valid triangle, I'd have specific cases, negative numbers, small numbers, large numbers, values close-to being overflowed, etcetera. Then generating combinations of these values, with or without repetition, to get a set of test data.

> (inf,0,-1), (5,10,1000), (10,5,5), (0,-1,5), (1000,inf,inf),
> 
> ...
1

1 Answers

1
votes

With the brand new Python 2.6, you have a standard solution with the itertools module that returns the Cartesian product of iterables :

import itertools

print list(itertools.product([1,2,3], [4,5,6]))
   [(1, 4), (1, 5), (1, 6),
   (2, 4), (2, 5), (2, 6),
   (3, 4), (3, 5), (3, 6)]

You can provide a "repeat" argument to perform the product with an iterable and itself:

print list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]

You can also tweak something with combinations as well :

print list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]

And if order matters, there are permutations :

print list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
   (2, 1), (2, 3), (2, 4),
   (3, 1), (3, 2), (3, 4),
   (4, 1), (4, 2), (4, 3)]

Of course all that cool stuff don't exactly do the same thing, but you can use them in a way or another to solve you problem.

Just remember that you can convert a tuple or a list to a set and vice versa using list(), tuple() and set().