安装
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_issuesstart = 0while True:issues = self._jira_api.jql(jql=jql, start=start)['issues']if not len(issues):breakstart = start + self.jira_limit_return_numberreturn_issues.extend(issues)return return_issuesdef 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 jsondef 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)")returnif build_id == None:print("build_id不存在,请检查输入格式是否正确")returnif version not in ['S05','S06','DG']:print("version不存在,请检查输入格式是否为(S05/S06/DG)")returnissue_dict = {# Basicf'{namemap["Project"]}': {"key": project}, # projectf'{namemap["Issue Type"]}': {"name": 'PR'}, # issuetypef'{namemap["Summary"]}': f"{node}节点启动失败(This is a test)", # summaryf'{namemap["Domain"]}': {"value": domain}, # Domain 高速/城区/HPAf'{namemap["Stage"]}': {"value": "SwIT"}, # Stagef'{namemap["Component/s"]}': [{"name": component}], # componentsf'{namemap["Location"]}': "北京", # Locationf'{namemap["Detected by"]}': {"value": "测试"}, # Detected by# affectedVersionf'{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"}, # Severityf'{namemap["Req ID"]}': "n/a", # Req IDf'{namemap["TC_ID"]}': "n/a", # TC_IDf'{namemap["Assignee"]}': {"name": "xuhongyuan"}, # assignee# f'{namemap["Labels"]}':{'主线日测'},# 'labels'# Testf'{namemap["BuildID"]}': build_id, # BuildIDf'{namemap["Bug type"]}': {"value": "New"}, # Bug type# Bug Descriptionf'{namemap["Bug Description"]}': bug_description,f'{namemap["与TC中的测试步骤一致"]}': {"value": "是"}, # TC中的测试步骤一致# Tester Analysisf'{namemap["Tester Analysis"]}': tester_analysis,}print(json.dumps(issue_dict,indent=4))# 创建jiraresponse = 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.passwordproject = args.projectdomain = args.domaincomponent = args.componentnode = args.nodeversion = args.versionbuild_id = args.build_idreport_html = args.report_htmlbug_description = f"""参考测试报告:{report_html}"""tester_analysis = f"""1)登录MDC台架:ssh root@10.1.3.25 密码:Huawei12#$2)进入测试目录smoke/node_launchexport HOLO_ROOT=/opt/usr/swtest/holotour/{build_id}/output/aarch64-linux-mdc610-2022-1230-llvm/release/targetcd $HOLO_ROOTcd smoke/node_launch3)查看测试脚本并验证上述目录可以找到以下两个脚本行车: 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)