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

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

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

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

  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,修改以下:java

 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格式輸出變量已經搞定。接下來是給變量賦值~~python

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

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

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方法一致。如我用到了this

@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

相關文章
相關標籤/搜索