blob: 1bc35a3ebbc1b817fd9f3b57fcb5f4f311f5592c [file] [log] [blame]
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +02001#!/usr/bin/env python
2import datetime
3import sys
4import logging
5from collections import defaultdict, OrderedDict
6
7import jira
8import argparse
9
10from testrail import TestRail
11from testrail.test import Test
abaraniukf0344a82018-12-10 11:01:43 +020012# from testrail_api import APIClient
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +020013from functools32 import lru_cache
14
15logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
16LOG = logging.getLogger(__name__)
17
18
19def run_cli():
20 cli = argparse.ArgumentParser(
21 prog="Report generator",
22 description="Command line tool for generate summary report")
23
24 commands = cli.add_subparsers(
25 title="Operation commands",
26 dest="command")
27
28 cli_process = commands.add_parser(
29 "create-report",
30 help="Create summary report",
31 description="Create summary report")
abaraniukf0344a82018-12-10 11:01:43 +020032 cli_process_link = commands.add_parser(
33 "mark-fails",
34 help="Extract linked bugs from previous reports",
35 description="Extract linked bugs from previous reports"
36 " and mark current")
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +020037 cli_process.add_argument(
38 "-T", "--testrail-host", dest="testrail_host",
39 required=True,
40 help="TestRail hostname")
41 cli_process.add_argument(
42 "-U", "--testrail-user", dest="testrail_user",
43 required=True,
44 help="TestRail user email")
45 cli_process.add_argument(
46 "-K", "--testrail-user-key", dest="testrail_user_key",
47 required=True,
48 help="TestRail user key")
49 cli_process.add_argument(
50 "-R", "--testrail-plan", dest="testrail_plan",
51 required=True,
52 help="TestRail test plan for analize")
53 cli_process.add_argument(
54 "-P", "--testrail-project", dest="testrail_project",
55 required=True,
56 help="TestRail project name")
57 cli_process.add_argument(
58 "--testrail-only-run", dest="testrail_only_run",
59 help="Analize only one run in selected plan")
60 cli_process.add_argument(
61 "--out-type", dest="out_type", choices=["text", "html", 'md', 'none'],
62 default='none',
63 help="Select output format for report table. "
64 "By default print nothing (none).")
65 cli_process.add_argument(
66 "--sort-by", dest="sort_by", default='fails',
67 choices=["fails", "blocks", 'project', 'priority', 'status'],
68 help="Select sorting column. By deafult table sort by fails")
69 cli_process.add_argument(
70 "--push-to-testrail", dest="push_report_flag", action="store_true",
71 default=False,
72 help="Save report in plan description")
73 cli_process.add_argument(
74 "-j", "--jira-host", dest="jira_host",
75 required=True,
76 help="JIRA hostname")
77 cli_process.add_argument(
78 "-u", "--jira-user", dest="jira_user_id",
79 required=True,
80 help="JIRA username")
81 cli_process.add_argument(
82 "-p", "--jira-password", dest="jira_user_password",
83 required=True,
84 help="JIRA user password")
85
abaraniukf0344a82018-12-10 11:01:43 +020086 # link fail bugs parameters
87 cli_process_link.add_argument(
88 "-T", "--testrail-host", dest="testrail_host",
89 required=True,
90 help="TestRail hostname")
91 cli_process_link.add_argument(
92 "-U", "--testrail-user", dest="testrail_user",
93 required=True,
94 help="TestRail user email")
95 cli_process_link.add_argument(
96 "-K", "--testrail-user-key", dest="testrail_user_key",
97 required=True,
98 help="TestRail user key")
99 cli_process_link.add_argument(
100 "-R", "--testrail-plan", dest="testrail_plan",
101 required=True,
102 help="TestRail test plan for analize")
103 cli_process_link.add_argument(
104 "-M", "--testrail-marked-plan", dest="testrail_marked_plan",
105 required=False,
106 help="TestRail test plan for parse")
107 cli_process_link.add_argument(
108 "-P", "--testrail-project", dest="testrail_project",
109 required=True,
110 help="TestRail project name")
111 cli_process_link.add_argument(
112 "--testrail-only-run", dest="testrail_only_run",
113 help="Name to update only specified run in selected plan")
114 cli_process_link.add_argument(
115 "--push-to-testrail", dest="update_report_flag", action="store_true",
116 default=False,
117 help="Save report in plan description")
118
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200119 if len(sys.argv) == 1:
120 cli.print_help()
121 sys.exit(1)
122
123 return cli.parse_args()
124
125
126def get_runs(t_client, plan_name, run_name):
127 LOG.info("Get runs from plan - {}".format(plan_name))
128 ret = []
129 plan = t_client.plan(plan_name)
Dennis Dmitrieva0622182018-05-09 04:39:19 +0300130 if plan:
131 for e in plan.entries:
132 for r in e.runs:
133 LOG.info("Run {} #{}".format(r.name, r.id))
134 if run_name is not None and r.name != run_name:
135 continue
136 ret.append(r)
137 else:
138 LOG.warning("Plan {} is empty".format(plan_name))
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200139 return ret
140
141
142def get_all_results(t_client, list_of_runs):
143 ret = []
144 for run in list_of_runs:
145 ret.extend(get_results(t_client, run))
146 return ret
147
148
abaraniukf0344a82018-12-10 11:01:43 +0200149def get_all_failed_results(t_client, list_of_runs, result_type):
150 """
151 returned result format:
152 [[run(id,name), result(id,status,defects...), test(id,name..)],
153 [run(id,name), result(id,status,defects...), test(id,name..)],
154 ...]
155 """
156 ret = []
157 for run in list_of_runs:
158 ret.extend(get_failed_results(t_client, run, result_type))
159 return ret
160
161
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200162@lru_cache()
163def fetch_test(api, test_id, run_id):
164 return Test(api.test_with_id(test_id, run_id))
165
166
167def get_results(t_client, run):
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200168 LOG.info("Get results for run - {}".format(run.name))
169 results = t_client.results(run)
170 ret = [(run.id, r) for r in results
171 if r.raw_data()['status_id'] is not None and
Dennis Dmitrievef6af332018-05-09 05:21:21 +0300172 r.raw_data()['defects'] is not None]
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200173 for r in ret:
174 run_id, result = r
175 test = fetch_test(result.api, result.raw_data()['test_id'], run_id)
176 LOG.info("Test {} - {} - {}".format(test.title, result.status.name,
177 ','.join(result.defects)))
178 return ret
179
180
abaraniukf0344a82018-12-10 11:01:43 +0200181def get_failed_results(t_client, run, result_type):
182 """
183 returned result format:
184 [run(id,name),
185 result(id,status,defects...),
186 test(id,name..)]
187 """
188 LOG.info("Get results for run - {}".format(run.name))
Dennis Dmitrievb4277022019-06-18 18:56:01 +0300189 results = t_client.results(run)
abaraniukf0344a82018-12-10 11:01:43 +0200190 results_with_test = []
Dennis Dmitriev7cab5482019-05-22 15:40:14 +0300191 if result_type == '5':
abaraniukf0344a82018-12-10 11:01:43 +0200192 ret = [(run, r) for r in results
193 if r.raw_data()['status_id'] is int(result_type) and
194 r.raw_data()['defects'] is None]
195 else:
196 ret = [(run, r) for r in results
197 if r.raw_data()['status_id'] is not None and
198 r.raw_data()['defects'] is not None]
199 for r in ret:
200 run, result = r
201 test = fetch_test(result.api, result.raw_data()['test_id'], run.id)
202 LOG.info("Test {} - {} - {} - {}"
203 .format(test.title, result.status.name,
204 result.raw_data()['status_id'],
205 ','.join(result.defects)))
206 results_with_test.append([run, result, test])
207 return results_with_test
208
209
210def mark_failed_results(t_cl, marked_res, failed_res, t_h):
211 """
212 Extract list tests with defect and compare it with tests to be marked,
213 and add defects and result from marked tests
214 Returned result format:
215 [[target_tests_to_update_with_defect, target_run_id],
216 [target_tests_to_update_with_defect, target_run_id],
217 ...]
218 """
219 LOG.info("Extract marked tests and attach to failed")
220
221 def generate_result(t_c, tst, m_r, m_t):
222 link_comment = "{url}/index.php?/tests/view/{uid}".format(
223 url=t_h, uid=m_t.id)
224 tmp_result = t_c.result()
225 tmp_result.test = tst
226 tmp_result.status = m_r.status
227 tmp_result.comment = "Result taked from: " + link_comment
228 tmp_result.defects = [str(m_r.defects[0])]
229 return tmp_result
230
231 # def check_if_marked():
232 # if ret.count()
233
234 ret = []
235 for run, result, test in failed_res:
236 for m_run, m_result, m_test in marked_res:
237 if run.name == m_run.name \
238 and test.title == m_test.title:
239 LOG.info(" MARKED FOUND: Run:{} test: .. {}-{}"
240 .format(run.id, test.title[-72:],
241 m_result.defects[0]))
242 ret.append([generate_result(t_cl, test, m_result,
243 m_test), run.id])
244 return ret
245
246
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200247@lru_cache()
248def get_defect_info(j_client, defect):
249 LOG.info("Get info about issue {}".format(defect))
250 try:
251 issue = j_client.issue(defect)
252 except jira.exceptions.JIRAError as e:
253 if e.status_code == 404:
254 LOG.error("Defect {} wasn't found in Jira".format(defect))
255 return {
256 'id': defect,
257 'title': "Title for #{} not found".format(defect),
258 'project': "Not found",
259 'priority': "Not found",
260 'status': "Not found",
261 'url': "Not found"
262 }
263 else:
264 raise
265 return {
266 'id': issue.key,
267 'title': issue.fields.summary,
268 'project': issue.fields.project.key,
269 'priority': issue.fields.priority.name,
270 'status': issue.fields.status.name,
271 'url': issue.permalink()
272 }
273
274
275def get_defects_table(jira_client, list_of_results, sort_by):
276 LOG.info("Collect report table")
277 table = defaultdict(dict)
278 for run_id, result in list_of_results:
279 for defect in result.defects:
280 if defect not in table:
281 info = get_defect_info(jira_client, defect)
282
283 table[defect].update(info)
284 table[defect]['results'] = set([(run_id, result)])
285 if result.status.name.lower() == 'blocked':
286 table[defect]['blocks'] = 1
287 table[defect]['fails'] = 0
288 else:
289 table[defect]['fails'] = 1
290 table[defect]['blocks'] = 0
291 else:
292 table[defect]['results'].add((run_id, result))
293 if result.status.name.lower() == 'blocked':
294 table[defect]['blocks'] += 1
295 else:
296 table[defect]['fails'] += 1
297 return OrderedDict(
298 sorted(table.items(), key=lambda i: i[1][sort_by], reverse=True))
299
300
301def get_text_table(table):
302 LOG.info("Generation text table")
303 lines = []
304 line = ("{fails:^5} | {blocks:^5} | {project:^10} | {priority:^15} | "
305 "{status:^15} | {bug:^100} | {tests} ")
306
307 def title_uid(r):
308 run_id, result = r
309 test = fetch_test(result.api, result.raw_data()['test_id'], run_id)
310 return {
311 "title": test.title,
312 "uid": test.id}
313
314 def list_of_defect_tests(results):
315 ret = ["[{title} #{uid}]".format(**title_uid(r)) for
316 r in results]
317 return ' '.join(ret)
318
319 lines.append(line.format(fails='FAILS', blocks='BLOCKS', project="PROJECT",
320 priority="PRIORITY", status="STATUS", bug="BUG",
321 tests="TESTS"))
322 for k in table:
323 one = table[k]
324 data = {
325 "fails": one['fails'],
326 "blocks": one['blocks'],
327 "project": one['project'],
328 "priority": one['priority'],
329 "status": one['status'],
330 "bug": "{uid} {title}".format(uid=one['id'], title=one['title']),
331 "tests": list_of_defect_tests(one['results'])
332 }
333 lines.append(line.format(**data))
334 return '\n'.join(lines)
335
336
337def get_md_table(table):
338 LOG.info("Generation MD table")
339 lines = []
340 line = ("||{fails} | {blocks} | {project} | {priority} | "
341 "{status} | {bug} | {tests} ")
342
343 def title_uid_link(r):
344 run_id, result = r
345 test = fetch_test(result.api, result.raw_data()['test_id'], run_id)
346
347 return {
348 "title": test.title.replace('[', '{').replace(']', '}'),
349 "uid": test.id,
350 "link": "{url}/index.php?/tests/view/{uid}".format(
abaraniukf0344a82018-12-10 11:01:43 +0200351 url=test.api._conf()['url'], uid=test.id)
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200352 }
353
354 def list_of_defect_tests(results):
355 ret = ["<[{title} #{uid}]({link})>".format(**title_uid_link(r))
356 for r in results]
357 return ' '.join(ret)
358
359 lines.append(line.format(fails='|:FAILS', blocks=':BLOCKS',
360 project=":PROJECT", priority=":PRIORITY",
361 status=":STATUS", bug=":BUG", tests=":TESTS"))
362 for k in table:
363 one = table[k]
364 data = {
365 "fails": one['fails'],
366 "blocks": one['blocks'],
367 "project": one['project'],
368 "priority": one['priority'],
369 "status": one['status'],
370 "bug": "[{uid} {title}]({url})".format(
371 uid=one['id'],
372 title=one['title'].replace('[', '{').replace(']', '}'),
373 url=one['url']),
374 "tests": list_of_defect_tests(one['results'])
375 }
376 lines.append(line.format(**data))
377 return '\n'.join(lines)
378
379
380def get_html_table(table):
381 LOG.info("Generation HTML table")
382 html = "<table>{lines}</table>"
383 lines = []
384 line = ("<tr><th>{fails:^5}</th><th>{blocks:^5}</th><th>{project:^10}</th>"
385 "<th>{priority:^15}</th>"
386 "<th>{status:^15}</th><th>{bug:^100}</th><th>{tests}</th></tr>")
387 lines.append(line.format(fails='FAILS', blocks='BLOCKS', project="PROJECT",
388 priority="PRIORITY", status="STATUS", bug="BUG",
389 tests="TESTS"))
390
391 def title_uid_link(r):
392 run_id, result = r
393 test = fetch_test(result.api, result.raw_data()['test_id'], run_id)
394
395 return {
396 "title": test.title,
397 "uid": test.id,
398 "link": "{url}/index.php?/tests/view/{uid}".format(
abaraniukf0344a82018-12-10 11:01:43 +0200399 url=test.api._conf()['url'], uid=test.id)
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200400 }
401
402 def list_of_defect_tests(results):
403 ret = ["<a href='{link}'>{title} #{uid}</a>".format(
abaraniukf0344a82018-12-10 11:01:43 +0200404 **title_uid_link(r)) for r in results]
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200405 return ' '.join(ret)
406
407 for k in table:
408 one = table[k]
409 data = {
410 "fails": one['fails'],
411 "blocks": one['blocks'],
412 "project": one['project'],
413 "priority": one['priority'],
414 "status": one['status'],
415 "bug": "<a href='{url}'>{uid} {title}</a>".format(
416 uid=one['id'], title=one['title'], url=one['url']),
417 "tests": list_of_defect_tests(one['results'])
418 }
419 lines.append(line.format(**data))
420 return html.format(lines=''.join(lines))
421
422
423def out_table(out_type, table):
424 if out_type == 'none':
425 return
426 elif out_type == 'html':
427 print(get_html_table(table))
428 elif out_type == 'md':
429 print(get_md_table(table))
430 else:
431 print(get_text_table(table))
432
433
434def push_report(t_client, plan_name, table):
435 LOG.info("Push report table into plan - {}".format(plan_name))
436 text = "Bugs Statistics (generated on {date})\n" \
437 "=======================================================\n" \
438 "{table}".format(
abaraniukf0344a82018-12-10 11:01:43 +0200439 date=datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Y"),
440 table=get_md_table(table))
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200441 plan = t_client.plan(plan_name)
Dennis Dmitrievef6af332018-05-09 05:21:21 +0300442 if plan:
443 plan.description = text
444 plan.api._post(
445 'update_plan/{}'.format(plan.id),
446 {
447 'name': plan.name,
448 'description': plan.description,
449 'milestone_id': plan.milestone.id
450 })
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200451
452
abaraniukf0344a82018-12-10 11:01:43 +0200453def update_report(t_client, plan_name, tests_table):
454 LOG.info("Update report table into plan - {}".format(plan_name)
455 + "\n===\nList tests to udate:")
456 plan = t_client.plan(plan_name)
457 if plan:
458 for r_test, run in tests_table:
459 t_client.add(r_test)
460 print(r_test.test.title)
461 LOG.info("\n===\nUpdate plan finished - {}".format(plan_name))
462
463
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200464def create_report(**kwargs):
465 j_host = kwargs.get('jira_host')
466 j_user = kwargs.get('jira_user_id')
467 j_user_pwd = kwargs.get('jira_user_password')
468 t_host = kwargs.get('testrail_host')
469 t_user = kwargs.get('testrail_user')
470 t_user_key = kwargs.get('testrail_user_key')
471 t_plan = kwargs.get('testrail_plan')
472 t_project = kwargs.get('testrail_project')
473 t_a_run = kwargs.get('testrail_only_run')
474 o_type = kwargs.get('out_type')
475 push_report_flag = kwargs.get('push_report_flag')
476 sort_by = kwargs.get('sort_by')
477
478 t_client = TestRail(email=t_user, key=t_user_key, url=t_host)
479 t_client.set_project_id(t_client.project(t_project).id)
480
481 j_client = jira.JIRA(j_host, basic_auth=(j_user, j_user_pwd))
482
483 runs = get_runs(t_client, t_plan, t_a_run)
484 results = get_all_results(t_client, runs)
485 table = get_defects_table(j_client, results, sort_by)
486 out_table(o_type, table)
487 if push_report_flag:
488 push_report(t_client, t_plan, table)
489
490
abaraniukf0344a82018-12-10 11:01:43 +0200491def mark_fails(**kwargs):
492 testrail_host = kwargs.get('testrail_host')
493 testrail_user = kwargs.get('testrail_user')
494 testrail_user_key = kwargs.get('testrail_user_key')
495 testrail_plan = kwargs.get('testrail_plan')
496 testrail_m_plan = kwargs.get('testrail_marked_plan')
497 testrail_project = kwargs.get('testrail_project')
498 testrail_active_run = kwargs.get('testrail_only_run')
499 if testrail_active_run == '':
500 testrail_active_run = None
501 update_report_flag = kwargs.get('update_report_flag')
502
503 testrail_client = TestRail(email=testrail_user, key=testrail_user_key,
504 url=testrail_host)
505 testrail_client.set_project_id(testrail_client.project(
506 testrail_project).id)
507
508 # Get list runs with marked results
509 marked_runs = get_runs(testrail_client, testrail_m_plan,
510 testrail_active_run)
511
512 # Get list runs to update
513 runs = get_runs(testrail_client, testrail_plan, testrail_active_run)
514
515 # Get list (failed, prod_failed, test_failed,skipped..) tests with defects
516 marked_results = get_all_failed_results(testrail_client, marked_runs,
517 '2,3,4,5,6,7,8,9')
518
519 # Get list (failed) tests without defects to mark
520 failed_results = get_all_failed_results(testrail_client,
521 runs, '5') # 5-failed
522
523 # Generate list tests to update based on compare (defected
524 # results for tests with failed and not defected)
525 tests_to_update = mark_failed_results(testrail_client, marked_results,
526 failed_results, testrail_host)
527
528 if update_report_flag:
529 update_report(testrail_client, testrail_plan, tests_to_update)
530
531
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200532COMMAND_MAP = {
abaraniukf0344a82018-12-10 11:01:43 +0200533 'create-report': create_report,
534 'mark-fails': mark_fails
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200535}
536
537
538def main():
539 args = run_cli()
540 COMMAND_MAP[args.command](**vars(args))
541
Dina Belovae6fdffb2017-09-19 13:58:34 -0700542
Dmitry Tyzhnenkofb0516d2016-11-17 17:55:26 +0200543if __name__ == '__main__':
544 main()