5

How to test if a string variable in Robot Framework is empty?

My first naïve attempt looked like this:

Run Keyword If  ${myVar}!=${EMPTY}

but it failed:

Evaluating expression '!=' failed: SyntaxError: unexpected EOF while parsing (, line 1)

I then found this issue at Github but it didn't suggest a solution, just that the error message was unclear. An alternative solution was presented here:

${length}=    Get Length    ${Portfolio_ste}
Run Keyword If    ${length}    Go To Edit Portfolio

but is this really the best practice?

(The context is that I use a variable argument list and if a certain variable contains a value something should be done, otherwise just ignore it)

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
  • 2
    `Run Keyword If '${myVar}'!='${EMPTY}' ` wrap your variables in apostrophe – Dev Oct 26 '18 at 12:34
  • 1
    This will cause parse errors if `${myVar}` contains newline characters. In that case, the proposed solution is appropriate. If you can be sure your string can be parsed, then use the solution presented in @Bryan's answer. – Adrian W Oct 28 '21 at 11:46

2 Answers2

9

The expression needs to be a valid python expression after variable substitution. Assuming for the moment that myVar might be something like the number 42, your expression would end up looking like this after substitution:

Run Keyword if  42!=

When comparing against the empty string you need to add quotes to guarantee that the expression is a proper python expression after substitution. For example:

Run Keyword If  "${myVar}"!="${EMPTY}"
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
-1

Try Get Variable Value. It solved my problem.

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
MarkHu
  • 1,694
  • 16
  • 29
  • For those of us who like to see a URL before clicking: https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Get%20Variable%20Value – MarkHu Feb 07 '21 at 21:35
  • 1
    you are free to hover over the link before clicking it ;-) Anyway, you answer doesn't solve OP's question: test whether the string is empty (i.e. exists, but contains no characters) – Adrian W Oct 28 '21 at 11:35