robotframework接口自动化之保持会话

1.自动完成请求上下文传递中的cookie

关键字create session会创建session对象,下一个请求带上session别名,该session对象会自动完成请求在上下文传递过程中的 Cookie 处理

 

场景举例:获取用户信息

url:https://testpassport.rabxxxxx.com

登录接口:POST api/sso/login

获取用户信息: GET api/sso/getUserInfo

获取用户信息接口直接调无需传参,参数信息从请求(登录接口)cookie中获取,这时候我们可以通过同一个session实例发出的请求之间保持cookies

*** Settings ***
Resource    ../../../../Resources/Business/http通用请求/http_requests.robot
Library    Collections    
Library    HttpLibrary.HTTP
Library    RequestsLibrary        
*** Test Cases ***
获取用户个人简略信息_保持会话_Get

    sso_login    1XXXXXXXX20    111111    pc    #登录接口
    ${header_dict}    Create Dictionary    Content-Type=application/json
    #根据session别名:TZ_robotframework控制是同一个session
    ${res}    Get Request    TZ_robotframework    api/sso/getUserInfo        #请求获取用户信息接口
    Log Json    ${res.content}  
 

*** Keywords ***
sso_login
    [Arguments]    ${account}    ${password}    ${fromType}        
    ${host}    Set Variable    http://testpassport.raXXXXX.com
    ${path}    Set Variable    /api/sso/login
    ${datas}    Create Dictionary
    Set To Dictionary    ${datas}    account    ${account}
    Set To Dictionary    ${datas}    fromType    ${fromType}
    Set To Dictionary    ${datas}    password    ${password}
    ${params}    Set Variable  
    ${res}    requests_post    ${host}    ${path}    ${datas}    ${params}       
    ${cookies}     Set Variable      ${res.cookies}    
    Log Json    ${res.content}
    
    #提取json数据方式一:
    ${info}    Get Json Value       ${res.content}     /msg    #填写数据所在层级路径提取json信息    
    
    # 断言验证
    Should Be Equal As Strings    ${info}}    ok

 

 

2.获取token

第二个请求要发往另一个host/域名,如某些app接口请求参数中需要带上cookie/token字段,这时候新请求可能需要创建另一个session,将cookie主动加到请求参数中,例如添加在headers中

场景举例:获取用户信息

登录url:https://testpassport.rabXXXXX.com

获取用户信息url:https://bXXX.test.rabXXXXX.com

登录接口:POST api/sso/login

获取用户信息: POST /api/user

*** Settings ***
Resource    ../../../../Resources/Business/XX登录token获取/ssoLogin.robot
Library    Collections    
Library    HttpLibrary.HTTP   
*** Variables ***
${host}     https://bXX.test.rabXXXXX.com
${path}    /api/user
*** Test Cases ***
获取用户信息_Get
    ${res_token}    sso_login_token    158******    111111    pc    ok     #获取并返回token
    ${datas}    Create Dictionary
    ${params}    Create Dictionary
    ${headers}     Create Dictionary    Cookie=${res_token}
    
    #发起请求获取用户信息接口并添加cookies到请求头
    ${res}    requests_get       ${host}     ${path}    ${datas}    ${params}    ${headers} 
    Log json    ${res.text}
# 断言判断    
    Should Be Equal As Numbers    ${200}    ${res.status_code}
    ${errorcode}    Parse Json    ${res.content}
    ${errorcode}    Get From Dictionary    ${errorcode}    errorcode   
    Should Be Equal    '${errorcode}'    '0'

你可能感兴趣的:(接口自动化,Robotframework)