Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

robotframework - How to perform defered variable substitution in Robot Framework?

I have this code snippet

*** Keywords ***
My Keyword
  [Arguments]  ${arg}
  ${xpath}  Set Variable  really long dynamic xpath using ${arg}
  Do Something With  ${xpath}
  etc.

My Other Keyword
  [Arguments]  ${arg}
  ${xpath}  Set Variable  really long dynamic xpath using ${arg}
  Do Something Totally Different With  ${xpath}
  etc.

To follow programming best practices, I want to have the xpath (the same in both keywords) defined at single place only. I tried to modify it like this

*** Variables *** 
${xpath_template}  really long dynamic xpath using ${arg}

*** Keywords ***
My Keyword
  [Arguments]  ${arg}
  ${xpath}  Evaluate  ${xpath_template}
  Do Something With  ${xpath}
  etc.

My Other Keyword
  [Arguments]  ${arg}
  ${xpath}  Evaluate  ${xpath_template}
  Do Something Totally Different With  ${xpath}
  etc.

In other words, I need the substitution of ${arg} in ${xpath_template} be defered until the moment ${arg} is defined. However, the code above does not perform it, nor my similar experiments when I tried to force Set Variable or ${{...}} to do it for me... Can you help me, please, to have the xpath be only once in my code?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution is to use the Replace Variables keyword.

*** Variables ***
${xpath_template}  blah blah ${arg}

*** Keywords ***
My Keyword
    [Arguments]  ${arg}
    ${xpath}  Replace variables  ${xpath_template}
    Return from keyword  ${xpath}

*** Test Cases ***
Example
    ${xpath}=  My keyword  Hello, world
    Should be equal  ${xpath}  blah blah Hello, world

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...