hanh nguyen
hanh nguyen

Reputation: 71

How to get variable with robot framework to rest API

I have a test suite

Library     RequestsLibrary
Library     JSONLibrary
Library   OperatingSystem


*** Variable ***
${base_url}    https://api.sportpartnerxxx.vn/v1
${identity_URL}    https://identity.sportpartnerxxx.vn

*** Test Cases ***

Login
    ${body}=    Create Dictionary    client_id=sportpartner-mobile-app    client_secret=ifd-sportpartner-secret-2021-mobile-app    grant_type=password    username=abc    password=123456
    ${header}=    create dictionary  content_type=application/x-www-form-urlencoded
    ${response}=    Post    ${identity_URL}/connect/token    headers=${header}    data=${body}
    ${token}=    Set Variable    Bearer ${response.json()["access_token"]}
    Status Should Be    200


Refresh token
    ${body}=    Create Dictionary    client_id=sportpartner-mobile-app    client_secret=ifd-sportpartner-secret-2021-mobile-app    grant_type=password    refresh_token=${refresh_token}
    ${header}=    create dictionary  content_type=application/x-www-form-urlencoded    Authorization=&{token}
    ${response}=    Post    ${identity_URL}/connect/token    headers=${header}    data=${body}
    Status Should Be    200

I want to take ${token} variable of Login test case add to Authorization value of Refresh token test case. But it failed. Does anyone help me?

Upvotes: 2

Views: 994

Answers (2)

Todor Minakov
Todor Minakov

Reputation: 20077

Variable crated in a case is local (visible) only in it, and in the keywords it calls; once the case ends, the var is deleted.
If you want it to be accessible in a follow up case, you need to extend its scope - call Set Suite Variable with it, or Set Global Variable - which will make it available for any other suites ran after this one.

This has one big drawback, though - you're adding dependency on the cases order; "Login" has always to be ran fist - and to succeed, so that "Refresh token" works.
That's why this is usually done through keywords (called in case setup, etc).

I'd kindly suggest to read about variables scopes in the user guide - http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#using-set-test-suite-global-variable-keywords

Upvotes: 3

Matt
Matt

Reputation: 135

You could try saving the variable with
Set Suite Variable
Then accessing it in your other test case

https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Set%20Suite%20Variable

Upvotes: 2

Related Questions