jira增删改查接口

安装

pip install atlassian-python-api==3.40.1 

若安装失败,可尝试加上清华源(-i https://pypi.tuna.tsinghua.edu.cn/simple)

使用

为了防止信息泄露,可将账号密码单独存放到json文件中 ,如credential.json

{
    "name" : "xiaoming",
    "password" : "xiaoming123"
}

jira增删改查操作代码

from atlassian import Jira
from loguru import logger
import json


__all__ = ['JiraHelper']
user_name = ''
user_password = ''

credential = json.load(open('账号密码对应的json存放路径/credential.json'))

if not credential["name"] or not credential["password"]:
    print("Please add your jira username and password to ./credential.json file first then retry")
    quit()
    
class JiraHelper:
    jira_limit_return_number = 50 

    def __init__(self):
        self._jira_api  = Jira('https://jira.holomatic.cn',
            username=credential['name'],
                        password=credential['password'])

    def get_issues_info_by_jql(self, jql):
        """
        :param jql:like this format:
        statusCategory != Done AND (assignee = currentUser() OR  worklogAuthor = currentUser())
        """
        return_issues = []
        if not jql:
            return return_issues
        start = 0
        while True:
            issues = self._jira_api.jql(jql=jql, start=start)['issues']
            if not len(issues):
                break

            start = start + self.jira_limit_return_number
            return_issues.extend(issues)
        return return_issues

    def create_jira_issue(self, issue_fields):
        """
        :param issue_fields: jira issue fields, like this format:
        {
            'project': {'key': 'HOLOTOUR'},#project
            'issuetype': {'name': 'PR'}, #issuetype
            'summary': 'xx节点启动失败(This is a test)',#summary
            'customfield_11601': {'value': '高速'},# Domain 高速/城区/HPA
            'customfield_10407':{'value': 'SwIT'}, #Stage
            'components': [
                {"name": "诊断-高速"}
            ],# components
        }
        ...
        return json str response: like this:
        {'id': '68493', 'self': 'https://jira.holomatic.cn/browse/HOLOTOUR-8680', 'key': 'HOLOTOUR-8680'}
        {'errorMessages': [], 'errors': {'issuetype': 'issue type is required'}}
        """
        return self._jira_api.create_issue(fields=issue_fields)

    def update_issue(self, issue_key, fields):
        """
        :param issue_key: issue key
        {
            "project": { "key" : "HoloTour" },
            "summary": "issue title",
            "description": "this is description field",
            "issuetype": {"id": 10004, "name": "PR"},
            "assignee": {"name": "xuhongyuan"},
            "priority": {"name": "Highest"},
        }
        ...
        return json str response: like this:
        {'id': '68493', 'self': 'https://jira.holomatic.cn/browse/HOLOTOUR-8680', 'key': 'HOLOTOUR-8680'}
        {'errorMessages': [], 'errors': {'issuetype': 'issue type is required'}}
        """
        return self._jira_api.issue_update(issue_key=issue_key, fields=fields)

    def issue_add_comments(self, issue_key, comments):
        """
        add comments
        :param issue_key:
        :param comments:
         return json str response: like this:
        {'id': '68493', 'self': 'https://jira.holomatic.cn/browse/HOLOTOUR-8680', 'key': 'HOLOTOUR-8680'}
        {'errorMessages': [], 'errors': {'issuetype': 'issue type is required'}}
        """
        return self._jira_api.issue_add_comment(issue_key, comments)

    def add_attachment(self, issue_key, file_name):
        """
        :param issue_key:
        :param file_name:
         return json str response: like this:
        {'id': '68493', 'self': 'https://jira.holomatic.cn/browse/HOLOTOUR-8680', 'key': 'HOLOTOUR-8680'}
        {'errorMessages': [], 'errors': {'issuetype': 'issue type is required'}}
        """
        return self._jira_api.add_attachment(issue_key, filename=file_name)

    def get_issue_status(self,issue_key):
        """
        get issue status
        """
        return self._jira_api.get_issue_status(issue_key)

    def get_issue_labels(self,issue_key):
        """
        get_issue_labels
        """
        return self._jira_api.get_issue_labels(issue_key)
    
    def delete_issue(self,issue_key):
        return self._jira_api.delete_issue(issue_key)

if __name__ == '__main__':
    pass
    # # 根据jql查询issue
    # get_issue = jira.get_issues_info_by_jql(f"project = {project} AND key ={jira_keys} ")
    # issue_key = get_issue[0]["key"] # 
    # print(issue_key) 
    
    # 删除
    # jira= JiraHelper()
    # jira.delete_issue('QH1-18373')

针对经常重复创建的jira可创建模板自动生成
具体使用场景示例

from jira_helper import JiraHelper
import sys
import argparse
import json

def jira_operation(project: str,
                   node: str,
                   domain: str,
                   component: str,
                   version: str,
                   build_id: int,
                   bug_description: str,
                   tester_analysis: str,
                   jira_keys: str = None,  # HOLOTOUR-8680
                   ):
    jira = JiraHelper()
    allfields = jira._jira_api.get_all_fields()
    namemap = {field['name']: field['id'] for field in allfields}
    # print(namemap.keys())

    projects = [i["key"] for i in jira._jira_api.projects() ]
    print(projects)

    if project not in [i['key'] for i in jira._jira_api.projects()]:
        print("project不存在,请检查输入格式是否正确(GH5/HOLOTOUR/QH1)")
        return
    if build_id == None:
        print("build_id不存在,请检查输入格式是否正确")
        return
    if version not in ['S05','S06','DG']:
        print("version不存在,请检查输入格式是否为(S05/S06/DG)")
        return
    issue_dict = {
        # Basic
        f'{namemap["Project"]}': {"key": project},  # project
        f'{namemap["Issue Type"]}': {"name": 'PR'},  # issuetype
        f'{namemap["Summary"]}': f"{node}节点启动失败(This is a test)",  # summary
        f'{namemap["Domain"]}': {"value": domain},  # Domain 高速/城区/HPA
        f'{namemap["Stage"]}': {"value": "SwIT"},  # Stage
        f'{namemap["Component/s"]}': [
            {"name": component}
        ],  # components
        f'{namemap["Location"]}': "北京",  # Location
        f'{namemap["Detected by"]}': {"value": "测试"},  # Detected by
        # affectedVersion
        f'{namemap["Affects Version/s"]}': [{"name": version}],
        f'{namemap["Release Type"]}': {"value": "Internal"},  # Release Type
        # priority (Highest/High/Middle/Low)
        f'{namemap["Priority"]}': {"name": "High"},
        f'{namemap["Severity"]}': {"value": "B"},  # Severity
        f'{namemap["Req ID"]}': "n/a",  # Req ID
        f'{namemap["TC_ID"]}': "n/a",  # TC_ID
        f'{namemap["Assignee"]}': {"name": "xuhongyuan"},  # assignee
        # f'{namemap["Labels"]}':{'主线日测'},# 'labels'
        # Test
        f'{namemap["BuildID"]}': build_id,  # BuildID
        f'{namemap["Bug type"]}': {"value": "New"},  # Bug type
        # Bug Description
        f'{namemap["Bug Description"]}': bug_description,
        f'{namemap["与TC中的测试步骤一致"]}': {"value": "是"},  # TC中的测试步骤一致
        # Tester Analysis
        f'{namemap["Tester Analysis"]}': tester_analysis,
    }
    

    print(json.dumps(issue_dict,indent=4))

    # 创建jira
    response = jira.create_jira_issue(issue_dict)
    generate_link = 'https://jira.holomatic.cn/browse/' + response['key']
    print("jira创建成功,链接为:",generate_link)


if __name__ == "__main__":
    prog = 'python3 jira_helper.py'
    description = (
        'Run the script to implement the jira operation')

    sys.argv = ' '.join([
        f'cmd',
        f'--project HOLOTOUR',
        f'--domain 高速',
        f'--component 诊断-高速',
        f'--node HoloVSLeftLidar',
        f'--version S06',
        f'--build_id 750386',
        f'--report_html http://192.168.2.113:9998/HoloTour/SWIT-Smoke_Test//test_result_20230816103519_230816_103519.html',

    ]).split()

    parser = argparse.ArgumentParser(prog=prog, description=description)
    parser.add_argument('--project', type=str, default=None,
                        help=f'jira所属项目(HOLOTOUR/QH1)')
    parser.add_argument('--domain', type=str, default=None, help=f'Domian')
    parser.add_argument('--component', type=str, default=None, help=f'模块名')
    parser.add_argument('--node', type=str, default=None, help=f'模块节点名称')
    parser.add_argument('--version', type=str, default=None,
                        help=f'影响版本(如S6/DG),可根据build_id到CI查看')
    parser.add_argument('--build_id', type=int, default=None, help=f'build_id')
    parser.add_argument('--report_html', type=str,
                        default=None, help=f'测试报告链接')

    args = parser.parse_args()
    # user_name = args.username
    # user_password = args.password
    project = args.project
    domain = args.domain
    component = args.component
    node = args.node
    version = args.version
    build_id = args.build_id
    report_html = args.report_html
    
    

    bug_description = f"""
        参考测试报告:
        {report_html}
    """

    tester_analysis = f"""
        1)登录MDC台架:
        ssh [email protected] 密码:Huawei12#$

        2)进入测试目录smoke/node_launch
        export HOLO_ROOT=/opt/usr/swtest/holotour/{build_id}/output/aarch64-linux-mdc610-2022-1230-llvm/release/target
        cd $HOLO_ROOT
        cd smoke/node_launch

        3)查看测试脚本并验证
        上述目录可以找到以下两个脚本
        行车: holo_node_car_pilot.sh
        泊车: holo_node_car_parking.sh

        从中start部分可以找到对应节点的启动命令,并在$HOLO_ROOT目录下执行相关命令验证问题。
        log文件的输出目录一般是${{HOLO_LOG_ROOT}}/log

        如果节点启动不成功, 可以按以下顺序排查:
        a)检查MANIFEST配置参数arguments是否正确. 注意节点启动命令参数来自于$HOLO_ROOT/share/mdc_manifest/outputcfg/Host0DpMachine对应节点的MANIFEST.json.
        b)其次检查arguments中的参数yaml文件是否安装了正确的版本.
        c)log中输出的其它错误
    """

    jira_operation(
        project=project,
        domain=domain,
        component=component,
        node=node,
        version=version,
        build_id=build_id,
        bug_description=bug_description,
        tester_analysis=tester_analysis
    )

你可能感兴趣的:(jira)