jira增删改查接口

安装

pip install atlassian-python-api==3.40.1 

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

使用

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

python 复制代码
{
    "name" : "xiaoming",
    "password" : "xiaoming123"
}

jira增删改查操作代码

python 复制代码
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可创建模板自动生成

具体使用场景示例

python 复制代码
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 root@10.1.3.25 密码: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
    )
相关推荐
@高山流水@3 天前
解决JIRA、Confluence用户自动注销、反复登录的问题
jira
vvw&13 天前
如何部署和配置项目管理工具 Plane - 开源 Jira 替代方案
linux·运维·服务器·ubuntu·开源·jira·plane
bread_00121 天前
jira导出文件乱码怎么解决
测试工具·jira
为啥我就不胖呢1 个月前
Jira使用笔记二 ScriptRunner 验证问题创建角色
笔记·jira
龙智DevSecOps解决方案2 个月前
工作管理实战指南:利用Jira、Confluence等Atlassian工具打破信息孤岛,增强团队协作【含免费指南】
atlassian·jira·工作管理
龙智DevSecOps解决方案2 个月前
一站式协作平台Jira新功能解读:AI驱动、个性化设置、灵活自定义等,助力项目管理更高效
人工智能·atlassian·jira
钉钉项目Teambition3 个月前
Jira Cloud涨价5%-20%,钉钉项目Teambition成优选替代
钉钉·jira·teambition
Wninacc4 个月前
jira敏捷开发管理工具视频教程Confluence工作流协同开发(2024)
java·javascript·eclipse·敏捷流程·jira
龙智DevSecOps解决方案4 个月前
龙智Atlassian解决方案实践案例:集成Jira、Confluence、JSM,助力某汽车行业客户实现高效项目管理
车载系统·atlassian·jira
龙智DevSecOps解决方案5 个月前
Atlassian Intelligence工具集解析:从自然语言到JQL处理,从虚拟代理到AI摘要、编辑器中的生成式AI等,全方位提升团队协作效率
人工智能·atlassian·软件需求·jira