Search code examples
restoauth-2.0robotframework

Robot Framework api test with Oauth2 - pass generated token to other test cases


Using similar code to this one, I am able to successfully generate a Token and authorize the request bellow it. Both actions happen in one test case. I tried creating a new test case with only copying the second request code and of course it says unauthorized. So my question is, since I can generate a token in the first test case, what do I have to add in order to use/pass the already generated token for a second, third, fourth, test cases?

${data}=     Create Dictionary    Token_Name=TestTokenname    grant_type=<grant type>    client_Id=<your Id>     Client_Secret=<Your client secret>    scope=<your scpe>
${headers}=   Create Dictionary    Content-Type=application/x-www-form-urlencoded

${resp}=    RequestsLibrary.Post Request    OA2    identity/connect/token    data=${data}    headers=${headers}
BuiltIn.Log To Console    ${resp}
BuiltIn.Log To Console    ${resp.status_code}
Should Be Equal As Strings    ${resp.status_code}    200
Dictionary Should Contain Value    ${resp.json()}   Testtokenname
${accessToken}=    evaluate    $resp.json().get("access_token")
BuiltIn.Log to Console    ${accessToken}
${token}=    catenate    Bearer    ${accessToken}
BuiltIn.Log to Console    ${token}
${headers1}=  Create Dictionary    Authorization=${token} 

RequestsLibrary.Create Session    GT    <Your Server URL>    verify=${True}        
${resp}=  RequestsLibrary.Get Request  GT    <Your API URL>    headers=${headers1}
Should Be Equal As Strings    ${resp.status_code}    200 ```

Solution

  • In your code, after getting and storing token in a variable, add the below line of code immediately. Variables set with this keyword are globally available in all subsequent test suites, test cases and user keywords.

    Set Global Variable    ${token}
    

    More detailed explanation in the below link https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set%20Global%20Variable