DingDing.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import os
  2. import socket
  3. from pathlib import Path
  4. from dingtalkchatbot.chatbot import DingtalkChatbot
  5. import datetime
  6. # 获取jenkins构建信息和本次报告地址
  7. import jenkins # 安装pip install python-jenkins
  8. from common.yaml_util import read_config_yaml, read_yaml_out_time_url, write_yaml_out_time_url
  9. # 获取本机IP
  10. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  11. # s.connect(("8.8.8.8", 80))
  12. # ip = s.getsockname()[0]
  13. # jenkins登录地址
  14. jenkins_url = "http://121.229.175.82:63222/"
  15. # 获取jenkins对象
  16. server = jenkins.Jenkins(jenkins_url, username='jiangwei', password='jW@123456') # Jenkins登录名 ,密码
  17. # job名称
  18. job_name = "job/qccq/" # Jenkins运行任务名称
  19. # job的url地址
  20. job_url = jenkins_url + job_name
  21. # 获取最后一次构建
  22. job_last_build_url = server.get_info(job_name)['lastBuild']['url']
  23. # 报告地址
  24. report_url = job_last_build_url + 'allure' # 'allure'为我的Jenkins全局工具配置中allure别名
  25. if "localhost" in report_url:
  26. report_url = report_url.replace("localhost", ip)
  27. else:
  28. report_url = report_url
  29. '''
  30. 钉钉推送方法:
  31. 读取report文件中"prometheusData.txt",循环遍历获取需要的值。
  32. 使用钉钉机器人的接口,拼接后推送text
  33. '''
  34. # url = 'https://oapi.dingtalk.com/robot/send?access_token=f8566d2ed0feb8dc3bf2856df161241a8cf5a4c76af3d903abcabfdebebdff0e' # webhook
  35. def DingTalkSend(info):
  36. d = {}
  37. # 获取项目绝对路径
  38. path = Path(__file__).parent
  39. file = '/report/export/prometheusData.txt'
  40. print(rf"{path}" + rf"{file}")
  41. # 打开prometheusData 获取需要发送的信息
  42. # f = open(rf"{path}" + rf"{file}", 'r', encoding='UTF-8')
  43. f = open(os.getcwd() + file, 'r', encoding='UTF-8')
  44. for lines in f:
  45. for c in lines:
  46. launch_name = lines.strip('\n').split(' ')[0]
  47. num = lines.strip('\n').split(' ')[1]
  48. d.update({launch_name: num})
  49. print(d)
  50. f.close()
  51. retries_run = d.get('launch_retries_run') # 运行总数
  52. print('运行总数:{}'.format(retries_run))
  53. status_defects = d.get('launch_problems_test_defects') # 未执行数
  54. if status_defects is None:
  55. status_defects = "0"
  56. else:
  57. status_defects = status_defects
  58. print(status_defects)
  59. status_passed = d.get('launch_status_passed') # 通过数量
  60. print('通过数量:{}'.format(status_passed))
  61. status_failed = d.get('launch_status_failed') # 不通过数量
  62. print('不通过数量:{}'.format(status_failed))
  63. out_time_url = str(read_yaml_out_time_url())
  64. print(out_time_url)
  65. # 钉钉推送
  66. text = (
  67. f"<font color=\'#FFA500\'>[通知] </font>青春重庆-{info}报告"
  68. "\n\n用例运行总数: " + retries_run +
  69. # "\n\n用例未执行数: " + status_defects +
  70. "\n\n用例通过数量: " + status_passed +
  71. '''\n\n<font>用例失败数量: </font><font color=\'#FF0000\' size=2>%s</font> \n\n''' +
  72. "\n\n响应超过2s接口汇总:"+ out_time_url+
  73. # "\n\n构建地址:\n" + job_url +
  74. "\n\n测试报告地址: \n" + report_url +
  75. "\n\n播报时间: " + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) % (status_defects)
  76. dd_robot = DingtalkChatbot(read_config_yaml("dingding", "test_yunwin_webhook"))
  77. ret = dd_robot.send_markdown(title='青春重庆', text=text, is_at_all=False)
  78. print(ret)
  79. def dingtalk_send_warning(msg):
  80. """
  81. 发送报警超时消息dingtalkchatbot
  82. :param msg: 请求返回res
  83. :return: none
  84. """
  85. try:
  86. res_time = round(msg.elapsed.total_seconds() * 1000, 2)
  87. text = f"<font color=\'#FFA500\'>[通知] </font>青春重庆-报警"\
  88. f"\n\n>请求接口路径: {msg.url} " \
  89. f"\n\n>请求体: {str(msg.request.body).replace('%','')} "\
  90. f"\n\n>接口响应时间: {res_time}毫秒 " \
  91. f"\n\n>播报时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} "
  92. dd_robot = DingtalkChatbot(read_config_yaml("dingding", "prod_webhook"))
  93. dd_robot.send_markdown(title='青春重庆', text=text, is_at_all=False)
  94. except Exception as e:
  95. raise e
  96. if __name__ == '__main__':
  97. # dingtalk_send_warning("测试")
  98. DingTalkSend("生产APP巡检")