सामग्री पर जाएँ

लेसन 9 · Syntax and Test Cases

Control Flow: IF, FOR, WHILE and TRY

Learn Robot Framework control structures: IF/ELSE, inline IF, FOR with RANGE, ENUMERATE and ZIP, WHILE limits, BREAK, CONTINUE and TRY/EXCEPT/FINALLY.

Test cases are mostly straight lines, but sometimes you need a decision or a loop. Robot has native control structures: IF, FOR, WHILE, TRY and the helpers BREAK, CONTINUE and RETURN. They are written in upper case and closed with END. Use them sparingly in tests. When logic grows, move it into a keyword, or into a Python library (see Python Keyword Libraries).

IF / ELSE IF / ELSE

ROBOTFRAMEWORK
*** Test Cases ***
Pick a size
    ${items}=    Set Variable    ${7}
    IF    ${items} > 10
        Log    large order
    ELSE IF    ${items} > 5
        Log    medium order
    ELSE
        Log    small order
    END

The condition is a Python expression after variable replacement. ${7} is the integer 7, while 7 alone would be a string, so comparisons like > 5 need numbers. Common conditions: '${status}' == 'OK', ${count} == 0, '${name}' != '', $name in ['ann', 'bob']. The last form with $name (no braces) uses the variable as a Python object, which is safer for text with quotes.

Inline IF fits one line:

ROBOTFRAMEWORK
IF    $user is None    Fail    No user
IF    ${n} > 3    Log    big    ELSE    Log    small

Inline IF can contain one keyword per branch; use the block form for more. Both can also assign: ${label}= IF ${n} > 3 Set Variable big ELSE Set Variable small.

FOR loops

ROBOTFRAMEWORK
*** Test Cases ***
Loops
    FOR    ${fruit}    IN    apple    banana    cherry
        Log    ${fruit}
    END

    FOR    ${i}    IN RANGE    3
        Log    round ${i}
    END

    @{names}=    Create List    ann    bob
    FOR    ${index}    ${name}    IN ENUMERATE    @{names}
        Log    ${index}: ${name}
    END

    @{ages}=    Create List    31    27
    FOR    ${name}    ${age}    IN ZIP    ${names}    ${ages}
        Log    ${name} is ${age}
    END
Form Meaning
IN a b c Loop over the listed values (or @{list} to expand a list)
IN RANGE stop Integers 0 to stop-1; also start stop and start stop step
IN ENUMERATE @{list} Index and item; start=1 changes the first index
IN ZIP ${l1} ${l2} Items of several lists together (shortest wins by default)

Notes:

  • Use @{list} to spread a list into the values. With IN ZIP, pass the lists as ${l1} (scalar form), not spread.
  • With IN ENUMERATE over a dictionary, use &{dict}.
  • Variables created in the loop remain after it ends, in the surrounding scope.

BREAK and CONTINUE

ROBOTFRAMEWORK
*** Test Cases ***
Find first even
    FOR    ${n}    IN    3    5    8    9
        IF    ${n} % 2 != 0    CONTINUE
        Log    first even number is ${n}
        BREAK
    END

CONTINUE skips to the next round; BREAK leaves the loop. They also work in WHILE.

WHILE

ROBOTFRAMEWORK
*** Test Cases ***
Count down
    ${n}=    Set Variable    ${3}
    WHILE    ${n} > 0
        Log    n is ${n}
        ${n}=    Evaluate    ${n} - 1
    END

A WHILE loop stops itself by default after 10,000 iterations to protect against infinite loops. Set limits explicitly:

ROBOTFRAMEWORK
WHILE    ${ready} == ${False}    limit=20    on_limit=pass
    ${ready}=    Check If Ready
END

limit can be a number of iterations (limit=20) or a time (limit=30s). on_limit=pass leaves the loop silently when the limit is reached, and on_limit_message=... sets the error text when it fails. Polling keywords such as Wait Until Keyword Succeeds are often a better tool than a hand-written loop.

TRY / EXCEPT / ELSE / FINALLY

ROBOTFRAMEWORK
*** Test Cases ***
Handle an expected error
    TRY
        Should Be Equal    1    2
    EXCEPT    1 != 2    AS    ${error}
        Log    caught: ${error}
    ELSE
        Log    nothing went wrong
    FINALLY
        Log    always runs
    END
  • EXCEPT catches failures whose message matches the given pattern. Without a pattern it catches any failure. Several patterns may be listed.
  • The default match type is GLOB (* and ?). Use type=START, type=REGEXP or type=LITERAL to change it: EXCEPT Connection .* refused type=REGEXP AS ${msg}.
  • AS ${error} stores the error message.
  • ELSE runs when no exception happened; FINALLY always runs, like a teardown for a block.
  • A catchable error is a normal failure; "fatal" errors, such as a timeout of the whole run, or a syntax problem, are not caught.

Use TRY when a failure is an acceptable outcome (an optional dialog, an expected error response). Do not use it to hide problems.

Stand-in 1: the same structures in Python

The blocks below are not Robot Framework. They show the semantics in Python: the same decisions and loops that the Robot snippets above express.

Python Stand-in: IF, FOR and WHILE logic

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Stand-in 2: TRY / EXCEPT with glob patterns

EXCEPT compares the error message with a pattern, glob style by default. The stand-in implements the matching and the ELSE and FINALLY ordering.

Python Stand-in: TRY / EXCEPT / ELSE / FINALLY

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep logic out of tests

A test with many nested IF and FOR blocks is hard to read. If you notice complex logic:

  1. Give the logic a name by moving it into a user keyword.
  2. Prefer data-driven tests (a template and a table of rows) over loops that run assertions.
  3. Move computations into a Python library keyword that has its own unit tests.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does FOR ${i} IN RANGE 3 iterate over?

    IN RANGE starts at 0 and stops before the given number, like Python's range().
  2. 2. Which statement exits a loop early?

    BREAK leaves the loop; CONTINUE only skips to the next iteration. END closes a block.
  3. 3. When does the FINALLY branch of TRY run?

    FINALLY runs whether the TRY body passed, failed or was caught by an EXCEPT.
  4. 4. Why use ${7} rather than 7 when comparing numerically in an IF?

    Arguments are strings unless a variable holds another type. ${7} creates a real integer.
  5. 5. What protects a WHILE loop from running forever?

    WHILE has a built-in iteration limit, and limit= and on_limit= let you control it.

Summary

  • IF, ELSE IF, ELSE and an inline IF make decisions; conditions are Python expressions.
  • FOR loops over values, IN RANGE, IN ENUMERATE and IN ZIP; BREAK and CONTINUE control them.
  • WHILE is protected by a default limit; set limit= and on_limit= yourself.
  • TRY / EXCEPT / ELSE / FINALLY handles expected failures; patterns are glob by default.
  • Keep tests simple: move logic into keywords or templates.

Next: User Keywords, Arguments and Return Values

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।