Robotframework get iteration for repeat

Viewed 108

In robotframework im using repeat to call a keyword x amount of times. What I want is to get the iteration number in the keyword that is called.

What I tried:

${iteration} =          0

*** Test Cases ***
Start Test
    repeat keyword  ${duration}  Run test iteration ${iteration}

*** Keywords ***
Run test iteration ${loop}
    ${iteration}=  Set Variable  evaluate  ${iteration}+1

What I expected was that In the report the called keywords would look like:

Run test iteration 0
Run test iteration 1
Run test iteration 2

But I see

Run test iteration 0
Run test iteration 0
Run test iteration 0

Is it possible to get the result I predicted?

Using robotframework 3.1.1

1 Answers

Yes, it is, and it all boils down to variables scope.
When you do the assignment in the keyword that variable is with a scope local to the keyword - it is visible inside it (not to a potential keyword that has called it), and is deleted when the keyword finishes. That is irregardless that it has the same name as the one defined in the Variables section - you are effectively redefining a new one with the same name, e.g. overriding it. And not changing the "global" one's value in any way.
Then on the next loop this is repeated, and thus you get a 0 in every run.

The fix is simple - just after changing the value, declare you want this variable to be visible in a higher scope (higher than the current keyword). You have a choice of 3 - case level, suite, or global (so all follow suites & cases can use it); here's for the case level:

Run test iteration ${loop}
    ${iteration}=  Evaluate  ${iteration}+1
    Set Test Variable    ${iteration}
Related