如何在机器人框架中将凭据传递给 RESTinstance POST 请求? [英] How to pass credentials to RESTinstance POST Request in robot framework?

查看:33
本文介绍了如何在机器人框架中将凭据传递给 RESTinstance POST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 代码(工作正常):

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

机器人框架代码:

我想在机器人框架中复制相同的 API 测试,但我不知道如何将凭据传递给 RESTinstance POST 方法

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

错误响应状态 - 401

ERROR RESPONSE STATUS - 401

推荐答案

requests post() 方法中的 auth 参数只是 http 基本身份验证的快捷方式.
另一方面,它是一个非常简单的(因此是基本的) - 带有名称为Authorization",值为Basic b64creds",其中 b64creds 是user:password"字符串的 base64 编码形式.

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.

所以流程非常简单 - 对凭据进行编码,并将它们添加为标题.只有一个警告 - python 的 base64 模块使用字节,这里Robotframework/python3中的字符串是unicode的,所以需要进行转换.

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}

这篇关于如何在机器人框架中将凭据传递给 RESTinstance POST 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆