Home > OS >  Variable from one Test cant be used in other(Variable 'token' is used, but not defined)
Variable from one Test cant be used in other(Variable 'token' is used, but not defined)

Time:12-16

I have the following two tests,

*** Settings ***

Library CustomizeLibrary

*** Variables ***

${username} anti

${password} anti

${headers} {"Content-Type": "application/json"}

*** Test Cases ***

GET Users'

${token}    Customize Get Token    http://127.0.0.1:5000/api/auth/token    ${token}  (Gives error: Variable 'token' is used, but not defined)

GET token based on existing user

${token}=    Customize Get Token    http://127.0.0.1:5000/api/auth/token    ${username}    ${password}    ${headers}
Set suite variable    ${token}

${token} is defined and set as suite variable in previous test not yet able to use it, Any sugession ?

CodePudding user response:

It is called a "static variable", a variable that is not restricted to a single test/method/class instance (Google for more info). This variable exists outside all your tests.

How to implement: Static Variables in Robot Framework

*** Settings *** 
... 
*** Variables *** 
.... other variables ....
${token}= Customize Get Token http://127.0.0.1:5000/api/auth/token ${username} ${password} ${headers}

Remark: your tests should be independent. You do NOT want 1 test to run first, otherwise the next one fails. Trust me, it is a anti Pattern and causes a world of hurt. Place the GetToken in an initializer/constructor to prevent issues.

CodePudding user response:

I would suggest looking at setting the suite variable during Suite Setup by calling a keyword to initialize the variable. It will run before tests and eliminates dependency between tests.

Here is a dummy example:

*** Settings ***
Suite Setup  Init Suite Variable

*** Test Cases ***
Scenario: Test 1 - Suite Variable
    Log To Console  ${suite_variable}

Scenario: Test 2 - Test Variable 
    Init Test Variable
    Log To Console  ${test_variable}

*** Keywords ***
Init Suite Variable 
    Set Suite Variable  ${suite_variable}  I'm at suite level

Init Test Variable 
    Set Test Variable   ${test_variable}  I'm at test level
  • Related