[TIP] py.test: How to define a test function with two or more parametrized arguments?

Stefano Lattarini stefano.lattarini at gmail.com
Sat Mar 20 17:03:21 PDT 2010


At Saturday 20 March 2010, Benjamin Peterson <benjamin at python.org> 
wrote:
> 2010/3/20 Stefano Lattarini <stefano.lattarini at gmail.com>:
> > Hello everybody.
> >
> > I want to make it clear first that I'm a newbie when it comes to
> > py.test, and I still don't understand test parametrization and
> > funcargs very well, so please forgive me if this is a stupid or
> > badly formulated question.
> >
> > Also, you might found it useful to know that I'm using python 2.5
> > and python 3.1 on Debian GNU/Linux, and that my py.test's version
> > is 1.2.1.
> >
> > My question is: there is a way to define a test function with two
> > or more parametrized arguments (provided by a
> > `pytest_generate_tests' hook), in a way that forces the test
> > function to run with *all possible combinations* of those
> > parametrized tests?
> >
> > An example might help to clarify the matter.
> >
> > I tried this:
> >
> >  def pytest_generate_tests(metafunc):
> >      if "an_even_number" in metafunc.funcargnames:
> >          for e in (0, 2, 4, 6):
> >              metafunc.addcall(funcargs={'an_even_number': e})
> >      if "an_odd_number" in metafunc.funcargnames:
> >          for o in (1, 3, 5, 7):
> >              metafunc.addcall(funcargs={'an_odd_number': o})
> >
> >  def test_with_multiple_parametrized_args(an_even_number,
> > an_odd_number): assert (an_even_number + an_odd_number) % 2 == 1
> >
> > expecting 16 tests to be run, one for each couple (x, y) with  x
> > = 0, 2, 4, 6 and  y = 1, 3, 5, 7.
> 
> The is problem you only provided one funcarg at a time, so the call
> ended up trying to request the other one! A nested loop should work
> better. :)
> 
Hello Benjamin.  Thanks for your answer: it really helped me to better 
understand the funcargs "magic".

Elaborating on your suggestion, I came up with an idiom which can be 
used to combine flat lists of funcargs without using (too much) 
boilerplate code.
I successfully used it to modify my previous example, making it work 
the way I originally intended.
The modified example is attached, in case someone might find it useful.

Thanks again for your help,
     Stefano
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test_foo.py
Type: text/x-python
Size: 1506 bytes
Desc: not available
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20100321/c6ae2c15/attachment.py>


More information about the testing-in-python mailing list