예제 #1
0
파일: ibtrader.py 프로젝트: Sdoof/ib-1
    def check_positions(self):
        db_positions = Fill.current_positions().rename(
            columns={'trade_amt': 'db'})
        broker_positions = self.get_broker_positions().rename(
            columns={'trade_amt': 'broker'})

        if len(broker_positions) == 0:
            broker_positions = pandas.DataFrame(
                columns=['contractid', 'broker'])
        if len(db_positions) == 0:
            db_positions = pandas.DataFrame(columns=['contractid', 'db'])

        check_df = db_positions.merge(broker_positions,
                                      on='contractid',
                                      how='outer').fillna(0)

        if all(check_df.db == check_df.broker):
            return True

        else:  #positions don't match
            fills = self.broker_fills()

            email = Email(
                "CRITICAL: {0} DB Broker Positions Don't Match".format(
                    datetime.datetime.now()),
                '{0} <br> {1}'.format(check_df.to_html(index=False),
                                      fills.to_html(index=False)))
            email.send(EMAIL_CRITICAL)

            self.reconcile()

            return False
예제 #2
0
def run(testname: str):
    '''
    运行测试用例生成html报告
    :param testname: 测试人
    :return:
    '''
    c = config()
    #获取测试账号转换为str
    test_username = str(c.username)

    with open(c.API_REPORT_PATH, 'wb') as f:
        suite = unittest.defaultTestLoader.discover(start_dir=c.APICASE_PATH,
                                                    pattern='test_*.py')
        runner = HTMLTestRunner(stream=f,
                                verbosity=2,
                                title='API测试报告',
                                description='接口html测试报告',
                                tester=testname,
                                test_user=test_username)
        runner.run(suite)
    e = Email(server='smtp.qq.com',
              sender='*****@*****.**',
              password='******',
              receiver='*****@*****.**',
              title='老马发送的今天的API自动化报告又来了,请注意查看!',
              message='来了来了,你的测试API自动化报告!!,注意如果收不到邮件注意查看垃圾箱还是退信了!',
              path=[c.API_REPORT_PATH, c.log_file_name])
    e.send()
예제 #3
0
파일: ibtrader.py 프로젝트: mcherkassky/ib
	def reconcile(self):
		broker_fills = self.broker_fills()

		# db_fills = Fill.filter_df(func.date(Fill.dt) == datetime.datetime.today().date())
		query = session.query(Fill, Order.ib_id).join(Order).filter(func.date(Fill.dt) == datetime.datetime.today().date())
		db_fills = pandas.read_sql(query.statement, query.session.bind)
		broker_fills.ib_id = broker_fills.ib_id.astype('int64')

		comparison = broker_fills.merge(db_fills.drop('dt', 1), on=['contractid', 'ib_id', 'trade_amt', 'trade_px'], how='left')
		unaccounted_fills = comparison[comparison.orderid.isnull()]

		for i in xrange(len(unaccounted_fills)):

			fill = unaccounted_fills.iloc[i]
			order = Order.filter(and_(Order.ib_id == int(fill.ib_id), func.date(Order.dt) == fill['dt'].date())).first()

			if order:
				unaccounted_fills.ix[fill.name,'orderid'] = order.id
			else:
				email = Email("CRITICAL: {0} Fill Reconciliation Failed".format(datetime.datetime.now()),"")
				email.send(EMAIL_CRITICAL)
				return False

		upload = unaccounted_fills.drop(['cusip','id','ib_id'],1)
		upload_dict = upload.to_dict(orient='records')

		Fill.__table__.insert().execute(upload_dict)

		email = Email("CRITICAL: {0} Reconciliation Success".format(datetime.datetime.now()),"")
		email.send(EMAIL_CRITICAL)
		return True
예제 #4
0
def create_report():
    # test_suit = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(CASE_PATH,
                                                   pattern='test_*.py',
                                                   top_level_dir=None)
    # for test in discover:
    #     for test_case in test:
    #         test_suit.addTest(test_case)
    now = time.strftime('%Y-%m-%d_%H_%M', time.localtime(time.time()))
    report = REPORT_PATH + '\\report%s.html' % now
    last_file = find_last_file(REPORT_PATH)
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title=reporttitle,
                                description=description)
        runner.run(discover)

    e = Email(title=title,
              message=message,
              receiver=receiver,
              server=server,
              sender=sender,
              password=password,
              path=last_file)
    e.send()
예제 #5
0
def send_report():
    path = os.path.join(os.path.dirname(os.getcwd()), "report", "report.html")

    e = Email(title='API自动化测试报告',
              message='这是今天的tms重构UI自动化测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.163.com',
              sender='*****@*****.**',
              password='******',
              path=path)
    e.send()
예제 #6
0
파일: data.py 프로젝트: Sdoof/ib-1
	def check(cls, threshold = 120):
		try:
			heartbeats = pandas.read_csv('heart.beat')
		except IOError:
			cls.initialize()
		heartbeats.last_seen = pandas.to_datetime(heartbeats.last_seen)

		for i in xrange(len(heartbeats)):
			heartbeat = heartbeats.iloc[i]

			if (datetime.datetime.now() - heartbeat.last_seen).seconds > threshold:
				email = Email("CRITICAL", "{0} Heartbeat Dead".format(heartbeat['name']))
				email.send(['*****@*****.**'])
예제 #7
0
파일: ibtrader.py 프로젝트: mcherkassky/ib
	def run(self):
		i = 0
		last_error = None

		while True:
			try:
				if self.check_integrity():
					pending = self.pending_orders()

					if pending:
						self.send_to_ib(pending)

					now = datetime.datetime.now()
					if now.time() > datetime.time(14,05) and now.time() < datetime.time(14,15):
						break

					if i%6 == 0:
						print 'Heartbeat: {0}'.format(now)



					i +=1
					last_error = None

					# #update heartbeat table
					Heartbeat.update('Trader')

					time.sleep(10)

				else:
					print "{0} DB Integrity Check Failed: Sleeping for 30 seconds".format(datetime.datetime.now())
					i = 0
					time.sleep(30)

			except Exception as e:
				error_str = traceback.format_exc()

				if not (type(last_error) == type(e) and last_error.args == e.args):
					email = Email("{0} IBTrader Bugging Out".format(datetime.datetime.now()), error_str)
					email.send(EMAIL_CRITICAL)

					#restart/rollback db session
					session.rollback()

				last_error = e
예제 #8
0
def run(testname):
    '''运行测试用例生成html报告'''
    report_path = REPORT_PATH + '\\web_report.html'
    with open(report_path, 'wb') as f:
        suite = unittest.defaultTestLoader.discover(start_dir=WEBCASE_PATH,
                                                    pattern='test_*.py')
        runner = HTMLTestRunner(stream=f,
                                verbosity=2,
                                title='web自动化测试报告',
                                description='这是第一次的测试报告',
                                tester=testname)
        runner.run(suite)
    e = Email(server='smtp.qq.com',
              sender='*****@*****.**',
              password='******',
              receiver='*****@*****.**',
              title='web自动化测试报告',
              message='测试后台web自动化测试报告!!',
              path=report_path)
    e.send()
예제 #9
0
파일: ibtrader.py 프로젝트: Sdoof/ib-1
    def reconcile(self):
        broker_fills = self.broker_fills()

        # db_fills = Fill.filter_df(func.date(Fill.dt) == datetime.datetime.today().date())
        query = session.query(Fill, Order.ib_id).join(Order).filter(
            func.date(Fill.dt) == datetime.datetime.today().date())
        db_fills = pandas.read_sql(query.statement, query.session.bind)
        broker_fills.ib_id = broker_fills.ib_id.astype('int64')

        comparison = broker_fills.merge(
            db_fills.drop('dt', 1),
            on=['contractid', 'ib_id', 'trade_amt', 'trade_px'],
            how='left')
        unaccounted_fills = comparison[comparison.orderid.isnull()]

        for i in xrange(len(unaccounted_fills)):

            fill = unaccounted_fills.iloc[i]
            order = Order.filter(
                and_(Order.ib_id == int(fill.ib_id),
                     func.date(Order.dt) == fill['dt'].date())).first()

            if order:
                unaccounted_fills.ix[fill.name, 'orderid'] = order.id
            else:
                email = Email(
                    "CRITICAL: {0} Fill Reconciliation Failed".format(
                        datetime.datetime.now()), "")
                email.send(EMAIL_CRITICAL)
                return False

        upload = unaccounted_fills.drop(['cusip', 'id', 'ib_id'], 1)
        upload_dict = upload.to_dict(orient='records')

        Fill.__table__.insert().execute(upload_dict)

        email = Email(
            "CRITICAL: {0} Reconciliation Success".format(
                datetime.datetime.now()), "")
        email.send(EMAIL_CRITICAL)
        return True
예제 #10
0
파일: ibtrader.py 프로젝트: mcherkassky/ib
	def check_positions(self):
		db_positions = Fill.current_positions().rename(columns={'trade_amt': 'db'})
		broker_positions = self.get_broker_positions().rename(columns={'trade_amt': 'broker'})

		if len(broker_positions) == 0:
			broker_positions = pandas.DataFrame(columns=['contractid', 'broker'])
		if len(db_positions) == 0:
			db_positions = pandas.DataFrame(columns=['contractid', 'db'])

		check_df = db_positions.merge(broker_positions, on='contractid', how='outer').fillna(0)

		if all(check_df.db == check_df.broker):
			return True

		else: #positions don't match
			fills = self.broker_fills()

			email = Email("CRITICAL: {0} DB Broker Positions Don't Match".format(datetime.datetime.now()),
							'{0} <br> {1}'.format(check_df.to_html(index=False), fills.to_html(index=False)))
			email.send(EMAIL_CRITICAL)

			self.reconcile()

			return False
    def run_holidayReply_case(self,is_reply,is_available):
        time.sleep(1)
        replySettingCheckboxEle = self.find_element(self.mailSettingPageHolidayReplyPage_replySettingCheckbox_loc)
        if is_reply:
            with allure.step("勾选回复设置选择框"):
                if "is-checked" not in replySettingCheckboxEle.get_attribute("class"):
                    replySettingCheckboxEle.click()
            if is_available:
                with allure.step("点击结束日期选择框"):
                    self.find_element(self.mailSettingPageHolidayReplyPage_endDateInput_loc).click()
                time.sleep(0.2)
                with allure.step("点击当前日期的后一天"):
                    self.find_element(self.mailSettingPageHolidayReplyPage_currentTodayAfterDay_loc).click()
            else:
                with allure.step("点击开始日期选择框"):
                    self.find_element(self.mailSettingPageHolidayReplyPage_startDateInput_loc).click()
                time.sleep(0.2)
                with allure.step("点击当前日期的前一天"):
                    self.find_element(self.mailSettingPageHolidayReplyPage_currentTodayBeforeDay_loc).click()
                with allure.step("点击结束日期选择框"):
                    self.find_element(self.mailSettingPageHolidayReplyPage_endDateInput_loc).click()
                time.sleep(0.2)
                with allure.step("点击当前日期的前一天"):
                    self.find_element(self.mailSettingPageHolidayReplyPage_currentTodayBeforeDay_loc).click()
            # with allure.step("获取当前日期"):
            #     currentDate_text = self.find_element(self.mailSettingPageHolidayReplyPage_currentDate_loc).text
            #     currentDate = int(re.findall('\d+',currentDate_text)[0])

        else:
            with allure.step("不勾选回复设置选择框"):
                if "is-checked" in replySettingCheckboxEle.get_attribute("class"):
                    replySettingCheckboxEle.click()

        with allure.step("点击保存按钮"):
            self.find_element(self.mailSettingPageHolidayReplyPage_saveBtn_loc).click()

        with allure.step("发送一封邮件至该SaaS账号"):
            emailTitle = random_name() + "--节假回复测试--" + time.strftime("%Y%m%d.%H.%M.%S")
            e = Email(
                title=emailTitle,
                message=random_text(),
                receiver="*****@*****.**",
                server='smtp.aliyun.com',
                sender='*****@*****.**',
                password='******'
            )
            e.send()
        time.sleep(60)
        with allure.step("回到邮件首页"):
            self.find_element(self.emailHomePage_loc).click()
        time.sleep(3)
        with allure.step("查询收件箱是否收到发送的邮件"):
            num = 0
            while True:
                allMailSubjects = self.get_elementText(self.recipientBoxPage_emailSubject_loc,index="all")
                if emailTitle in allMailSubjects:
                    break
                else:
                    num = num + 1
                    time.sleep(20)
                if num == 35:
                    raise Exception("收件箱没有主题是:{}的邮件,请排查".format(emailTitle))
        with allure.step("切换到已发箱"):
            self.find_element(self.recipientBoxPage_hasSendBoxBtn_loc).click()
        with allure.step("查看是否有回复邮件"):
            allMailSubjects_hasSendBox = self.get_elementText(self.recipientBoxPage_emailSubject_loc,index="all")
            replyMailSubject_hasSendBox = "Re:"+emailTitle
            if is_available:
                if replyMailSubject_hasSendBox not in allMailSubjects_hasSendBox:
                    raise Exception("已发箱中没有主题是:{}的邮件,请排查".format(replyMailSubject_hasSendBox))
                # with allure.step("点击主题是:{}的邮件".format(replyMailSubject_hasSendBox)):
                #     self.find_element()
            else:
                if replyMailSubject_hasSendBox in allMailSubjects_hasSendBox:
                    raise Exception("已发箱中有主题是:{}的邮件,请排查".format(replyMailSubject_hasSendBox))
예제 #12
0
    def test_search(self):
        datas = ExcelReader(self.excel).data
        for d in datas:
            with self.subTest(data=d):
                self.sub_setUp()
                self.page.search(d['search'])
                time.sleep(2)
                self.page = BaiDuResultPage(self.page)  # 页面跳转到result page
                links = self.page.result_links
                for link in links:
                    logger.info(link.text)
                self.sub_tearDown()


if __name__ == '__main__':
    report = REPORT_PATH + '\\report.html'
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='从0搭建测试框架 灰蓝',
                                description='修改html报告')
        runner.run(TestBaiDu('test_search'))
    e = Email(title='测试报告',
              message='这是今天的测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.qq.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()
 def run_addBlackList_case(self, is_del):
     time.sleep(1)
     with allure.step("判断是否有黑名单列表,如果有,则全部删除"):
         headCheckboxEle = self.find_element(
             self.mailSettingPageBlackListPage_headCheckbox_loc)
         if "is-disabled" not in headCheckboxEle.get_attribute("class"):
             headCheckboxEle.click()
             with allure.step("点击删除按钮"):
                 self.find_element(
                     self.mailSettingPageBlackListPage_delBlackListBtn_loc
                 ).click()
                 time.sleep(4)
     with allure.step("点击添加按钮"):
         self.find_element(
             self.mailSettingPageBlackListPage_addBlackListBtn_loc).click()
     with allure.step("输入邮件地址"):
         self.find_element(
             self.mailSettingPageBlackListPage_emailAccountInput_loc
         ).send_keys("163.com")
     with allure.step("输入邮件主题"):
         self.find_element(
             self.mailSettingPageBlackListPage_emailSubjectInput_loc
         ).send_keys("广告")
     if is_del:
         with allure.step("点击直接删除按钮"):
             self.mouseClick(
                 self.mailSettingPageBlackListPage_directDelBtn_loc)
     else:
         with allure.step("点击存放到垃圾箱按钮"):
             self.mouseClick(
                 self.mailSettingPageBlackListPage_storeRubbishBoxBtn_loc)
     with allure.step("点击确定按钮"):
         self.find_element(
             self.mailSettingPageBlackListPage_sureAddBlackListBtn_loc
         ).click()
     with allure.step("判断添加成功后的toast提示是否正确"):
         toast_text = self.get_elementText(self.toast_loc)
         if toast_text != "保存成功":
             raise Exception("添加成功黑名单的toast提示不对,:{}".format(toast_text))
     with allure.step("判断添加之后,列表中是否存在相应信息"):
         allMatchInfomations = self.get_elementText(
             self.mailSettingPageBlackListPage_matchInfomationTd_loc,
             index="all")
         allHandleWays = self.get_elementText(
             self.mailSettingPageBlackListPage_handleWayTd_loc, index="all")
         if "163.com" not in allMatchInfomations or "广告" not in allMatchInfomations:
             raise Exception("添加的黑名单,不在黑名单列表中")
         for handleWay in allHandleWays:
             if is_del:
                 if handleWay != "直接删除":
                     raise Exception("列表中的处理方式:{},不对".format(handleWay))
             else:
                 if handleWay != "存入垃圾箱":
                     raise Exception("列表中的处理方式:{},不对".format(handleWay))
     with allure.step("给该账号发送两封邮件"):
         emailTitle_account = random_name() + "--黑名单测试--" + time.strftime(
             "%Y%m%d.%H.%M.%S")
         emailTitle_subject = random_name(
         ) + "--黑名单测试--广告--" + time.strftime("%Y%m%d.%H.%M.%S")
         e1 = Email(title=emailTitle_account,
                    message=random_text(),
                    receiver="*****@*****.**",
                    server='smtp.163.com',
                    sender='*****@*****.**',
                    password='******')
         e1.send()
         e2 = Email(title=emailTitle_subject,
                    message=random_text(),
                    receiver="*****@*****.**",
                    server='smtp.aliyun.com',
                    sender='*****@*****.**',
                    password='******')
         e2.send()
     time.sleep(150)
     with allure.step("回到邮件首页"):
         self.find_element(self.emailHomePage_loc).click()
     if is_del:
         boxName = "回收箱"
     else:
         boxName = "垃圾箱"
     boxNameBtn_loc = (By.XPATH,
                       self.recipientBoxPage_approvalBoxBtn_loc[1].replace(
                           "审批箱", boxName))
     self.find_element(boxNameBtn_loc).click()
     with allure.step("查询{}是否收到发送的邮件".format(boxName)):
         num = 0
         while True:
             time.sleep(3)
             subjects = self.get_elementText(
                 self.recipientBoxPage_emailSubject_loc, index="all")
             # allMailSubjects = []
             # for subject in subjects:
             #     allMailSubjects.append(subject.split("】")[1])
             if emailTitle_subject in subjects and emailTitle_account in subjects:
                 break
             else:
                 num = num + 1
                 time.sleep(20)
                 self.find_element(boxNameBtn_loc).click()
             if num == 15:
                 raise Exception("{}箱没有主题是:{}或者{}的邮件,请排查".format(
                     boxName, emailTitle_account, emailTitle_subject))
     with allure.step("回到设置tab页面"):
         self.find_element(self.recipientBoxPage_settingTabBtn_loc).click()
     time.sleep(0.3)
     with allure.step("单个删除黑名单"):
         with allure.step("获取第一个黑名单"):
             firstBlackListEle = self.find_element(
                 self.mailSettingPageBlackListPage_matchInfomationTd_loc)
             firstBlackList_matchInfomationText = firstBlackListEle.text
             print(firstBlackList_matchInfomationText)
         with allure.step("悬浮第一个黑名单"):
             self.mouseHover(
                 self.mailSettingPageBlackListPage_matchInfomationTd_loc)
         time.sleep(0.2)
         with allure.step("点击单个删除按钮"):
             self.find_element(
                 self.mailSettingPageBlackListPage_delSingleBlackListBtn_loc
             ).click()
         with allure.step("判断删除成功后的toast提示是否正确"):
             toast_text = self.get_elementText(self.toast_loc)
             if toast_text != "删除成功":
                 raise Exception("删除黑名单的toast提示不对,:{}".format(toast_text))
         with allure.step("判断列表中是否还有删除的黑名单信息"):
             allMatchInfomations = self.get_elementText(
                 self.mailSettingPageBlackListPage_matchInfomationTd_loc,
                 index="all")
             if firstBlackList_matchInfomationText in allMatchInfomations:
                 raise Exception("已删除的黑名单信息:{},仍然在列表中:{}".format(
                     firstBlackList_matchInfomationText,
                     allMatchInfomations))
     time.sleep(0.3)
     with allure.step("全部删除黑名单"):
         with allure.step("勾选全选选择框"):
             self.find_element(
                 self.mailSettingPageBlackListPage_headCheckbox_loc).click(
                 )
         with allure.step("点击删除按钮"):
             self.find_element(
                 self.mailSettingPageBlackListPage_delBlackListBtn_loc
             ).click()
         with allure.step("判断删除成功后的toast提示是否正确"):
             toast_text = self.get_elementText(self.toast_loc)
             if toast_text != "删除成功":
                 raise Exception("删除黑名单的toast提示不对,:{}".format(toast_text))
         with allure.step("判断列表中是否还有黑名单信息"):
             time.sleep(1)
             if self.is_element_exist(
                     self.
                     mailSettingPageBlackListPage_matchInfomationTd_loc[1]):
                 raise Exception("已经全部删除了黑名单,但是列表中中依然存在黑名单信息")
예제 #14
0
def runnerjob(scheduler, id, mailaddress, jobcontent, jobtarget):
    logger.info('开始执行定时任务,用例集id是' + str(id))
    logger.info(str(scheduler.get_jobs()))
    # close_old_connections()
    #获取用例集ID
    case_list = list(
        Template_detail.objects.filter(templateid_id=id, isdelete=0).values(
            'usercaseid_id', 'usercaseid__usercasename', 'usercaseid__isequal',
            'usercaseid__isnotequal').order_by('usercaseid__run_order'))
    casecount = len(case_list)
    templatename = list(
        Template_info.objects.filter(id=id, isdelete=0).values(
            'templatename', 'publicpar', 'pnumber'))  #用例集名称
    pubpar = templatename[0]['publicpar']  #公共参数
    if (pubpar != None and pubpar != ""):
        pubpar = eval(pubpar)

    #添加测试报告
    okcount = 0
    failcount = 0
    errorcount = 0
    r_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    obj = Interface_result(templateid_id=id,
                           totalcount=casecount,
                           okcount=okcount,
                           failcount=failcount,
                           errorcount=errorcount,
                           runnertime=r_time)
    obj.save()
    objid = obj.id

    #执行用例集
    for i in range(0, casecount):
        caseid = case_list[i]["usercaseid_id"]
        casename = case_list[i]["usercaseid__usercasename"]
        isequal = case_list[i]["usercaseid__isequal"]
        isnotequal = case_list[i]["usercaseid__isnotequal"]
        actualdata = ''

        #判断用例名字是否为空
        if casename != "":

            #检查点
            jp = Jsonprint()
            ttype = 0  #检查状态
            try:
                r = case_task_views.run_case(caseid, pubpar)  #接口返回结果
                r_text = json.loads(r)  #JSON转字典
                r_result = r_text['msg']
                r_type = r_text['resulttype']  #结果状态
                actualdata = jp.show_real_data(r_text['actual_url'],
                                               r_text['actual_headers'],
                                               r_text['actual_data'])

                if r_type == 200:

                    if isequal != '':
                        check_str = jp.checkresult(r_result, isequal,
                                                   1)  #检查点内容
                    elif isnotequal != '':
                        check_str = jp.checkresult(r_result, isnotequal,
                                                   2)  #检查点内容
                    else:
                        check_str = ''
                    ttype = jp.resulttype  #检查状态
                else:
                    check_str = ''
                    errorcount += 1
            except Exception as e:
                logger.error(caseid + casename + '执行失败!' + str(e))
                errorcount += 1
                check_str = ''
                r_result = str(e)

            #计算通过数和失败数
            if ttype == 1:
                okcount += 1
            elif ttype == 2:
                failcount += 1

            #添加测试报告明细
            objlist = Interface_result_detail(
                resultid_id=objid,
                usercaseid_id=caseid,
                type=ttype,
                resultinfo=r_result,
                checkinfo=check_str,
                runnertime=datetime.datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S'),
                actualdata=actualdata)
            objlist.save()
            #修改通过数和失败数
            Interface_result.objects.filter(id=objid).update(
                okcount=okcount, failcount=failcount, errorcount=errorcount)

    #统计数据
    runnerstate = 0
    if failcount == 0 and errorcount == 0:
        runnerstate = 1
    views.saveresult(pnumber=templatename[0]['pnumber'],
                     templateid=id,
                     runnerstate=runnerstate,
                     runnertime=r_time,
                     okcount=okcount,
                     failcount=failcount,
                     errorcount=errorcount)

    #发邮件
    emailtitle = '【' + templatename[0]['templatename'] + '】接口自动化测试报告'
    _content = """
    <html>
        <body>
            <table>
                <tr>
                    <td><b>测试描述:</b></td>
                    <td style="text-align: left">%s</td>
                </tr>
            </table>
            <div>------------------------------------------------------------------------------------</div>
            <table>
                <tr>
                    <td><b>测试目标:</b></td>
                    <td style="text-align: left">%s</td>
                </tr>
            </table>
            <div>------------------------------------------------------------------------------------</div>
            <table>
                <tr>
                    <td><b>执行时间:</b></td>
                    <td>%s</td>
                </tr>
                <tr>
                    <td><b>用例总数:</b></td>
                    <td>%d个</td>
                </tr>
                <tr>
                    <td><b>通过数:</b></td>
                    <td>%d个</td>
                </tr>
                <tr>
                    <td><b>失败数:</b></td>
                    <td>%d个</td>
                </tr>
                <tr>
                    <td><b>错误数:</b></td>
                    <td>%d个</td>
                </tr>
                <tr>
                    <td><b>报告详情地址:</b></td>
                    <td><a href="http://10.9.2.142/report/testreport?id=%d" target="_blank">点击查看详情</a></td>
                </tr>
            </table>
        </body>
    </html>
    """ % (jobcontent, jobtarget, r_time, casecount, okcount, failcount,
           errorcount, objid)

    e = Email(title=emailtitle,
              message=_content,
              receiver=mailaddress,
              server='smtp.7lk.com',
              sender='*****@*****.**',
              password='******',
              path='')
    logger.info('开始发送邮件!')
    e.send()
예제 #15
0
import unittest
import os
from utils.config_reader import ROOT_PATH
from utils.HTMLTestRunner_PY3 import HTMLTestRunner
from utils.mail import Email

report_name = os.path.join(ROOT_PATH, 'report\\report.html')
print('testrunner', ROOT_PATH)
fp = open(report_name, 'wb')
case_path = os.path.dirname(os.path.abspath('.')) + r'\case'
suite = unittest.TestLoader().discover(case_path)
if __name__ == "__main__":

    #runner = unittest.TextTestRunner()
    runner = HTMLTestRunner(stream=fp,
                            verbosity=2,
                            title='接口测试报告',
                            description='网站接口')
    runner.run(suite)
    email = Email(path=report_name)
    email.send()
예제 #16
0
        self.driver.quit()

    def test_search(self):
        datas = ExcelReader(self.excel).data
        for d in datas:
            with self.subTest(data=d):
                self.sub_setUp()
                self.driver.find_element(*self.locator_kw).send_keys(d['search'])
                self.driver.find_element(*self.locator_su).click()
                time.sleep(2)
                links = self.driver.find_elements(*self.locator_result)
                for link in links:
                    logger.info(link.text)
                self.sub_tearDown()


if __name__ == '__main__':
    report = REPORT_PATH + '\\report.html'
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f, verbosity=2, title='从0搭建测试框架 灰蓝', description='修改html报告')
        runner.run(TestBaiDu('test_search'))
    e = Email(title='百度搜素测试报告',
              message='这是今天的测试报告,请查收!',
              receiver='*****@*****.**',
              server='...',
              sender='...',
              password='******',
              path=report
              )
    e.send()
    def run_addMailRule_case(self, condition, excuteOperate,
                             deliverOrChargeFirst, deliverOrChargeSecond,
                             containKey, send_info):

        self.find_element(self.mailSettingPageMailRulePage_mailRuleBtn).click()
        with allure.step("输入收件规则的名字"):
            time.sleep(0.2)
            self.find_element(
                self.mailSettingPageMailRulePage_mailRuleNameInput).clear()
            self.find_element(
                self.mailSettingPageMailRulePage_mailRuleNameInput).send_keys(
                    "邮件规则测试")
        time.sleep(0.2)
        with allure.step("点击触发条件"):
            self.find_element(
                self.mailSettingPageMailRulePage_conditionBtn).click()
        time.sleep(0.2)
        with allure.step("选中{}".format(condition)):
            mailSettingPageMailRulePage_condition_loc = (
                By.XPATH,
                self.mailSettingPageMailRulePage_condition_allMails[1].replace(
                    "全部邮件", condition))
            self.scroll_element(mailSettingPageMailRulePage_condition_loc)
            time.sleep(0.3)
            self.find_element(
                mailSettingPageMailRulePage_condition_loc).click()
        if "邮件主题" in condition or "发件地址" in condition:
            with allure.step("输入包含的关键词"):
                self.find_element(
                    self.mailSettingPageMailRulePage_containKeyInput).clear()
                self.find_element(
                    self.mailSettingPageMailRulePage_containKeyInput
                ).send_keys(containKey)
        time.sleep(0.2)
        with allure.step("点击执行操作"):
            self.find_element(
                self.mailSettingPageMailRulePage_excuteOperateBtn).click()
        time.sleep(0.2)
        with allure.step("选中{}".format(excuteOperate)):
            mailSettingPageMailRulePage_excuteOperate_loc = (
                By.XPATH,
                self.mailSettingPageMailRulePage_excuteOperate_merger[1].
                replace("直接归并", excuteOperate))
            self.find_element(
                mailSettingPageMailRulePage_excuteOperate_loc).click()
        time.sleep(0.2)
        with allure.step("点击收取至或者分发给一级选择框"):
            self.find_element(
                self.mailSettingPageMailRulePage_firstChargeBtn).click()
        time.sleep(0.2)
        with allure.step("选中{}".format(deliverOrChargeFirst)):
            mailSettingPageMailRulePage_deliverOrChargeFirstBox_loc = (
                By.XPATH,
                self.mailSettingPageMailRulePage_firstCharge_customizeBox[1].
                replace("自定义箱", deliverOrChargeFirst))
            self.find_element(
                mailSettingPageMailRulePage_deliverOrChargeFirstBox_loc).click(
                )
        # with allure.step("选中二级箱子选择框"):
        #     self.find_element(self.mailSettingPageMailRulePage_secondChargeBtn).click()
        # time.sleep(0.2)
        # with allure.step("选中{}".format(deliverOrChargeSecond)):
        #     mailSettingPageMailRulePage_deliverOrChargeSecondBox_loc = (By.XPATH,self.mailSettingPageMailRulePage_secondCharge_boxList[1].replace(""))
        #     self.find_element(self.mailSettingPageMailRulePage_secondCharge_boxList).click()
        with allure.step("点击保存按钮"):
            self.find_element(
                self.mailSettingPageMailRulePage_saveMailRuleBtn).click()
        with allure.step("开始发送邮件"):
            emailTitle = random_name() + "收件规则测试-{}".format(
                condition) + time.strftime("%Y%m%d.%H.%M.%S")
            e = Email(title=emailTitle,
                      message=random_text(),
                      receiver="*****@*****.**",
                      server=send_info['server'],
                      sender=send_info['sender'],
                      password=send_info['password'])
            e.send()
        time.sleep(150)
        with allure.step("点击邮件首页"):
            self.find_element(self.emailHomePage_loc).click()
        with allure.step("遍历箱子,查看是否收到主题是:{}的邮件".format(emailTitle)):
            num = 0
            while True:
                if deliverOrChargeFirst == "客户箱":
                    with allure.step("点击客户箱tab"):
                        self.find_element(
                            self.recipientBoxPage_customerBoxBtn_loc).click()
                    time.sleep(0.5)
                    with allure.step("点击最近联系的第一个客户箱"):
                        self.find_element(
                            self.customerBoxPage_firstRecentBox_loc).click()
                elif deliverOrChargeFirst == "供应商箱":
                    with allure.step("点击供应商tab"):
                        self.find_element(
                            self.recipientBoxPage_supplierBoxBtn_loc).click()
                    time.sleep(0.5)
                    with allure.step("点击最近联系的第一个供应商箱子"):
                        self.find_element(
                            self.supplierBoxPage_firstRecentBox_loc).click()
                elif deliverOrChargeFirst == "内部联系人箱":
                    with allure.step("点击内部联系人tab"):
                        self.find_element(
                            self.recipientBoxPage_innerBoxBtn_loc).click()
                    time.sleep(0.5)
                    with allure.step("点击最近联系的第一个内部联系人箱子"):
                        self.find_element(
                            self.innerBoxPage_firstRecentBox_loc).click()
                else:
                    with allure.step("点击自定义测试箱,查看是否收到邮件"):
                        self.find_element(
                            self.customizeBoxPage_firstBox_loc).click()
                time.sleep(3)
                subjects = self.get_elementText(
                    self.recipientBoxPage_emailSubject_loc, index="all")
                # allMailSubjects = []
                # for subject in subjects:
                #     allMailSubjects.append(subject.split("】")[1])
                if emailTitle in subjects:
                    break
                else:
                    with allure.step("点击邮箱tab"):
                        self.find_element(
                            self.recipientBoxPage_emailBoxBtn_loc).click()
                    with allure.step("点击收件箱"):
                        self.find_element(self.receiptBox_loc).click()
                    time.sleep(2)
                    num = num + 1
                    time.sleep(20)
                if num == 15:
                    print(subjects)
                    raise Exception("收件箱没有主题是:{}的邮件,请排查".format(emailTitle))