Catch Network and Console Run-times Log For UI Automation

记录怎么使用CDP 在UI automation 过程中catch network log 以及console log(以robotframework 为例)

方法一: 直接使用chorme driver+selenium (CDP)

针对console log :这个实现非常简单,因为往往更多有用的信息都在network 中反应,这里只是记录了前端的log

@keyword
    def get_console_log(self):
        """
        Get browser console log and return as list.
        This is achieved by webdriver built-in get_log() method.
        """
        self.info("Get browser console log")
        console_list = [log for log in self.driver.get_log('browser')]
        #console_list = [log['message'] for log in self.driver.get_log('browser')]
        return console_list

针对network log :需要在open browser 时就设置enabled logging:performance=ALL browser=ALL ,会自动开始记录所有的log,需要进行处理时,适应driver.get_log ,这其中存在问题,就是可能有些请求的body 没有记录下来,如果直接get log 打印出来很可能body 全都是空,这里需要在存储log的时候处理一层,通过request id 去获取他的response body。这里只操作了对于requeswillbesent类型的获取,实际上有非常多的类型,根据实际需要改改就行。实现如下:

def get_request_log_with_body(self):
        self.info("Get browser request/response log")
        request_list = []
        logs = self.driver.get_log("performance")
        for log in logs[:]:
            request_list.append(log)
            log_method = json.loads(log.get("message")).get("message").get("method")
            if log_method == "Network.requestWillBeSent":
                requestId = json.loads(log.get("message")).get("message").get("params").get("requestId")
                try:
                    body = self.driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})
                    get_body = 'Request_Response:' + str(body)
                    request_list.append(get_body)
                except exceptions.WebDriverException:
                    body= 'response.body is null'
                    get_body = 'Request_Response:' + body
                    request_list.append(get_body)
        return  request_list

配合使用:

  • 使用Create webdriver:
&{logging_cap}    Create Dictionary    performance=ALL    browser=ALL  
${ChromeOptions}=     Evaluate      sys.modules['selenium.webdriver'].ChromeOptions()  sys,selenium.webdriver 
 # Method debugger_address is not callable so convert to Capabilities Dictionary and set it manually
 ${ChromeCapabilities}=     Call Method     ${ChromeOptions}    to_capabilities
 Set To Dictionary    ${ChromeCapabilities["goog:chromeOptions"]}    debuggerAddress    127.0.0.1:9289  
 Set To Dictionary    ${ChromeCapabilities}    goog:loggingPrefs=&{logging_cap}    pageLoadStrategy=none   
    # Instead of using the Chrome Options use Capabilities.
    Create WebDriver    Chrome    desired_capabilities=${ChromeCapabilities}    executable_path=./Drivers/chromedriver.exe

使用open browser:

&{logging_cap}    Create Dictionary    performance=ALL    browser=ALL

    &{cap}    Create Dictionary    goog:loggingPrefs=&{logging_cap}    pageLoadStrategy=none    proxy=&{proxy} 
   
    Open Browser    ${.Url}    ${BROWSER}    alias=activebrowser    desired_capabilities=&{cap}    executable_path=${executable}
    ...    options=add_argument('--no-sandbox');add_argument('--disable-gpu');add_argument('ignore-certificate-errors');add_argument('--enable-logging');add_argument('--v=1');add_argument('--disable-web-security')

存在的问题:
当页面重新加载或者进行重定向以后,log 就会被清空,因为cdp没有直接针对persevere log 的操作,这里会非常不方便,同时log的记录会带来性能问题以及存储的log 过多可能会导致阻塞(具体原因自己百度下 有size问题)

所以有了方案二的诞生:

使用browsermobProxy
相关背景介绍:https://github.com/lightbody/browsermob-proxy
简单来说相当于配置了代理可以对所有的流量进行保存拦截。但是他提供了直接保存为har的方法,这对于辅助debug 非常的简单快捷

直接将本机设置为代理server即可,

&{logging_cap}    Create Dictionary    performance=ALL    browser=ALL
    &{proxy}      Create Dictionary    proxyType=MANUAL    sslProxy=127.0.0.1:7072    httpProxy=127.0.0.1:7072  
    &{cap}    Create Dictionary    goog:loggingPrefs=&{logging_cap}    pageLoadStrategy=none    proxy=&{proxy} 
    &{host}    Create Dictionary    address=127.0.0.1    port=7072    trustAllServers=True  
    ##enabled mob      
    Start Local Server      ${EXECDIR}\\Plugins\\browsermob-proxy-2.1.4\\bin\\browsermob-proxy
    ${BrowserMob_Proxy}=    Create Proxy    ${host}
    ##open
    Open Browser    ${Data_Common_CC_${ENV}.Url}    ${BROWSER}    alias=activebrowser    desired_capabilities=&{cap}    executable_path=${executable}
    ...    options=add_argument('--no-sandbox');add_argument('--disable-gpu');add_argument('ignore-certificate-errors');add_argument('--enable-logging');add_argument('--v=1');add_argument('--disable-web-security')
    ##begin recording
    &{har}    Create Dictionary    captureHeaders=true    captureContent=true    captureBinaryContent=true
    New Har    options=${har}
Catch Har Log
    ${current_time}=    Get Current Date
    ${format_date} =    Convert Date    ${current_time}    result_format=%Y%m%d%H%M%S
    ${har}    Get Har As JSON
    Create File    ${EXECDIR}//TestLog//${format_date}.har     ${har} 

简单快捷方便,并且重定向不会影响log 记录, 等于preserver log的功能,但是如果测试也同时在使用其他的代理,需要考虑怎么兼容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值