コード例 #1
0
ファイル: testsuite.py プロジェクト: Root9512/UIFramework
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()
コード例 #2
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
コード例 #3
0
ファイル: run_api_case.py プロジェクト: babyxiaoma/Auto_frame
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()
コード例 #4
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()
コード例 #5
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(['*****@*****.**'])
コード例 #6
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
コード例 #7
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()
コード例 #8
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
コード例 #9
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_dir = REPORT_PATH + '\\%s.html' % now
    re_open = open(report_dir, 'wb')
    runner = HTMLTestRunner(stream=re_open,
                            title=reporttitle,
                            description=description)
    runner.run(test_suit)
    re_open.close()
    e = Email(title='自动化测试报告',
              message='',
              receiver='*****@*****.**',
              server='smtp.163.com',
              sender='*****@*****.**',
              password='******',
              path=report_dir)
    e.mail_send()
コード例 #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
コード例 #11
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
コード例 #12
0
                    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'
    print(report)
    print("开始执行测试并生成报告")
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='从0搭建测试框架 灰蓝',
                                description='修改html报告')
        runner.run(TestBaidu('test_search'))
        print("输出report.html成功")

    print("发送邮件")
    e = Email(title='百度搜索测试报告',
              message='这是今天的测试报告',
              receiver='...',
              server='...',
              sender='...',
              password='******',
              path=report)
    e.send()
コード例 #13
0
        self.driver.find_element(*self.locator_su).click()
        self.driver.implicitly_wait(5)
        links = self.driver.find_elements(*self.locator_result)
        for link in links:
            #print(link.text)
            logger.info(link.text)
'''
if __name__ == '__main__':  #Alt + Shift +F10 以文件模式执行会出报告
    #unittest.main(verbosity=2)
    # 报告格式
    now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
    report = REPORT_PATH + r'\\' + now + 'report.html'
    f = open(report, 'wb')
    runner = HTMLTestRunner(f,
                            verbosity=2,
                            title=u'百度测试报告',
                            description=u'用例执行情况')
    runner.run(TestBaiDu('test_search'))
    #第一种邮件发送方法
    """
    e = Email(title='百度测试报告',
              message='这是今天的测试报告,请查收。',
              server='smtp.qq.com',
              sender='************@qq.com',
              password='******',
              receiver='********@qq.com',
              path=report)"""
    e = Email(file_path=report)
    #e.send()

    #Email().sentreport()#这是第二种发送邮件方法
コード例 #14
0
ファイル: test_baidu_5.py プロジェクト: moolighty/test
        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()
コード例 #15
0
    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))
コード例 #16
0
from utils import HTMLTestRunner
import time
from utils.mail import Email
from utils.config import REPORT_PATH


def create_test_suite():
    test_list_path = "../testcase"
    test_unit = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(test_list_path,
                                                   pattern="test_*.py")
    for test_suite in discover:
        for test_case in test_suite:
            test_unit.addTest(test_case)
            print(test_case)

    return test_unit


all_test = create_test_suite()
now_time = time.strftime("%Y%m%d%H%M%S", time.localtime())

report = REPORT_PATH + '\\' + now_time + 'report.html'
with open(report, "wb") as outfile:
    runner = HTMLTestRunner.HTMLTestRunner(stream=outfile,
                                           title=u"管理端测试报告",
                                           description=u"用例执行情况:",
                                           verbosity=2)
    runner.run(all_test)
e = Email(path=report, message="详情请下载后打开查看测试报告结果")
e.send()
コード例 #17
0
ファイル: client.py プロジェクト: ssiyad/telegram-mail-bot
 def get_mail_by_index(self, index):
     resp_status, mail_lines, mail_octets = self.server.retr(index)
     return Email(mail_lines)
コード例 #18
0
                links = self.page.result_links
                for link in links:
                    logger.info(link.text)
                self.sub_tearDown()


if __name__ == '__main__':
    REPORT_NAME = '{}-report.html'.format(time.strftime('%Y-%m-%d-%H-%M-%S'))
    report = os.path.join(REPORT_PATH, REPORT_NAME)

    with open(report, 'wb') as rp:
        runner = HTMLTestRunner(rp,
                                verbosity=2,
                                title='测试框架练习',
                                description='生成html报告')
        runner.run(TestBaiDu('test_search'))

    _email = Config().get('email')

    message1 = '这是今天的测试报告'
    message2 = open(report, 'r', encoding='utf-8').read()

    e = Email(title=_email.get('title'),
              receiver=_email.get('receiver'),
              server=_email.get('server'),
              sender=_email.get('sender'),
              password=_email.get('password'),
              path=report,
              message='{0}\n{1}'.format(message1, message2))
    e.send()
コード例 #19
0
ファイル: test_bing.py プロジェクト: Lingzy/kingdeewebtest
                self.sub_setUp()
                # self.driver.find_element(*self.locator_input).send_keys(d['search'])
                # self.driver.find_element(*self.locator_btn).click()
                self.page.search(d['search'])
                time.sleep(2)
                self.page = BingResultPage(self.page)
                # links = self.driver.find_elements(*self.locator_result)
                links = self.page.result_links
                for link in links:
                    logger.info(link.text)
                self.sub_tearDown()


if __name__ == '__main__':
    report = REPORT_PATH + '\\' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.html'
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='bing_http_test_report',
                                description='test report')
        runner.run(TestBing('test_bing'))
    # unittest.main(verbosity=2)
    e = Email(title='bing test report',
              message='This is the test report ,please check it',
              receiver='*****@*****.**',
              server='smtp.126.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()
コード例 #20
0
            logger.info('success')


if __name__ == '__main__':
    # unittest.main()
    report = REPORT_PATH + '\\report.html'
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='We center问答平台',
                                description='登录功能')
        runner.run(TestPost('test_signin'))  # 需要0,False参数
    e = Email(title='We Center登录测试报告',
              message='这是今天的测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.qq.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()

# import os, time, unittest, ddt, logging
# from utils.config import Config, DRIVER_PATH, DATA_PATH, REPORT_PATH
# from utils.log import logger
# from utils.file_reader import ExcelReader
# from utils.HTMLTestRunner import HTMLTestRunner
# from utils.mail import Email
# from wecenter_test.page.page_login import Login
#
#
# @ddt.ddt
コード例 #21
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()
コード例 #22
0

class Suite(unittest.TestSuite):
    def __init__(self, suite):
        self.suite = suite

    def runSuite(self):
        html_file = REPORT_PATH + '\\' + str(times) + '.html'
        fp = open(html_file, 'wb')
        runner = HTMLTestRunner(stream=fp,
                                verbosity=2,
                                title=u'测试报告',
                                description=u'用例执行情况:')
        runner.run(self.suite)
        fp.close()


if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTests(unittest.TestLoader().loadTestsFromName(
        'test.interface.test_case.Test_case'))
    Suite(suite).runSuite()
    report = REPORT_PATH + '\\' + str(times) + '.html'
    e = Email(title='测试报告',
              message='这是本次的测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.163.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()
コード例 #23
0
              
                self.page = BaiDuResultPage(self.page)
    '''
    '''
    def search_1(self):
        self.driver.find_element(*self.locator_kw).send_keys('selenium+python')
        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)
            # driver.quit()
    '''


if __name__ == '__main__':
    report = config1.REPORT_PATH + '\\report.html'
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='从0搭建测试框架 灰蓝',
                                description='修改html报告')
        runner.run(TestBaiDu('test_register'))
    e = Email(title='百度搜索测试报告',
              message='这是今天的测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.163.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()
コード例 #24
0
ファイル: case_test.py プロジェクト: yanxianhui/Test_web-zi
    testsuite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestBaiDu))
    #now=time.strftime("%Y-%m-%d-%H:%M:%S",time.localtime(time.time()))
    report = REPORT_PATH + '\\report.html'
    with open(report, 'wb+') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='第一个html报告',
                                description='修改html报告')
        runner.run(testsuite)
    #fp = open(report, 'wb+')
    #runner = HTMLTestRunner(stream=fp, verbosity=2, title='第一个html报告', description='修改html报告')

    #fp.close()
    e = Email(title='ERP测试报告',
              message='这是今天的测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.126.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()
    """初始化Email

            :param title: 邮件标题,必填。
            :param message: 邮件正文,非必填。
            :param path: 附件路径,可传入list(多附件)或str(单个附件),非必填。
            :param server: smtp服务器,必填。
            :param sender: 发件人,必填。
            :param password: 发件人密码,必填。
            :param receiver: 收件人,多收件人用“;”隔开,必填。
            """
コード例 #25
0
        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'
    print(report)
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='从0搭建测试框架 泓霏',
                                description='修改html报告')
        runner.run(TestBaiDu('test_search'))
    e = Email(title='hkjf测试报告',
              message='这是今天的测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.qq.com:465',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()
コード例 #26
0
import unittest, os
from config import config
from utils.mail import Email
from utils.HTMLTestRunner_PY3 import HTMLTestRunner

case_path = os.path.join(config.BASE_PATH, 'test', 'API', 'case')  #测试用例位置

report = config.REPORT_PATH + '\\report.html'  #测试报告位置

suit = unittest.defaultTestLoader.discover(case_path,
                                           pattern="Test*.py")  #实例化测试套件

if __name__ == '__main__':
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(stream=f,
                                verbosity=2,
                                title='安智智慧校园 API 自动化测试报告',
                                description='3月22日2.0.1版本上线前最后一次自动化测试')
        runner.run(suit)
    e = Email(title='安智智慧校园 API 自动化测试报告',
              message='这次的测试报告,请查收!',
              receiver='*****@*****.**',
              server='smtp.163.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e.send()
コード例 #27
0
        runner.run(tests)
        print("test end")





if __name__ == '__main__':
    # unittest.main()
    for i in range(1):
        try:
            now_time = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')
            report = REPORT_PATH + '\\report' + ' ' + now_time + 'num' + str(i) + '.html'
            if run_case_package == 'basic_operate':
               test = TestRunner(run_case_name, case_path=CASE_PATH_BASIC_OPERATE, title="测试用例:" + run_case_name)
            else:
                test = TestRunner(run_case_name, case_path=CASE_PATH_BEFORE_UPGRADE, title="测试用例:" + run_case_name)
            test.run()
        except Exception as b:
            print("test run error:%s" % str(b))
    e = Email(title='cloud自动化测试报告',
              message='Hi,please open using chrome',
              receiver=email_name,
              sender='*****@*****.**',
              password='******',
              # sender='*****@*****.**',
              # password='******',
              server='smtp.qq.com',
              path=report
              )
    e.send()
コード例 #28
0
if __name__ == "__main__":
#     verbosity是一个选项,表示测试结果的信息复杂度,有0、1、2 三个值
# 0 (静默模式): 你只能获得总的测试用例数和总的结果 比如 总共10个 失败2 成功8
# 1 (默认模式): 非常类似静默模式 只是在每个成功的用例前面有个“.” 每个失败的用例前面有个 “F”
# 2 (详细模式):测试结果会显示每个测试用例的所有相关的信息
    #unittest.main(verbosity=2)
    report = os.path.join(REPORT_PATH, 'report.html')
    # with open(report, 'wb') as f:
    #     runner = HTMLTestRunner(f, verbosity=2, title='TestFrame测试框架', description='修改html测试报告')
    #     runner.run(TestBaiDu('test_search'))

    # 发送邮件
    e = Email(server='smtp.qq.com',
              sender='*****@*****.**',
              password='******',
              receiver='*****@*****.**',
              title="frame_work测试报告",
              message="2020-06-13的测试报告",
              path=report
            )
    e.send()


# 通过By和直接调用无差别
# driver.find_element_by_id('kw').send_keys("selenium")
# driver.find_element_by_id('su').click()
# results = driver.find_elements_by_xpath('//*[@id="content_left"]/div/h3/a')


コード例 #29
0
        for d in datas:
            with self.subTest(data=d):
                self.sub_setup()
                driver = self.driver
                driver.find_element(*self.locator_kw).send_keys(d['search'])
                driver.find_element(*self.locator_su).click()
                time.sleep(2)
                links = driver.find_element(*self.locator_result).text
                logger.info(links)
                self.sub_tearDown()


if __name__ == '__main__':
    report = REPORT_PATH + '\\report.html'
    print(report)
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='轻量级测试框架-百度测试',
                                description='百度用例')
        #必须用unittest.main   否则无法生成报告
        runner.run(TestBaiDu('test_search_0'))
        e = Email(title='百度搜索测试报告',
                  message='这是今天的测试报告,请查收!',
                  receiver='*****@*****.**',
                  server='smtp.qq.com',
                  sender='*****@*****.**',
                  password='******',
                  path=report)
        e.send()
        unittest.main(runner)
コード例 #30
0
ファイル: test.py プロジェクト: lhuiace/Test_framework
        pass

    def tearDown(self):
        pass

    def test1(self):
        url = Config().get('URL')
        logger.info(url)
        logbug.info(111)


if __name__ == '__main__':
    report = REPORT_PATH + '\\report.html'
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f,
                                verbosity=2,
                                title='壁虎自动化测试报告',
                                description='报告')
        runner.run(TestBao('test1'))
    f = open(report, 'rb')
    mail_body = f.read()
    e = Email(title='自动化测试报告',
              message=mail_body,
              receiver='*****@*****.**',
              server='smtp.exmail.qq.com',
              sender='*****@*****.**',
              password='******',
              path=report)
    e._attach_file(LOG_PATH + '\\' + 'bug.log')
    e.send()
コード例 #31
0
ファイル: runApp.py プロジェクト: 3058035655/zstestjf122201
print(appreport_path)


def creat_suite():
    uit = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(testcase_path,
                                                   pattern="test_*.py")
    for test_suite in discover:
        # print(test_suite)
        for test_case in test_suite:
            uit.addTest(test_case)
            return uit


suite = creat_suite()
fp = open(appreport_path, "wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                       title="测试结果",
                                       description="appium测试结果")
runner.run(suite)
fp.close()
e = Email(
    title='appium测试报告',
    message='这是今天的android测试报告,请查收!',
    receiver='*****@*****.**',
    # server='smtp.qq.com:465',
    server='smtp.mxhichina.com:465',
    sender='*****@*****.**',
    password='******',
    path=appreport_path)
e.send()
コード例 #32
0

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([],self.verificationErrors)





if __name__ == "__main__":
    suite = unittest.TestSuite()
    suite.addTest(TestLeisu('test1'))
    suite.addTest(TestLeisu('test2'))


    reprot = REPORT_PATH + '\\report.html'
    with open(reprot,'wb') as f:
        runner = HTMLTestRunner(f,verbosity=2,title='镭速2.0版本自动化测试',description='自动化测试报告')
        runner.run(suite)
    e = Email(title='Raysync 2.0 测试报告',
              message='这是今天的测试报告,请查收',
              receiver='*****@*****.**',
              sender='*****@*****.**',
              password='******',
              server='smtp.exmail.qq.com',
              path =reprot,
              )
    e.send()

コード例 #33
0
ファイル: test_baidu.py プロジェクト: Jacessw/Test_frame_rz
    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()
コード例 #34
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()