You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyCharm的ROBOT Framework中使用Browserstack Automate API标记测试状态

错误原因及修复方案

核心错误点

  • 请求格式不匹配:PUT请求声明了Content-Type: application/json,但你用data参数传字典,RequestsLibrary默认会将字典转为表单格式,和Header声明的格式不符,触发400错误。
  • 状态值大小写错误:BrowserStack标记测试状态的接口仅接受小写的passed/failed作为status参数值,你代码中写的大写Pass/Fail会直接触发422 Unprocessable Entity错误。
  • Session ID获取方式冗余易错:不需要额外调用接口查询最近的会话ID,直接用SeleniumLibrary内置关键字就能拿到当前运行的测试会话ID,避免并发测试时ID拿错的问题。
  • 鉴权参数硬编码:创建请求会话时的鉴权参数没有复用已定义的${BSUser}、${AccessKey}变量,占位符没替换就会触发鉴权相关错误。

修复后的代码调整

1. 测试用例部分简化Session ID获取

*** Test Cases ***
landing page test
    Open Browser   url=${SiteUrl}   browser=chrome   remote_url=${RemoteURL}   desired_capabilities=browser:chrome,browser_version:latest,os:Windows,os_version:10,build:test_build1
    set window size  440  717
    # 直接获取当前测试会话ID,无需调用接口查询
    ${session_id}=    Get Session Id
    Set Global Variable      ${session_id}
    # 鉴权复用已定义变量
    ${auth}=    create list  ${BSUser}  ${AccessKey}
    create session  mysession  ${BaseURL}   auth=${auth}

    wait until element is visible  //div[contains(text(),'Table')]
    ${txt}    Get Text    xpath=//div[contains(text(),'Table')]
    ${res}    Should Be Equal As Strings    ${txt}    ${ver_txt1}
    Run keyword if   '${txt}' == '${ver_txt1}'   Test keyword 1     ELSE  Test keyword 2
    sleep  3s

2. 关键字部分调整请求参数和状态值

*** Keywords ***
Test keyword 1
    Log to console  Success!!!!
    ${body}=    create dictionary  status=passed  reason=Validation Passed
    ${header}=  create dictionary  Content-Type=application/json
    # 用json参数代替data,自动将字典转为JSON格式
    ${response}=    PUT On Session  mysession   /automate/sessions/${session_id}.json  json=${body}  headers=${header}
    ${jsonresponse}=    set variable  ${response.json()}
    ${code}=  convert to string  ${response.status_code}
    should be equal  ${code}  200
    Log to console  ${jsonresponse}

Test keyword 2
    Log to console  Test Failed...
    ${body}=    create dictionary  status=failed  reason=Validation Failed
    ${header}=  create dictionary  Content-Type=application/json
    ${response}=    PUT On Session  mysession   /automate/sessions/${session_id}.json  json=${body}  headers=${header}
    ${jsonresponse}=    set variable  ${response.json()}
    ${code}=  convert to string  ${response.status_code}
    should be equal  ${code}  200
    Log to console  ${jsonresponse}

按照以上修改后即可正常调用BrowserStack接口标记测试用例状态。

内容的提问来源于stack exchange,提问作者Kasun Ishanka Yapa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:24:03