利用python每日统计JIRA上的BUG变动情况,并发送到钉钉群

BUG管理系统有很多,我们公司选用的是JIRA。而质量部除了需要每周有周报,为了每日掌握当天的BUG状态,也可以每日统计“关闭”、“新建”的BUG,及时同步到钉钉群。

如图:

利用python每日统计JIRA上的BUG变动情况,并发送到钉钉群_第1张图片

 

发送消息到钉钉群比较简单,钉钉开发者文档有详细的API说明:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq

先做一个调用钉钉API的dingding.py模块:

# __author__ = 'ak'


import requests
import json
import sys


def run(msg, urls, atMobiles):
    """
    调用钉钉
    :param msg:  要发送消息   此模块只支持文本消息
    :param urls:   钉钉群的token,列表传入,循环发送
    :param atMobiles:  需要at的人,列表,每个元素为手机号
    :return: 
    """
    data1 = {
         "msgtype": "text",
         "text": {
             "content": msg
         },
         "at": {
             "atMobiles": atMobiles,
             "isAtAll": False
         }
     }

    header = {'Content-Type': 'application/json; charset=utf-8'}
    print(data1)
    for url in urls:
        temp1 = requests.post(url=url, data=json.dumps(data1), headers=header)

        print(temp1)


if __name__ == '__main__':
    urls1 = [r'https://oapi.dingtalk.com/robot/send?access_token=123', ]
    msg1 = sys.argv[1]
    atMobiles1 = []
    run(msg=msg1, urls=urls1, atMobiles=atMobiles1)

此部分比较简单,随后开始需求整理。

先吃饭,留坑。

续。

JIRA官网也有详细的API文档和JQL讲解。JQL用来从JIRA的筛选器内筛选出需要的数据,API可以从http(s) 接口获取JQL筛查出的数据。Python第三方库中有封装好可供调用的jira库,文档地址:https://jira.readthedocs.io/en/latest/

 

需要注意:JIRA可以提供https服务,也可以提供http服务,如https服务,登录时需要注意证书问题。此处可能是唯一需要注意的点。

公司需求:针对每个项目,统计该项目当日创建、解决、关闭和BUG池中剩余BUG数目。

针对这些需求构造不同的jql,以项目名称和时间作为参数。

get_bugs 方法统计各个jql执行后的数目

all_bugs 方法构造需要发送钉钉字符串

new_data_format 方法实际发送

需要传入参数:统计的项目、jira所在服务器、用户名、密码、钉钉发送的token列表等。代码如下:

from jira import JIRA
import datetime
from dingding import run


class JiraParse:
    def __init__(self, name, password, server, project, max_results):
        self.name = name
        self.password = password
        self.server = server
        self.project = project
        self.bug_jql = 'project = {project} AND issuetype = 缺陷 AND status in (Open, "In Progress", Reopened, Resolved)'
        self.closed_jql = 'project = {project} AND issuetype = 缺陷 AND status = Closed AND updated ' \
                          '>= {today} AND updated <= {tomorrow} ORDER BY created DESC'
        self.solved_jql = 'project = {project} AND issuetype = 缺陷 AND resolved >= {today} AND resolved <= {tomorrow}'
        self.created_jql = 'project = {project} AND issuetype = 缺陷 AND created >= {today} AND created <= {tomorrow}'
        self.max_results = max_results
        self.jira_object = JIRA(server=self.server, basic_auth=(self.name, self.password), options={'verify':False})

    def search_issues(self, jql):
        issues = self.jira_object.search_issues(
            jql_str=jql, maxResults=self.max_results)
        return issues

    def get_bugs(self, jql, _dict):
        """

        :param jql:  需要查询的sql
        :param _dict:  放入_dict中,
        :return:  返回该sql计数 sum_bug
        """
        sum_bug = 0
        temp = self.search_issues(jql)
        for each in temp:
            sum_bug += 1
            temp1 = str(each.fields.priority)
            if _dict.get(temp1):
                _dict[temp1] += 1
            else:
                _dict[temp1] = 1

        return sum_bug

    def all_bugs(self):
        """
        bug_dict 不确定以后需要不需要,先统计出来放着。
        :return:
        """
        now_time = datetime.datetime.now()
        today = now_time.strftime('%Y-%m-%d')
        tomorrow = (now_time + datetime.timedelta(days=1)).strftime('%Y-%m-%d')
        # sum_solved = 0
        # sum_created = 0
        # sum_closed = 0
        bug_dict = dict()
        sum_solved = self.get_bugs(self.solved_jql.format(project=self.project, today=today, tomorrow=tomorrow),
                                   bug_dict)
        sum_created = self.get_bugs(self.created_jql.format(project=self.project, today=today, tomorrow=tomorrow),
                                    bug_dict)
        sum_closed = self.get_bugs(self.closed_jql.format(project=self.project, today=today, tomorrow=tomorrow),
                                   bug_dict)

        bug_str = '今日新增 {created} 个bug.\n今日关闭 {closed} 个bug.\n' \
                  '今日RD解决 {solved} 个bug.\n\n'.format(closed=sum_closed, created=sum_created, solved=sum_solved)
        # str1 = '优先级为 {priority} 的Bug共有 {number}个。'
        # for each in bug_dict:
        #     bug_str += str1.format(priority=each, number=bug_dict[each])
        # bug_str += '\n\n'
        return bug_str

    def new_data_format(self):
        """
        构造发送字符串
        :return:
        """
        now_time = datetime.datetime.now()
        # today = now_time.strftime('%Y-%m-%d')
        # tomorrow = (now_time + datetime.timedelta(days=1)).strftime('%Y-%m-%d')
        now = now_time.strftime('%Y-%m-%d %H:%M:%S')

        final = ''
        final += now + ': \n' + self.all_bugs()

        d = {'Highest': {'number': 0, 'keys': []}, 'High': {'number': 0, 'keys': []},
             'Medium': {'number': 0, 'keys': []}, 'Low': {'number': 0, 'keys': []},
             'Lowest': {'number': 0, 'keys': []}}
        issues = self.search_issues(self.bug_jql.format(project=self.project))
        for each in issues:
            priority = each.fields.priority
            priority_str = str(priority)
            key = each.key
            if d[priority_str]['number']:
                d[priority_str]['number'] += 1
                d[priority_str]['keys'].append(key)
            else:
                d[priority_str]['number'] = 1
                d[priority_str]['keys'].append(key)

        str_0 = '{project} 当前未关闭Bug共有{number}个 :\n'.format(project=self.project, number=str(len(issues)))
        str1 = '优先级为 {priority} 的Bug共有 {number}个。 '
        str2 = 'bug编号为: '

        for each in d:
            str1_2 = str1.format(priority=each, number=d[each]['number'])
            str_0 += str1_2
            if each in ['Highest', 'High'] and d.get(each)['number'] != 0:
                str2_2 = str2 + ','.join(d[each]['keys'])
                str_0 += str2_2 + '\n'
            else:
                str_0 += '\n'

        final += str_0


        print(d)
        return final




if __name__ == '__main__':
    project = 'YQTP '
    server = r'https://xxx.com:443'
    name = 'name'
    password = 'password'
    max_results = 1000
    atMobiles1 = []
    urls1 = ['token1', 'token2']
    j = JiraParse(server=server, name=name, password=password, project=project, max_results=max_results)
    msg1 = j.new_data_format()
    run(msg=msg1, urls=urls1, atMobiles=atMobiles1)

 

你可能感兴趣的:(测试脚本)