2

When I have a parametrized pytest test like in the following case:

@parametrize('repetition', range(3))
@parametrize('name', ['test', '42'])
@parametrize('number', [3,7,54])
def test_example(repetition, name, number):
    assert 1 = 1

the test runner prints out lines like follows:

tests\test_example.py:12: test_example[1-test-7]

where the parametrized values show up in the rectangular bracket next to the test functions name (test_example[0]). How can I access the content of the rectangular bracket (i.e. the string 0) inside the test? I have looked at the request fixture, but could not find a suitable method for my needs.

To be clear: Inside the test method, I want to print the string 1-test-7, which pytest prints on the console.

How can I access the string 1-test-7, which pytest print out during a test?

I do not want to create this string by myself using something like

print str(repetition)+"-"+name+"-"+str(number)

since this would change every time I add a new parametrized argument to the test method.

In addition, if more complex objects are used in the parametrize list (like namedtuple), these objects are just references by a shortcut (e.g. object1, object2, ...).

Addendum: If I use the request fixture as an argument in my test method, I 'see' the string I would like to access when I use the following command

print request.keywords.node.__repr__()

which prints out something like

<Function 'test_example[2-test-3]'>

I am trying to find out how this method __repr__ is defined, in order to access directly the string test_example[2-test-3] from which I easily can extract the string I want, 2-test-3 in this example.

Alex
  • 41,580
  • 88
  • 260
  • 469
  • 2
    Isn't that just `repetition`? – mgilson Jul 24 '14 at 06:54
  • In this easy example - yes. But I have more complex examples in which I use many different parametrized arguments. Instead of creating this string myself by doing something like `str(repetition)+"_"+name+"_"+answer+"_"+str(number)`... I want to somehow get it from pytest itself, without creating a long and cumbersome string by myself... – Alex Jul 24 '14 at 06:57
  • So what's the question then? How can pytest automagically create some completely custom strings for you? I'd say it cannot. – famousgarkin Jul 24 '14 at 07:11

1 Answers1

2

The solution makes use of the built-in request fixture which can be accessed as follows:

def test_example(repetition, name, number, request):
    s = request.keywords.node.name
    print s[s.find("[")+1:s.find("]")]

which will print the parameter string for each single parametrized test, so each parametrized test can be identified.

Alex
  • 41,580
  • 88
  • 260
  • 469