问题
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