python3修改HTMLTestRunner,生成有截圖的測試報告,並發送測試郵件(二)


3. 如何將第一步得到的地址和名稱 輸入 進第二步里的表格中呢。。。

用上述查找元素的方法,發現HTMLTestRunner.py中REPORT_TEST_WITH_OUTPUT_TMPL是用來輸出測試結果的。我們只需要將截圖url和名稱寫進去即可。

假定我們目前已經可以定位到每個用例的具體截圖,並將截圖url定義為變量html,名稱定義成變量name,修改HTMLTestRunner.py的代碼如下:

  REPORT_TEST_WITH_OUTPUT_TMPL = r"""
<tr id='%(tid)s' class='%(Class)s'>
    <td class='%(style)s'><div class='testcase'>%(desc)s</div></td>
    <td colspan='5' align='center'>

    <!--css div popup start-->
    <a class="popup_link" onfocus='this.blur();' href="javascript:showTestDetail('div_%(tid)s')" >
        %(status)s</a>
    <td><a href="%(html)s" target="_blank">%(name)s</a></td>      <!--此處修改-->
    <div id='div_%(tid)s' class="popup_window">
        <div style='text-align: right; color:red;cursor:pointer'>
        <a onfocus='this.blur();' onclick="document.getElementById('div_%(tid)s').style.display = 'none' " >
           [x]</a>
        </div>
        <pre>
        %(script)s
        </pre>
       
    </div>
    <!--css div popup end-->   
    </td>

</tr>
""" # variables: (tid, Class, style, desc, status)

找到變量定義的函數:_generate_report_test,修改如下:

 row = tmpl % dict(
            tid = tid,
            Class = (n == 0 and 'hiddenRow' or 'none'),
            style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),
            desc = desc,
            script = script,
            html = html,        #此處修改
            name = name,     #此處修改
            status = self.STATUS[n],
        )
        rows.append(row)
        if not has_output:
            return

定義變量、以url格式輸出變量已經搞定。接下來是給變量賦值~~

思路:依照大神們些的博客,看出函數_generate_report_test中的ue和uo代表unittest中打印日志和拋出異常日志。想到如果我把截圖的url和name打印到日志中,就能夠從ue和uo中很容易的提取到url和name。
開始對unittest進行改造~~

思路:我想對每條用例都輸出截圖,不論fail或者pass。如果用例執行正確,則只打印日志。如果用例執行錯誤,則打印日志並拋出異常日志。

unittest是python3自帶的庫,我們需要找到unittest文件夾,對case.py修改。路徑:XXX(自己的python安裝路徑)\Python\Python36\Lib\unittest
case.py的TestCase類中增加兩個方法

def screenshot():
def add(func):
具體如下:

class TestCase(object):
    def screenshot():    #(一)中講過定義截圖的方法
        imageName = str(time.time()) + '.png '  
        imagepath = '//sdcard//' + imageName
        path = os.getcwd() + '\\screenshot'  
        if not os.path.exists(path):        
            os.mkdir( path)
        os.system("adb shell //system//bin//screencap -p " + imagepath)
        os.system('adb pull ' + imagepath + path)
        print('lustrat' + path + '\\' + imageName + 'luend')  #輸出日志,前后加'luStrat'luEnd'特殊字符方便截取

    def add(func):  #增加打印日志的方法
        def wrapper(self, first, second, msg=None):
            try:
                func(self, first, second, msg=None)
                TestCase.screenshot()

            except AssertionError:  
                TestCase.screenshot()
                raise AssertionError(msg)  # 拋出AssertionError
        return wrapper

 

然后在用到的assert方法前加@add裝飾器。注意定義的func的傳參與assert方法一致。如我用到了

@add        #此處修改
def assertEqual(self, first, second, msg=None): """Fail if the two objects are unequal as determined by the '==' operator. """ assertion_func = self._getAssertEqualityFunc(first, second) assertion_func(first, second, msg=msg)

至此HTMLTestRunner.py的uo和ue輸出的日志就包含了print的截圖地址信息

最后一步了,取出ue和uo的關於截圖的url和name,並賦值給變量html和name就搞定了~~~ 

    def _generate_report_test(self, rows, cid, tid, n, t, o, e):
        # e.g. 'pt1.1', 'ft1.1', etc
        has_output = bool(o or e)
        tid = (n == 0 and 'p' or 'f') + 't%s.%s' % (cid+1,tid+1)
        name = t.id().split('.')[-1]
        doc = t.shortDescription() or ""
        desc = doc and ('%s: %s' % (name, doc)) or name
        tmpl = has_output and self.REPORT_TEST_WITH_OUTPUT_TMPL or self.REPORT_TEST_NO_OUTPUT_TMPL
        # o and e should be byte string because they are collected from stdout and stderr?
        if isinstance(o,str):
            # TODO: some problem with 'string_escape': it escape \n and mess up formating
            # uo = unicode(o.encode('string_escape'))
            uo = e
        else:
            uo = o
        if isinstance(e,str):
            # TODO: some problem with 'string_escape': it escape \n and mess up formating
            # ue = unicode(e.encode('string_escape'))
            ue = o      #此處修改
        else:
            ue = o

        script = self.REPORT_TEST_OUTPUT_TMPL % dict(
            id = tid,
            output = saxutils.escape(str(uo)+str(ue)),
        )
        s= str(uo) +str(ue)      #此處修改開始
        if s.count('png')!=0:       #判斷日志中是否有圖片
            html =  s[s.find('lustrat')+7:s.find('luend')]
            name =  html[html.find('shot\\')+5:]
        else:
            html = ' '
            name = ' '              #此處修改結束
        row = tmpl % dict(
            tid = tid,
            Class = (n == 0 and 'hiddenRow' or 'none'),
            style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'none'),
            desc = desc,
            script = script,
            html = html,
            name = name,
            status = self.STATUS[n],
        )
        rows.append(row)
        if not has_output:
            return

百度雲盤下載地址:unittest文件夾case.py修改鏈接:https://pan.baidu.com/s/1eTMJu86 密碼:n19o

                                       HTMLTestRunner.py鏈接:https://pan.baidu.com/s/1dGSRbg9 密碼:lw0e


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM