How to use OR condition for Keywords in Robot Framework?

最后都变了- 提交于 2019-12-04 17:29:22

You can join XPath result sets with the | to do what is equivalent to an OR.

${count}    Get Matching Xpath Count    //div[@prop='value'|//table[@id='bar']|//p
Run Keyword If    ${count} > 0    Some Keyword

If you just want to fail if none of the XPaths are found:

Page Should Contain Element    xpath=//div[@prop='value'|//table[@id='bar']|//p

What you ask can be done with combination of Run Keyword And Return Status calls.

${el1 present}=  Run Keyword And Return Status     Page Should Contains Element    //some xpath1
${el2 present}=  Run Keyword And Return Status     Page Should Contains Element    //some xpath2
${el3 present}=  Run Keyword And Return Status     Page Should Contains Element    //some xpath3
${el4 present}=  Run Keyword And Return Status     Page Should Contains Element    //some xpath4

Run Keyword If  not ${el1 present} or not ${el2 present} or not ${el3 present} or not ${el4 present}   Fail  None of the elements is present on the page

Though this approach is straightforward, it is suboptimal - it will check for every element, even though the first may be present, and there is no need to check for the 2nd, 3rd and 4th. This (very expresive) version will do that:

${some element present}=  Run Keyword And Return Status     Page Should Contains Element    //some xpath1
${some element present}=  Run Keyword If  not ${some element present}    Run Keyword And Return Status     Page Should Contains Element    //some xpath2    ELSE    Set Variable    ${some element present}
${some element present}=  Run Keyword If  not ${some element present}    Run Keyword And Return Status     Page Should Contains Element    //some xpath3    ELSE    Set Variable    ${some element present}
${some element present}=  Run Keyword If  not ${some element present}    Run Keyword And Return Status     Page Should Contains Element    //some xpath4    ELSE    Set Variable    ${some element present}

Run Keyword If  not ${some element present}   Fail  None of the elements is present on the page

It uses the fact that Run Keyword If returns the value of the called keyword.

In summary, the first approach is better used when all conditions (Page Should Contain Element) should be checked (with the corresponding logical condition at the end - connected with and, not or as in this example).
The second - when just one is sufficient, and the rest shouldn't be checked if one is found to hold true.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!