How to pass credentials to RESTinstance POST Request in robot framework?

我怕爱的太早我们不能终老 提交于 2019-12-23 02:38:24

问题


Python Code (Working fine):

 credentials = ("key","token")
 verify = False
 if not verify:
     from requests.packages.urllib3.exceptions import InsecureRequestWarning  
     requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

response = requests.post(url, auth=credentials, data=json.dumps(payload), headers={'content-type': 'application/json'}, verify=verify)
status = response.status_code

Robot Framework Code:

I would like to duplicate same API testing in robot framework but i am stuck how to pass credentials to the RESTinstance POST method

*** Settings ***
Library         REST    url=https://testhost.com   ssl_verify=${verify}

*** Variables ***
header = {"content-type": "application/json"}

*** Test Cases ***
Test Task
    POST     endpoint=/api/something   body=${payload}   headers=${header}
    Output   response status

ERROR RESPONSE STATUS - 401


回答1:


The auth argument in requests post() method is just a shortcut to http basic authentication.
And it on the other hand is a very simple (hence - basic) one - a header with name "Authorization", with value "Basic b64creds", where b64creds is base64 encoded form of the "user:password" string.

So the flow is quite simple - encode the credentials, and add them as a header. There is only one caveat - python's base64 module works with bytes, where the strings in Robotframework/python3 are unicode, so they have to be converted.

${user}=    Set Variable    username
${pass}=    Set Variable    the_password

# this kyword is in the Strings library
${userpass}=    Convert To Bytes    ${user}:${pass}   # this is the combined string will be base64 encode
${userpass}=    Evaluate    base64.b64encode($userpass)    base64

# add the new Authorization header
Set To Dictionary    ${headers}    Authorization    Basic ${userpass}

# and send the request with the header in:
POST     endpoint=/api/something   body=${payload}   headers=${header}


来源:https://stackoverflow.com/questions/53265635/how-to-pass-credentials-to-restinstance-post-request-in-robot-framework

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