如何在机器人框架中将凭据传递给 RESTinstance POST 请求?

Sat*_*amy 2 python robotframework

Python代码(工作正常):

 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
Run Code Online (Sandbox Code Playgroud)

机器人框架代码:

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

*** 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
Run Code Online (Sandbox Code Playgroud)

错误响应状态 - 401

Tod*_*kov 5

authrequests 方法中的参数只是post()http 基本身份验证的快捷方式。
另一方面,它是一个非常简单(因此是基本)的标头,名称为“Authorization”,值为“Basic b64creds ”,其中b64creds是“user:password”字符串的 Base64 编码形式。

因此流程非常简单 - 对凭据进行编码,并将其添加为标头。只有一个警告 - python 的base64 模块使用 bytes,其中 Robotframework/python3 中的字符串是 unicode,因此必须对其进行转换。

${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}
Run Code Online (Sandbox Code Playgroud)