Jenkins擴(kuò)展釘釘消息通知

背景

Jenkins借助釘釘插件气堕,實(shí)現(xiàn)當(dāng)構(gòu)建失敗時(shí),自動(dòng)觸發(fā)釘釘預(yù)警畔师。雖然插件允許自定義消息主體娶靡,支持使用 Jenkins環(huán)境變量,但是局限性依舊很大看锉。當(dāng)接收到釘釘通知后姿锭,若想進(jìn)一步查看報(bào)錯(cuò)具體原因塔鳍,仍完全依賴郵件通知,很影響效率呻此。

如何在釘釘通知消息中轮纫,獲取到本次構(gòu)建的具體內(nèi)容,如失敗占比焚鲜、失敗用例報(bào)錯(cuò)詳情等掌唾,本文記錄了解決思路。最終實(shí)現(xiàn)結(jié)果如圖:

解決思路

Jenkins + RobotFramework 項(xiàng)目

思路如下:

  1. 使用Startup Trigger插件和Groovy plugin插件, 在服務(wù)重啟時(shí)自動(dòng)修改Jenkins CSP配置, 解決Robot Framework項(xiàng)目測(cè)試報(bào)告在Jenkins服務(wù)器上無法預(yù)覽的問題, 如下:
System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "")
  1. Jenkins項(xiàng)目構(gòu)建完成后, 在構(gòu)建后操作中恃泪,利用Post Build Task插件提供的命令行功能, 傳入相關(guān)參數(shù)執(zhí)行封裝的腳本, 如下:
if "%構(gòu)建失敗時(shí)觸發(fā)釘釘通知%"=="true" (
    echo ************推送釘釘消息通知************
    cd %WORKSPACE%/test
    C:/python38/python.exe dingtalk.py --id=%BUILD_NUMBER% --name=%JOB_NAME% --server=xxxxxx
    echo *******************************************
    exit 0
)

說明幾點(diǎn):

  • “構(gòu)建失敗時(shí)觸發(fā)釘釘通知” 是我自定義的布爾類型的項(xiàng)目構(gòu)建參數(shù)郑兴,用于更方便的控制是否觸發(fā)釘釘消息通知;
  • dingtalk.py是封裝的腳本贝乎,其內(nèi)容在下面會(huì)詳細(xì)說明;
  • Post Build Task 插件的位置必須位于 Robot Framework插 件之后, 否則會(huì)引發(fā)以下異常:
robot.errors.DataError: Reading XML source '<in-memory file>' failed: Incompatible XML element 'html'
  1. 編寫第二步中調(diào)用的釘釘消息通知腳本叽粹,其核心思路可分為兩點(diǎn):
    1. 獲取并分析本次構(gòu)建結(jié)果文件(如: output.xml), 提取數(shù)據(jù), 如: 失敗占比览效、失敗用例報(bào)錯(cuò)詳情等;
    2. 組裝 Markdown 格式的消息主體, 然后調(diào)用 DingTalk Webhook 接口, 推送消息通知;
    核心代碼如下:
def fetch_robot_output_xml(xml_name=None, save=False, cache=True) -> str:
    """ 從服務(wù)器上獲取 Robot Framework 項(xiàng)目構(gòu)建完成后生成的xml文件
    @param xml_name: xml文件名稱, 部分項(xiàng)目會(huì)合并測(cè)試報(bào)告, 默認(rèn)`merge.xml`
    @param save: 是否將文件保存到本地, 默認(rèn) False
    @param cache: 默認(rèn)為True, 會(huì)首先遍歷本地已保存的構(gòu)建文件, 若文件名稱不存在才會(huì)向服務(wù)器發(fā)起請(qǐng)求;
    @Returns : xml文件內(nèi)容
    """
    xml_name = xml_name if xml_name else "merge.xml"
    url = url_prefix + f"{name}/{id}" + f"/robot/report/{xml_name}"

    output_xml = None
    if cache:
        for xml in robot_outputs.glob('*.xml'):
            if name in xml.stem and id in xml.stem:
                output_xml = xml.read_text(encoding='utf-8')
                break
    if not output_xml:
        print(f"發(fā)起請(qǐng)求獲取測(cè)試報(bào)告, 目標(biāo)URL: {url}")
        # curl -X GET {URL} --user {USER}:{TOKEN}
        resp = requests.get(url, auth=HTTPBasicAuth(jenkins_user.encode('utf-8'), jenkins_token.encode('utf-8')))
        resp.encoding = 'utf-8'
        output_xml = resp.text

    if save and not cache:
        save_output_xml(output_xml, f"{server}_{name}_{id}_output.xml")
    print("Done.")
    return output_xml

def parse_robot_result(xml) -> dict:
    """解析用例運(yùn)行結(jié)果
    pip install robotframework==3.2.1
    獲取統(tǒng)計(jì)信息, 優(yōu)先使用此方法, 因?yàn)閤ml文件中可能會(huì)不包含有效的測(cè)試報(bào)告信息, 如請(qǐng)求獲取文件服務(wù)器返回404的情況
    """
    print('解析用例運(yùn)行結(jié)果...')
    try:
        suite = ExecutionResult(xml).suite
    except DataError as e:
        raise e('解析xml文件失敗, 請(qǐng)檢查構(gòu)建文件內(nèi)容是否完整, 確認(rèn)服務(wù)器上的構(gòu)建文件是否已被刪除')

    all_tests = suite.statistics.critical
    total, passed, failed = all_tests.total, all_tests.passed, all_tests.failed
    pass_rate = round((passed / total) * 100, 2)
    is_success = True if failed == 0 else False

    stat = {'server': server, 'job': name, 'build_id': id, 'total': total, 'passed': passed, 'failed': failed, 'pass_rate': str(pass_rate) + "%", 'is_success': is_success}
    print('Done')
    return stat


def pick_fail_cases(xml: str) -> list:
    print('獲取所有失敗用例及其報(bào)錯(cuò)信息...')
    root = ET.fromstring(xml)

    fail_cases = []
    for case in root.iter('test'):
        status = case.find('status')
        if status.get('status') == "FAIL":
            fail_cases.append({"case": case.get('name'), "message": truncate_text(status.text)})
    print('Done.')
    return fail_cases

def package_dingtalk_text(stat: dict) -> dict:
    print("組裝釘釘通知信息主體...")
    # 項(xiàng)目頁(yè)面地址
    job_url = url_prefix + stat['job'] + '/'
    # 本次構(gòu)建ID以及詳情頁(yè)面地址
    build_id = stat['build_id']
    build_url = job_url + build_id + '/'
    # 統(tǒng)計(jì)信息
    summary_text = f"用例總數(shù):{stat['total']},失敗用例數(shù):{stat['failed']}虫几, 通過率: {stat['pass_rate']}\n"
    # 用例報(bào)錯(cuò)詳情
    case_error_details = ""
    num = 1  # 序號(hào)
    if len(stat['fail_cases']) > 0:
        for case in stat['fail_cases']:
            case_error_details = case_error_details + f"{num}. 用例名稱: {case['case']}, 失敗原因: {case['message']}\n"
            num += 1
    print("Done.")
    return {
        "server_show_name": server_show_name,
        "job_show_name": job_show_name,
        "job_url": job_url,
        "build_id": build_id,
        "build_url": build_url,
        "summary_text": summary_text,
        "case_error_details": case_error_details
    }


def ding_talk(message=None):
    """
    目前只支持markdown語法的子集, 參考官方文檔: https://developers.dingtalk.com/document/app/custom-robot-access
    """
    print("推送釘釘消息通知...")
    webhook = "https://oapi.dingtalk.com/robot/send?access_token=1048af6c9a25ea5e924ae328c6782b68c48a40bcea773df96eadce783f2941ca"
    headers = {"Content-Type": "application/json", "Charset": "UTF-8"}

    payload = {
        "msgtype": "markdown",
        "markdown": {
            "title":
            "心跳測(cè)試",
            "text":
            f"# [[{message['server_show_name']}] 心跳測(cè)試-{message['job_show_name']}]({message['job_url']})\n***\n>*失敗用例會(huì)自動(dòng)重復(fù)執(zhí)行一次, 若仍然失敗, 則標(biāo)記為失敗*\n***\n- 任務(wù):#[{message['build_id']}]({message['build_url']})\n- 狀態(tài):失敗\n- 統(tǒng)計(jì)信息:{message['summary_text']}\n - 失敗用例報(bào)錯(cuò)詳情: \n\n{message['case_error_details']}\n"
        },
        "at": {
            "isAtAll": True
        }
    }
    resp = requests.post(webhook, json=payload, headers=headers)
    print(resp.text)
    print("Done.")
    return resp

Jenkins + Jmeter 項(xiàng)目

前兩步是共同的锤灿,也是通過解析result.jtl文件提取需要的數(shù)據(jù),直接貼代碼:

def fetch(xml_name=None, save_file=False) -> str:
    xml_name = xml_name if xml_name else "result.jtl"
    url = url_prefix + f"{name}/{id}" + f"/artifact/{name}result/{xml_name}"
    print(url)
    resp = requests.get(url, auth=HTTPBasicAuth(jenkins_user.encode('utf-8'), jenkins_token.encode('utf-8')))
    status_code = resp.status_code
    if status_code == 200:
        resp.encoding = 'utf-8'
        xml = resp.text

        if save_file:
            save(xml, f"{server}_{name}_{id}_{xml_name}")

        return xml
    elif status_code == 404:
        print(f"{status_code}, 指定的測(cè)試報(bào)告不存在, 可能已被刪除, 請(qǐng)去服務(wù)器上檢查")
        raise Exception("{status_code}, 指定的測(cè)試報(bào)告不存在, 可能已被刪除, 請(qǐng)去服務(wù)器上檢查")
    elif status_code == 500:
        print(f"獲取測(cè)試報(bào)告失敗, 詳情: {status_code} >> {resp.text}")
        raise Exception(f"獲取測(cè)試報(bào)告失敗, 詳情: {status_code} >> {resp.text}")
    else:
        return None

def parse(xml):
    """分析xml測(cè)試報(bào)告, 提取數(shù)據(jù)"""
    result = {}
    try:
        root = ET.fromstring(xml)
    except ParseError:
        raise ParseError("解析XML文件失敗, 請(qǐng)檢查服務(wù)器上文件是否存在")

    # 獲取統(tǒng)計(jì)信息
    samples = root.findall('httpSample')
    failures = [sample for sample in samples if sample.get('s') == "false"]
    failures_cnt = len(failures)
    success = [sample for sample in samples if sample.get('s') == "true"]
    success_cnt = len(success)
    is_success = True if failures_cnt == 0 else False
    success_rate = "100%" if is_success else str(round((success_cnt / len(samples)) * 100, 2)) + "%"
    result['summary'] = {"samples": len(samples), "is_success": is_success, "failures_cnt": failures_cnt, "success_rate": success_rate}

    # 數(shù)據(jù)清洗, 獲取失敗用例的報(bào)錯(cuò)信息
    fail_details = []
    if failures_cnt > 0:
        pat = re.compile(".*R-TraceId:(.*?)\n.*", re.DOTALL)
        for sample in failures:
            msg = [] 
            for res in sample.findall('assertionResult'):
                for child in res:
                    if child.tag in ("failure", "error") and child.text == "true":
                        try:
                            msg.append(res.find('failureMessage').text)  # ?這個(gè)節(jié)點(diǎn)可能會(huì)不存在
                        except AttributeError:
                            msg.append("")

            response_header = sample.find('responseHeader').text
            try:
                traceid = pat.match(response_header).group(1).strip()
            except AttributeError:
                traceid = None
            response_data = sample.find('responseData').text.replace('\r\n', '')
            fail_details.append({
                'sample': sample.get('lb'),
                "traceid": traceid,
                'data': truncate_text(response_data),
                'msg': truncate_text(",".join(msg))
            })

    result['fail_samples'] = fail_details
    result.update({
        "server": server,
        'job': name,
        'build_id': id,
    })
    return result

參考文檔:

  1. Jenkins DingTalk插件文檔: https://jenkinsci.github.io/dingtalk-plugin/guide/getting-started.html
  2. Jenkins Robot Framework插件文檔: https://plugins.jenkins.io/robot/
  3. 釘釘自定義機(jī)器人接入官方文檔: https://developers.dingtalk.com/document/app/custom-robot-access/title-nfv-794-g71
  4. RobotFramework測(cè)試用例的自行解析: http://www.reibang.com/p/3e1b7ba3a48c
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末辆脸,一起剝皮案震驚了整個(gè)濱河市但校,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌啡氢,老刑警劉巖状囱,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異倘是,居然都是意外死亡亭枷,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門搀崭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來叨粘,“玉大人,你說我怎么就攤上這事瘤睹∩茫” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵轰传,是天一觀的道長(zhǎng)驴党。 經(jīng)常有香客問我,道長(zhǎng)绸吸,這世上最難降的妖魔是什么鼻弧? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任设江,我火速辦了婚禮,結(jié)果婚禮上攘轩,老公的妹妹穿的比我還像新娘叉存。我一直安慰自己,他們只是感情好度帮,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布歼捏。 她就那樣靜靜地躺著,像睡著了一般笨篷。 火紅的嫁衣襯著肌膚如雪瞳秽。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天率翅,我揣著相機(jī)與錄音练俐,去河邊找鬼。 笑死冕臭,一個(gè)胖子當(dāng)著我的面吹牛腺晾,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播辜贵,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼悯蝉,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了托慨?” 一聲冷哼從身側(cè)響起鼻由,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎厚棵,沒想到半個(gè)月后蕉世,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡窟感,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年讨彼,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片柿祈。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡哈误,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出躏嚎,到底是詐尸還是另有隱情蜜自,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布卢佣,位于F島的核電站重荠,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏虚茶。R本人自食惡果不足惜戈鲁,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一仇参、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧婆殿,春花似錦诈乒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至消约,卻和暖如春肠鲫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背或粮。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工导饲, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人氯材。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓帜消,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親浓体。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354