async def test(self): with self.browser as browser: browser.set_window_size(2500, 1200) logging.info('Init the items info') project_info_dicts = dict() for project_name in self.project_names: last_item_dict = init_items_info(browser, project_name) logging.info( f'project {project_name}: Begin floor price: {last_item_dict["last_price"]}' ) project_info_dicts[project_name] = last_item_dict try: self.index += 1 # 检查是否要退出 with redis.Redis(connection_pool=self.pool) as r: exit = r.get('exit') if exit == 'True': raise ValueError('Time to exit') # 遍历项目获取信息 for project_name, last_item_dict in project_info_dicts.items(): last_item_dict = fetch_floor_info(browser, project_name, self.index, last_item_dict, self.threshold) project_info_dicts[project_name] = last_item_dict if self.index % 39 == 0: self.index = 0 except Exception as e: logging.info(traceback.format_exc()) send_email(mail_sender, mail_license, ['*****@*****.**'], 'The program meet bug', traceback.format_exc()) finally: browser.quit()
def run_single_project(project_name, proxy=False, driver_path='./chromedriver'): """ 运行单一的项目 1. 初始化 2. 进行数据的获取 """ with webdriver.Chrome(driver_path, chrome_options=set_chrome_options(proxy)) as browser: browser.set_window_size(2500, 1200) # 1. 初始化 last_item_dict = init_items_info(browser, project_name) logging.info(f'project {project_name}: Begin floor price: {last_item_dict["last_price"]}') begin_time = time.time() try: while True: # 项目获取信息 # 2. 进行数据的获取 last_item_dict = fetch_floor_info( browser, project_name, last_item_dict, threshold, cool_down_time) # 如果大于打log的时间则显示 if (time.time() - begin_time) >= logging_info_time: logging.info( f'project {project_name}: floor price: {last_item_dict["last_price"]}') begin_time = time.time() except Exception as e: logging.info(traceback.format_exc()) send_email( mail_sender, mail_license, 'The program meet bug', traceback.format_exc(), [mail_receivers[0]])
def send_email_to_register(info_dict): """把邮件传到相应已经注册的用户手中""" # 生成相应的信息 project_name = info_dict['project_name'] info_type = info_dict['type'] url = f'https://opensea.io/collection/{project_name}?search[sortAscending]=true&search[sortBy]=PRICE&search[toggles][0]=BUY_NOW' if info_type == 'price': last_price = info_dict['last_price'] new_price = info_dict['new_price'] title = f'project {project_name}: floor price changed, {last_price} -> {new_price}' send_text = get_html_mail_content( f'The project {project_name} has new floor price, check it, {last_price} -> {new_price}', url) else: item_list = info_dict['item_list'] title = f'project {project_name}: there have new list, {item_list}' send_text = get_html_mail_content( f'The project {project_name} has new list, {item_list}, check it', url) # 发送到相应的注册者手中 for receiver_address, project_names in mail_register_dict.items(): if project_name in project_names: send_email(mail_sender, mail_license, title, send_text, receiver_address)
def register(request): """ 注册 :param request: :return: """ if request.method == 'GET': return render(request, 'user/register.html') else: username = request.POST.get('username', '') password = request.POST.get('password', '') pswd_again = request.POST.get('pswd-again', '') email = request.POST.get('email', '') msg = register_info_logic(username, password, pswd_again, email) if msg != 'ok': log.error('register error:{}'.format(msg)) return render(request, 'user/register.html', {'error': msg}) else: User.objects.create_user(username=username, password=password, email=email) user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) request.session['user'] = username # 将session信息记录到浏览器 user_ = User.objects.get(username=username) request.session['user_id'] = user_.id # 将session信息记录到浏览器 response = redirect('/index/') send_email('*****@*****.**', '注册登录记录', report_id=username, register=True) log.info('用户: {} 注册并登录成功!'.format(username)) request.session.set_expiry(None) # 关闭浏览器后,session失效 return response
def test_httprunner(env_id, case_id_list, plan="", username="******"): logger.log_info('test_httprunner------->HttpRunner执行测试计划中<--------------') start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) begin_time = time.clock() case_num = len(case_id_list) content = [] j = 0 execute = Test_execute(env_id, case_id_list, run_mode="1", plan=plan) case_result = execute.test_case if "error" in case_result.keys(): logger.log_error(case_result["msg"]) return report_path = case_result['report_path'] for i in range(len(case_result['summary']['details'])): for records in case_result['summary']['details'][i]['records']: j += 1 records['id'] = j for data in records.get('meta_datas', {}).get('data', {}): body = json.dumps(data.get('request', {}).get('body', {}), ensure_ascii=False).replace('Markup', '').replace( '"', '') if body: import urllib.parse data['request']['body'] = urllib.parse.unquote( body.encode('utf-8').decode('unicode_escape').encode( 'utf-8').decode('unicode_escape')) content.append(case_result) summary = case_result.get('summary', {}) stat = summary.get('stat', {}).get('teststeps', {}) pass_num = stat.get('successes', 0) fail_num = stat.get('failures', 0) error_num = stat.get('errors', 0) skip_num = stat.get('skipped', 0) end_time = time.clock() totalTime = str(end_time - begin_time)[:6] + ' s' # pic_name = DrawPie(pass_num, fail_num, error_num, skip_num) report_name = plan.plan_name + "-" + str(start_time).replace(':', '-') report = Report(plan_id=plan.plan_id, report_name=report_name, content=content, case_num=case_num, pass_num=pass_num, fail_num=fail_num, error_num=error_num, pic_name="", skip_num=skip_num, totalTime=totalTime, startTime=start_time, update_user=username, make=1, report_path=report_path) report.save() if fail_num or error_num: title = plan.plan_name report_id = Report.objects.get(report_name=report_name).report_id send_email(title=title, report_id=report_id) logger.log_info('HttpRunner执行测试计划完成!')
def run(suite): cf.logging.info("================================== 测试开始 ==================================") with open(cf.report_file, 'wb') as f: # 从配置文件中读取 result = HTMLTestRunner(stream=f, title="Api Test", description="测试描述").run(suite) if result.failures: save_failures(result, cf.last_fails_file) if cf.send_email_after_run: send_email(cf.report_file) # 从配置文件中读取 cf.logging.info("================================== 测试结束 ==================================")
def run(suite): seps = '=' * 25 logging.info(f"{seps} 测试开始 {seps}") with open(config.report_file, 'wb') as f: # 从配置文件中读取 result = HTMLTestRunner(stream=f, title="Api Test", description="测试描述", tester="韩志超", verbosity=3).run(suite) if result.failures: if not os.path.exists(config.cache_dir): os.makedirs(config.cache_dir) save_failures(result, config.last_fails_file) if config.send_email_after_run: send_email(config.report_file) # 从配置文件中读取 logging.info(f"{seps} 测试结束 {seps}")
def run(suite): logging.info("=" * 30 + "测试开始" + "=" * 30) result = BeautifulReport(suite) result.report(filename='report_{}.html'.format(now), description='接口测试', report_dir=report_path, theme='theme_cyan') count_num = result.testsRun fail_num = result.failure_count error_num = result.error_count pass_num = result.success_count rate = (pass_num / count_num) * 100 print(count_num, pass_num, fail_num, error_num, rate) # 发送邮件 if send_email_after_run: send_email(get_lastest_file(), count_num, pass_num, fail_num, error_num, rate) logging.info("=" * 30 + "测试结束" + "=" * 30)
def run(suite): logging.info( "================================== 测试开始 ==================================" ) with open(report_file, 'wb') as f: result = HTMLTestRunner(stream=f, title="Api Test", description="测试描述", tester="yaocz").run(suite) if result.failures: save_failures(result, last_fails_file) if send_email_after_run: send_email(report_file) logging.info( "================================== 测试结束 ==================================" )
def run(suite): logging.info( "=====================================测试开始========================================" ) with open(report_file, 'wb') as f: #二进制写格式打开要生成的报告文件 result = HTMLTestRunner(stream=f, title="Api Test", description="测试描述", tester="念念").run(suite) if result.failures: # 保存失败用例序列化文件 save_failures(result, last_fails_file) if send_email_after_run: # 是否发送邮件 send_email(report_file) logging.info( "=====================================测试结束=======S=================================" )
def _send_event_email(self, inc_id, ics_filename, send_to): ''' Construct and send email with event to task owner ''' try: subject = "New task for incident %s assigned to you" % inc_id body = "" from_addr = self.options.get('smtpfrom') args = {"server": self.options.get('smtpserver')} port = self.options.get('smtpport') if port: args['port'] = port if self.options.get('use_ssl'): LOG.info("SSL connection to mailbox required") server = send_email.connect_smtp_ssl( self.options.get('smtpuser'), self.options.get('smtppw'), **args) elif self.options.get('use_start_tls'): LOG.info("TLS connection to mailbox required") server = send_email.connect_smtp(self.options.get('smtpuser'), self.options.get('smtppw'), **args) else: LOG.info("Using insecure SMTP connection") server = send_email.connect_smtp(self.options.get('smtpuser'), self.options.get('smtppw'), **args) send_email.send_email(server, from_addr, send_to, subject, body, [ ics_filename, ]) LOG.info("Mail sent") except Exception as e: # Let exception fall up for framework to handle LOG.error(traceback.format_exc()) raise
import unittest from lib.HTMLTestReportCN import HTMLTestRunner # from api_test_dealer.lib.HTMLTestRunner import HTMLTestRunner from config.config import * from lib.send_email import send_email import time logging.info( "================================== 测试开始 ==================================" ) suite = unittest.defaultTestLoader.discover(test_path) now = time.strftime('%Y-%m-%d_%H_%M', time.localtime(time.time())) report = REPORT_PATH + '\\%s.html' % now print(report) with open(report, 'wb') as f: # 从配置文件中读取 HTMLTestRunner(stream=f, title="经销商审批", description="测试描述", tester="lv and wang").run(suite) send_email(report) # 从配置文件中读取 logging.info( "================================== 测试结束 ==================================" )
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from config import config from lib.HTMLTestReportCN import HTMLTestRunner from lib.send_email import send_email config.logging.info("=" * 25 + "测试开始" + "=" * 25) suite = unittest.defaultTestLoader.discover( config.testcase_path) #找test开头的.py的测试用例路径 with open(config.report_file, "wb") as f: HTMLTestRunner(stream=f, title="测试报告", description="描述").run(suite) send_email(config.report_file) config.logging.info("邮件已发送") config.logging.info("=" * 25 + "测试结束" + "=" * 25)
def test_plan(env_id, case_id_list, plan="", username="******"): logger.log_info('test_plan------->默认方式执行测试计划中<--------------') start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) begin_time = time.clock() case_num = len(case_id_list) content = [] pass_num = 0 fail_num = 0 error_num = 0 i = 0 for case_id in case_id_list: execute = Test_execute(env_id, case_id_list, case_id=case_id, run_mode="0") case_result = execute.test_case content.append(case_result) end_time = time.clock() totalTime = str(end_time - begin_time)[:6] + ' s' for step in content: for s in step['step_list']: if s["result"] == "pass": pass_num += 1 i += 1 s['id'] = i if s["result"] == "fail": fail_num += 1 i += 1 s['id'] = i if s["result"] == "error": error_num += 1 i += 1 s['id'] = i pic_name = DrawPie(pass_num, fail_num, error_num) report_name = plan.plan_name + "-" + str(start_time) report = Report(plan_id=plan.plan_id, report_name=report_name, content=content, case_num=case_num, pass_num=pass_num, fail_num=fail_num, error_num=error_num, pic_name=pic_name, totalTime=totalTime, startTime=start_time, update_user='******', make=0) report.save() Plan.objects.filter(plan_id=plan.plan_id).update( update_user=username, update_time=datetime.now()) if fail_num or error_num: _to = [] user = User.objects.filter(is_superuser=1).filter(is_staff=1).filter( is_active=1).values() for u in user: _to.append(u['email']) if _to: title = plan.plan_name report_id = Report.objects.get(report_name=report_name).report_id send_email(_to=_to, title=title, report_id=report_id) else: logger.log_warning( '收件人邮箱为空,无法发送邮件!请在 EasyTeat接口测试平台 - 用户管理 模块中设置.') logger.log_info('默认方式测试计划执行完成!')
def test_httprunner(env_id, case_id_list, plan="", username="******"): logger.log_info('test_httprunner------->HttpRunner执行测试计划中<--------------') start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) begin_time = time.clock() case_num = len(case_id_list) content = [] j = 0 execute = Test_execute(env_id, case_id_list, run_mode="1", plan=plan) case_result = execute.test_case report_path = case_result['report_path'] for i in range(len(case_result['summary']['details'])): for records in case_result['summary']['details'][i]['records']: j += 1 records['id'] = j for data in records.get('meta_datas', {}).get('data', {}): body = json.dumps(data.get('request', {}).get('body', {}), ensure_ascii=False).replace('Markup', '').replace( '"', '') if body: import urllib.parse data['request']['body'] = urllib.parse.unquote( body.encode('utf-8').decode('unicode_escape').encode( 'utf-8').decode('unicode_escape')) content.append(case_result) summary = case_result.get('summary', {}) stat = summary.get('stat', {}).get('teststeps', {}) pass_num = stat.get('successes', 0) fail_num = stat.get('failures', 0) error_num = stat.get('errors', 0) end_time = time.clock() totalTime = str(end_time - begin_time)[:6] + ' s' pic_name = DrawPie(pass_num, fail_num, error_num) report_name = plan.plan_name + "-" + str(start_time).replace(':', '-') report = Report(plan_id=plan.plan_id, report_name=report_name, content=content, case_num=case_num, pass_num=pass_num, fail_num=fail_num, error_num=error_num, pic_name=pic_name, totalTime=totalTime, startTime=start_time, update_user=username, make=1, report_path=report_path) report.save() if fail_num or error_num: _to = [] user = User.objects.filter(is_superuser=1).filter(is_staff=1).filter( is_active=1).values() for u in user: _to.append(u['email']) if _to: title = plan.plan_name report_id = Report.objects.get(report_name=report_name).report_id send_email(_to=_to, title=title, report_id=report_id) else: logger.log_warning( '收件人邮箱为空,无法发送邮件!请在 EasyTeat接口测试平台 - 用户管理 模块中设置.') logger.log_info('HttpRunner执行测试计划完成!')
# coding=utf-8 # /usr/bin/env python3 ''' Author: swang Email: [email protected] date: 2020-11-05 14:57 ''' import HTMLTestRunner import unittest from config.config import * from lib.send_email import send_email logging.info("====================== 测试开始 ======================") suite = unittest.defaultTestLoader.discover(test_path) # 三方库HTMLTestRunner报告 with open(report_file, 'wb') as f: HTMLTestRunner.HTMLTestRunner(stream=f, title='sw_测试报告').run(suite) send_email(report_file) logging.info("====================== 测试结束 ======================")
pdf.cell(80, 10, 'Meter', 1) pdf.cell(40, 10, 'Energy Usage [kWh]', 1) pdf.ln() pdf.cell(10) pdf.set_font('arial', '', 10) for i in range(0, len(weekly_summary_consumption)): pdf.cell(80, 10, '%s' % (weekly_summary_consumption.Meter[i]), 1) pdf.cell(40, 10, '%s' % (weekly_summary_consumption.energy_kwh[i]), 1) pdf.ln() pdf.cell(10) #pdf.cell(-90) pdf.cell(90, 10, " ", 0, 2, 'C') pdf.cell(-25) pdf.image('charts/plot_treemap.png', x=None, y=None, w=200, h=280, type='', link='') pdf.output('output/reports/submetering_report_' + report_date + '.pdf', 'F') #send an email content = 'Please find the weekly report including energy consumption in ' + building_name + ', highlighting specific areas of consumption' send_email(content, receivers=recipient_email, subject='Energy consumption statistics for ' + building_name, file_location='output/reports/submetering_report_' + report_date + '.pdf', file_name='submeters_report')
#!/usr/bin/env python #-*- coding:utf-8 -*- import unittest import HTMLTestRunner from lib.get_data import get_data import os from lib.send_email import send_email from tester.user.test_add import * from tester.user.test_add_group import * if __name__ == '__main__': # suite = unittest.TestSuite() # suite.addTests(unittest.TestLoader().loadTestsFromName('tester.user.test_add.TestAdd')) # suite.addTests(unittest.TestLoader().loadTestsFromName('tester.user.test_add_group.TestAddGroup')) base_path = os.path.dirname(__file__) testdir = os.path.join(base_path + "\\tester\\user\\") discover = unittest.defaultTestLoader.discover(testdir, "test*.py") #生成测试报告 report_path = get_data("path", "report_file") fp = open(report_path, "wb") runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title=u'Api Test', description=u'用例执行情况', tester=u'fishyu') runner.run(discover) #runn.run(suite) fp.close() send_email() #将结果用邮件发送
def run_plan(*args, **kwargs): logger.log_info('run plan------->执行定时任务中<------{}----{}----'.format( args, kwargs)) start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) if not args and not kwargs: logger.log_error('查询定时任务计划为空!') return if "data" in str(kwargs): task_name = eval(kwargs["data"])["task_name"] task_id = eval(kwargs["data"])["task_id"] else: task_name = kwargs["task_name"] task_id = kwargs["task_id"] if "[" in str(args): args = eval(args[0]) begin_time = time.clock() content = [] report_path = [] pass_num = 0 fail_num = 0 error_num = 0 skip_num = 0 j = 0 case_num = len(args) for plan_id in args: try: plan = Plan.objects.get(plan_id=plan_id) except Plan.DoesNotExist: logger.log_error('设置定时任务的计划不存在!') return env_id = plan.environment_id case_id_list = eval(plan.content) begin_time = time.clock() execute = Test_execute(env_id, case_id_list, run_mode="1", plan=plan) case_result = execute.test_case if "error" in case_result.keys(): logger.log_error(case_result["msg"]) return report_path.append(case_result['report_path']) for i in range(len(case_result['summary']['details'])): for records in case_result['summary']['details'][i]['records']: j += 1 records['id'] = j for data in records.get('meta_datas', {}).get('data', {}): body = json.dumps(data.get('request', {}).get('body', {}), ensure_ascii=False).replace( 'Markup', '').replace('"', '') if body: import urllib.parse data['request']['body'] = urllib.parse.unquote( body.encode('utf-8').decode('unicode_escape'). encode('utf-8').decode('unicode_escape')) content.append(case_result) summary = case_result.get('summary', {}) stat = summary.get('stat', {}).get('teststeps', {}) pass_num += stat.get('successes', 0) fail_num += stat.get('failures', 0) error_num += stat.get('errors', 0) skip_num += stat.get('skipped', 0) end_time = time.clock() totalTime = str(end_time - begin_time)[:6] + ' s' # pic_name = DrawPie(pass_num, fail_num, error_num, skip_num) report_name = task_name + "-" + str(start_time).replace(':', '-') report = Report(plan_id="", report_name=report_name, content=content, case_num=case_num, pass_num=pass_num, fail_num=fail_num, error_num=error_num, pic_name="", totalTime=totalTime, skip_num=skip_num, startTime=start_time, update_user="******", make=1, report_path=report_path, task_id=task_id) report.save() if fail_num or error_num: title = task_name report_id = Report.objects.get(report_name=report_name).report_id send_email(title=title, report_id=report_id) logger.log_info('HttpRunner执行定时任务完成!{}--{}--'.format(args, kwargs))
for i in data['zero_data']['zero_readings_values'][building][0]: if int(i['duration'])>alert_threshold_minutes: timestamp=i['anomalies_details'][-1][0] alert={timestamp: 'Zero values recorded for the period of '+i['duration']+' minutes during normal occupancy hours in ' +building} recorded_alerts.update(alert) for building in buildings_name_nan_data: for i in data['nan_data']['nan_readings_values'][building][0]: timestamp=i['anomalies_details'][-1][0] alert={timestamp:'Missing values recorded for the period of '+i['duration']+' minutes during normal occupancy hours in ' +building} recorded_alerts.update(alert) ## save alerts in json output with open('output/'+formated_date+'.json', 'w') as fp: json.dump(recorded_alerts, fp) #%%SEND EMAIL NOTIFICATION IF ANY ALERTS RECORDED##### if len(recorded_alerts)>0: alerts='' for i in recorded_alerts: alerts=alerts+i+' '+recorded_alerts[i][:]+'\n\n' content=' Missing data events detected. Check the details below: \n\n'+alerts send_email( content, #Fill email address receivers = recipient_email_address, subject = 'Missing data events detected for energy meters at '+facility_name, file_location = None, file_name = None )
import unittest from lib.HTMLTestReportCN import HTMLTestRunner from config.config import * from lib.send_email import send_email logging.info("================================== 测试开始 ==================================") suite = unittest.defaultTestLoader.discover("./") fp = open(report_file, 'wb') runner = HTMLTestRunner(stream=fp, title='爱租机接口自动化测试', description='运行环境:MySQL(PyMySQL), Requests, unittest ') runner.run(suite, rerun=0, save_last_run=False) fp.close() send_email(report_file) # 发送邮件 logging.info("================================== 测试结束 ==================================")
import unittest from conf import config from lib.HTMLTestRunner_PY3 import HTMLTestRunner from lib.send_email import send_email # 遍历指定文件夹下及子包下的所有测试用例 test_ #all = unittest.defaultTestLoader.discover("testcase") # 绝对路径法: import os # testcase目录 case_file = os.path.join(config.project_path, 'testcase') all = unittest.defaultTestLoader.discover(case_file) if __name__ == "__main__": # unittest.TextTestRunner(verbosity=2).run(all) # 两个不能同时使用 config.logging.info("测试开始" + "=" * 50) with open(config.report_file, "wb") as f: # 二进制写模式 HTMLTestRunner(stream=f, title="User接口测试报告", description="测试报告").run(all) if config.is_send_email: send_email() config.logging.info("发送邮件成功") config.logging.info("测试结束" + "=" * 50)
import unittest from lib.HTMLTestReportCN import HTMLTestRunner # 修改导入路径 from config.config import * # 修改导入路径 from lib.send_email import send_email # 修改导入路径 logging.info("================================== 测试开始 ==================================") suite = unittest.defaultTestLoader.discover(test_path) # 从配置文件中读取 with open(report_file, 'wb') as f: # 从配置文件中读取 try: HTMLTestRunner(stream=f, title="Api Test", description="测试描述").run(suite) except Exception: print(123) if send_email_after_run: send_email(report_file) # 从配置文件中读取 logging.info("================================== 测试结束 ==================================")
def test_plan(env_id, case_id_list, plan="", username="******"): logger.log_info('test_plan------->默认方式执行测试计划中<--------------') start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) begin_time = time.clock() case_num = len(case_id_list) content = [] pass_num = 0 fail_num = 0 error_num = 0 skip_num = 0 i = 0 for case_id in case_id_list: execute = Test_execute(env_id, case_id_list, case_id=case_id, run_mode="0") case_result = execute.test_case if "error" in case_result.keys(): logger.log_error(case_result["msg"]) return content.append(case_result) end_time = time.clock() totalTime = str(end_time - begin_time)[:6] + ' s' for step in content: for s in step['step_list']: if s["result"] == "pass": pass_num += 1 i += 1 s['id'] = i if s["result"] == "fail": fail_num += 1 i += 1 s['id'] = i if s["result"] == "error": error_num += 1 i += 1 s['id'] = i if s["result"] == "skipped": skip_num += 1 i += 1 s['id'] = i # pic_name = DrawPie(pass_num, fail_num, error_num, skip_num) report_name = plan.plan_name + "-" + str(start_time) report = Report(plan_id=plan.plan_id, report_name=report_name, content=content, case_num=case_num, pass_num=pass_num, fail_num=fail_num, error_num=error_num, pic_name="", totalTime=totalTime, startTime=start_time, update_user=username, make=0, skip_num=skip_num) report.save() Plan.objects.filter(plan_id=plan.plan_id).update( update_user=username, update_time=datetime.now()) if fail_num or error_num: title = plan.plan_name report_id = Report.objects.get(report_name=report_name).report_id send_email(title=title, report_id=report_id) logger.log_info('默认方式测试计划执行完成!')
params1_list=total_energy_modelled_dc, details_name_par2='total_energy_generated_ac', params2_list=total_energy_generated_ac, details_name_par3='system_pr', params3_list=pr, details_name_par4='daily_energy', params4_list=daily_energy) #add pr to alerts log if data['alerts']: #define the filename filename = end_date[:10] + '.json' #path to the outpu directory file_path = 'output/' + name + '/' + filename # create a json file with data with open(file_path, 'w') as outfile: json.dump(data, outfile) outfile.write('\n') #%%generate pdf report and send emeil pdf_report_location = generate_pdf(name=name, end_date=end_date, pr_days=pr_days) #send an email send_email( content= 'Weekly energy performance report for PV system have been generated, please check the attachment', receivers=recipient_email_address, subject='Building1- PV System performance report', file_location=pdf_report_location, file_name='pv_performance_report')
def run_plan(): log.info('run plan------->执行测试计划中<--------------') start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) plan = Plan.objects.filter(is_task=1).all().values() if plan == None: log.error('查询定时任务计划为空!') return plan_id = plan[0]['plan_id'] env_id = plan[0]['environment_id'] case_id_list = eval(plan[0]['content']) begin_time = time.clock() case_num = len(case_id_list) content = [] pass_num = 0 fail_num = 0 error_num = 0 i = 0 for case_id in case_id_list: execute = Test_execute(env_id, case_id_list, case_id=case_id) case_result = execute.test_case content.append(case_result) end_time = time.clock() totalTime = str(end_time - begin_time)[:6] + ' s' for step in content: for s in step['step_list']: if s["result"] == "pass": pass_num += 1 i += 1 s['id'] = i if s["result"] == "fail": fail_num += 1 i += 1 s['id'] = i if s["result"] == "error": error_num += 1 i += 1 s['id'] = i pic_name = DrawPie(pass_num, fail_num, error_num) report_name = plan[0]['plan_name'] + "-" + str(start_time) report = Report(plan_id=plan_id, report_name=report_name, content=content, case_num=case_num, pass_num=pass_num, fail_num=fail_num, error_num=error_num, pic_name=pic_name, totalTime=totalTime, startTime=start_time, update_user='******', make=0) report.save() if fail_num or error_num: _to = [] user = User.objects.filter(is_superuser=1).filter(is_staff=1).filter( is_active=1).values() for u in user: _to.append(u['email']) if _to: title = plan[0]['plan_name'] report_id = Report.objects.get(report_name=report_name).report_id send_email(_to=_to, title=title, report_id=report_id) else: log.warning('收件人邮箱为空,无法发送邮件!请在 EasyTeat接口测试平台 - 用户管理 模块中设置.') log.info('测试任务执行完成!')