Exemplo n.º 1
0
 def collection_stock_prices(self, stock_name, filepath=file_path):
     """
     收集股票信息
     :param stock_name:股票代码
     :param filepath:excel文件路径
     :return:
     """
     new_data = {}
     prices = {}
     t = time.strftime("%Y-%m-%d", time.localtime())
     prices['当前'] = self.dr.get_ele_content(stock_new_prices)
     prices['今开'] = self.dr.get_ele_content(stock_opentoday_prices)
     prices['最高'] = self.dr.get_ele_content(stock_highest_prices)
     prices['昨收'] = self.dr.get_ele_content(stock_closeyes_prices)
     prices['最低'] = self.dr.get_ele_content(stock_lowest_prices)
     prices['涨跌幅度'] = self.dr.get_ele_content(stock_increase)
     self.stock_police(stock_name, prices)
     new_data[t] = prices
     excel = operateExcel(filepath, stock_name)
     old_data = excel.get_excel_dict()
     if old_data:
         all_data = {**old_data, **new_data}
     else:
         all_data = new_data
     excel.input_excel(all_data)
     print('采集成功,在{0}中查看'.format(filepath))
     self.dr.get_page_screenshot(case_name=stock_name + '股票_详情')
     BeautifulReport.add_test_img3(stock_name + '股票_详情')
Exemplo n.º 2
0
def run_case(all_case, reportName="report"):
    '''第二步:执行所有的用例, 并把结果写入HTML测试报告'''
    now = time.strftime("%Y_%m_%d %H_%M_%S")
    report_path = os.path.join(cur_path, reportName)  # 用例文件夹
    #调用BeautifulReport报告模板的方法
    runner = BeautifulReport(all_case)
    runner.report(filename="report%s.html" % now,
                  description='爱学习自动化测试报告',
                  log_path=report_path)
Exemplo n.º 3
0
 def check_case(self, name='进入众测价值'):
     """检查是否成功"""
     url = self.dr.get_page_url()
     if url == zc_value_url:
         print('{0}用例成功!'.format(name))
         log.info('{0}用例成功!'.format(name))
         self.dr.get_page_screenshot(file_path=self.img_path, case_name=name + '_成功')
         BeautifulReport.add_test_img3(name + '_成功')
     else:
         print('{0}用例失败'.format(name))
         log.info('{0}用例失败!'.format(name))
         self.dr.get_page_screenshot(file_path=self.img_path, case_name=name + '_失败')
         BeautifulReport.add_test_img3(name + '_失败')
Exemplo n.º 4
0
 def moreProcess_report(self):
     """多进程执行用例并输出报告"""
     log.info('start moreProcess!')
     pros = []
     q = mp.Queue(maxsize=len(self.caselist))
     for i in self.suite_all:
         pro = Process(target=self.process_run_Beautifuhtml,
                       args=(i, q, True))
         pros.append(pro)
     for pro in pros:
         pro.start()
     for pro in pros:
         self.report_result.append(q.get())
         # time.sleep(1)
         # print(self.report_result)
         # pro.join()
         # try:
         #     self.report_result.append(q.get_nowait())
         #     print(self.report_result)
         #     pro.join()
         # except _queue.Empty as queue:
         #     log.error('异常,_queue.Empty:"{0}"'.format(queue))
         #     pro.terminate()
         #     raise
     dict = {}
     log.info('start data processing!')
     for i in range(len(self.report_result)):
         if i == 0:
             dict['testName'] = self.report_result[0]['testName']
             dict['beginTime'] = self.report_result[0]['beginTime']
             dict['testPass'] = self.report_result[i]['testPass']
             dict['testResult'] = self.report_result[i]['testResult']
             dict['testAll'] = self.report_result[i]['testAll']
             dict['testFail'] = self.report_result[i]['testFail']
             dict['testSkip'] = self.report_result[i]['testSkip']
             dict['testError'] = self.report_result[i]['testError']
         else:
             dict['testPass'] += self.report_result[i]['testPass']
             dict['testResult'] += self.report_result[i]['testResult']
             dict['testAll'] += self.report_result[i]['testAll']
             dict['testFail'] += self.report_result[i]['testFail']
             dict['testSkip'] += self.report_result[i]['testSkip']
             dict['testError'] += self.report_result[i]['testError']
         dict['totalTime'] = self.report_result[i]['totalTime']
     log.info('MoreProcess end.start Transfer data and generate reports...')
     result = BeautifulReport(self.suite_all)
     result.stop_output(log_path=self.reportFile1 + '\\', FIELDS=dict)
     log.info('End of the project.Please see the report!')
Exemplo n.º 5
0
 def open_url(self, url):
     t1 = time.time()
     try:
         self.driver.get(url)
         log.info('{0} Open url: {1}, spend {2} seconds'.format(
             success, url,
             time.time() - t1))
     except Exception as e:
         log.info('Open link {0}: {1}, spend {2} seconds'.format(
             fail, url,
             time.time() - t1))
         log.error(e)
         self.get_page_screenshot(file_path=screenshot_path,
                                  case_name=url + '_打开url失败')
         BeautifulReport.add_test_img3(url + '_打开url失败')
         raise
Exemplo n.º 6
0
 def check_filtertask_result1(self, name='筛选可参与任务'):
     """判断用例是否成功"""
     flag, ele = self.dr.judge_element(zc_cantask_result)  # 判断是否有可参与任务
     if flag:
         text = self.dr.get_ele_content(zc_cantask_result)
         print('用例成功,目前无任务,提示文案为:'.format(text))
         log.info('Success filter task case, result:"{0}"'.format(text))
         self.dr.get_page_screenshot(file_path=self.img_path,
                                     case_name=name + '_无结果时')
         BeautifulReport.add_test_img3(name + '_无结果时')
     else:
         print('用例成功,{0}完成!'.format(name))
         log.info('用例成功,{0}完成!'.format(name))
         self.dr.get_page_screenshot(file_path=self.img_path,
                                     case_name=name + '_有结果时')
         BeautifulReport.add_test_img3(name + '_有结果时')
Exemplo n.º 7
0
 def pool_run_Beautifuhtml(self, suite=None, q=None, process=False):
     """执行用例并输出漂亮报告方法"""
     try:
         name = '/report1' if platform.system(
         ) != 'Windows' else '\\report1'
         if not process:
             suite = self.suite_all
         result = BeautifulReport(suite, verbosity=2)
         results = result.report(filename=name,
                                 description='测试众测报告',
                                 log_path=self.reportFile1,
                                 process=process)
         if process:
             q.put(results)
     except Exception as e:
         log.error(e)
         raise
Exemplo n.º 8
0
 def click_userhome_myrecord(self):
     """点击我的战绩,并输出贡献率"""
     self.dr.click(zc_userhome_myrecord)
     flag, ele = self.dr.judge_element(zc_myrecord_devote)
     if flag:
         devote = self.dr.get_ele_content(zc_myrecord_devote)
         print('用例通过,贡献率为:{0}'.format(devote))
         log.info('Success case, devote:"{0}"'.format(devote))
         self.dr.get_page_screenshot(file_path=self.img_path,
                                     case_name='查看战绩_成功',
                                     source='other')
     else:
         print('用例失败')
         log.info('Fail case!')
         self.dr.get_page_screenshot(file_path=self.img_path,
                                     case_name='查看战绩_失败',
                                     source='other')
         BeautifulReport.add_test_img('test_查看战绩_失败')
         assert flag
Exemplo n.º 9
0
 def get_page_url(self, source='web'):
     """获取当前页面链接"""
     t1 = time.time()
     try:
         current_url = self.driver.current_url
         log.info(
             '{0} Get current page link:"{1}" , spend {2} seconds'.format(
                 success, current_url,
                 time.time() - t1))
     except Exception as e:
         log.error('Fail get current page link, spend "{1}" seconds'.format(
             fail,
             time.time() - t1))
         log.error(e)
         title = self.get_page_title()
         self.get_page_screenshot(case_name=title + '_获取页面链接失败',
                                  source=source)
         BeautifulReport.add_test_img3(title + '_获取页面链接失败')
         raise
     return current_url
Exemplo n.º 10
0
 def max_window(self, source='web'):
     """
     最大化窗口
     :return:
     """
     t1 = time.time()
     try:
         self.driver.maximize_window()
         log.info('{0} Maximize window, spend {1} seconds'.format(
             success,
             time.time() - t1))
     except Exception as e:
         log.info('{0} Maximize window, spend {1} seconds'.format(
             fail,
             time.time() - t1))
         log.error(e)
         url = self.get_page_url()
         self.get_page_screenshot(case_name=url + '_最大化窗口失败', source=source)
         BeautifulReport.add_test_img3(url + '_最大化窗口失败')
         raise
Exemplo n.º 11
0
 def process_run_Beautifuhtml(self, suite=None, q=None, process=False):
     """执行用例并输出漂亮报告方法"""
     # global results
     try:
         lock.acquire()
         name = '\\report1'
         if not process:
             suite = self.suite_all
         result = BeautifulReport(suite, verbosity=2)
         results = result.report(filename=name,
                                 description='测试deafult报告',
                                 log_path=self.reportFile1,
                                 process=process)
         if process:
             q.put(results)
             # q.send(results)
             # q.close()
     except Exception as e:
         log.error(e)
         raise
     finally:
         lock.release()
Exemplo n.º 12
0
 def pool_report(self):
     """使用进程池执行用例并输出报告"""
     log.info('start pool!')
     q = mp.Manager().Queue()
     pool = mp.Pool()
     for i in self.suite_all:
         pool.apply_async(self.pool_run_Beautifuhtml, args=(i, q, True))
     pool.close()
     pool.join()
     for i in range(q.qsize()):
         self.report_result.append(q.get())
     dict = {}
     log.info('start data processing!')
     for i in range(len(self.report_result)):
         if i == 0:
             dict['testName'] = self.report_result[0]['testName']
             dict['beginTime'] = self.report_result[0]['beginTime']
             dict['testPass'] = self.report_result[i]['testPass']
             dict['testResult'] = self.report_result[i]['testResult']
             dict['testAll'] = self.report_result[i]['testAll']
             dict['testFail'] = self.report_result[i]['testFail']
             dict['testSkip'] = self.report_result[i]['testSkip']
             dict['testError'] = self.report_result[i]['testError']
         else:
             dict['testPass'] += self.report_result[i]['testPass']
             dict['testResult'] += self.report_result[i]['testResult']
             dict['testAll'] += self.report_result[i]['testAll']
             dict['testFail'] += self.report_result[i]['testFail']
             dict['testSkip'] += self.report_result[i]['testSkip']
             dict['testError'] += self.report_result[i]['testError']
         dict['totalTime'] = self.report_result[i]['totalTime']
     log.info('MoreProcess end.start Transfer data and generate reports...')
     result = BeautifulReport(self.suite_all)
     slash = '/' if platform.system(
     ) != 'Windows' else '//'  # 判断系统,给出不同路径连接符
     result.stop_output(log_path=self.reportFile1 + slash, FIELDS=dict)
     log.info('End of the project.Please see the report!')
     print('用例结束,在{0}查看报告!'.format(self.reportFile1))
Exemplo n.º 13
0
 def click(self, css, secs=8, source='web'):
     """
     重写click方法
     :param css:
     :param secs:
     :return:
     """
     t1 = time.time()
     try:
         ele = self.find_element(css, secs)
         ele.click()
         log.info('{0} Click element:"{1}", spend {2} seconds'.format(
             success, css,
             time.time() - t1))
     except Exception as e:
         log.info(
             '{0} Unable to the element:"{1}", spend {2} seconds'.format(
                 fail, css,
                 time.time() - t1))
         log.error(e)
         self.get_page_screenshot(case_name=css + '_点击失败', source=source)
         BeautifulReport.add_test_img3(css + '_点击失败')
         raise
Exemplo n.º 14
0
 def chick_zc_honor(self, name='最新一期'):
     """
     检查是否成功获取到荣誉榜单
     param:name, 输入需要检查的榜单期数
     """
     try:
         honor_list = {}
         eles = self.dr.finds_element(zc_honor_tablename)
         for num in range(1, len(eles) + 1):
             text = self.dr.get_ele_content(eles[num - 1])
             honor_list[num] = text
         print('用例成功,"{0}荣誉榜单"为:\n{1}'.format(name, honor_list))
         log.info('Success case!')
         self.dr.get_page_screenshot(file_path=self.img_path,
                                     case_name=name + '荣誉榜单_成功')
         BeautifulReport.add_test_img3(name + '荣誉榜单_成功')
     except Exception as e:
         print('查看"{0}荣誉榜单"用例失败!'.format(name))
         log.error('Fail view newhonor case!')
         log.error(e)
         self.dr.get_page_screenshot(file_path=self.img_path,
                                     case_name=name + '荣誉榜单_失败')
         BeautifulReport.add_test_img3(name + '荣誉榜单_失败')
         raise
Exemplo n.º 15
0
 def wait_activity(self, activity, timeout=8, interval=1):
     """
     等待activity出现
     :param activity:需要等待的activity
     :param timeout: 超时时间
     :param interval: 轮询查找activity时间
     :return:
     """
     t1 = time.time()
     try:
         self.driver.wait_activity(activity, timeout, interval)
         log.info('{0} Find the activity:{1}, spend {2} seconds'.format(
             success, activity,
             time.time() - t1))
     except Exception as e:
         log.info('{0} Not find the activity:{1}, spend {2} seconds'.format(
             fail, activity,
             time.time() - t1))
         log.error(e)
         self.get_page_screenshot(file_path=screenshot_path,
                                  case_name=activity + '_等待activity',
                                  source='app')
         BeautifulReport.add_test_img3(activity + '_等待activity')
         raise
Exemplo n.º 16
0
import unittest,time
from common.BeautifulReport import BeautifulReport
from test_case import test_163_login
now = time.strftime("%Y-%m-%d %H-%M-%S", time.localtime(time.time()))
report_title='用例执行报告'+now+'.html'
report_path=r'G:\UI_Test\Demo_Test\report'

# 报告地址&名称
report_title = r'Example报告_' + now + ".html"  # 如果不能打开这个文件,可能是now的格式,不支持:和空格
if __name__ == '__main__':
    suite = unittest.TestSuite()
    loader=unittest.TestLoader()
    suite.addTests(loader.loadTestsFromModule(test_163_login))
    #运行用例filename=报告名称,description=所有用例总的名称,report_path=报告路径,如果不填写默认当前执行文件目录
    BeautifulReport(suite).report(filename=report_title, description='登录模块',log_path=report_path)
Exemplo n.º 17
0
# 加载指定目录下的所有case
test_dir = get_file_path() + "\\test_case"
# 配置运行用例、运行方式
discover = unittest.defaultTestLoader.discover(test_dir, pattern='login_demo*.py', top_level_dir=None)
run_type = "BeautifulReport"  # BeautifulReport 或者 HTMLTestRunner

if __name__ == "__main__":
    # 判断report文件夹是否存在,不存在的话创建文件夹
    project_dir = os.listdir(get_file_path())
    dir_name = 'report'
    if dir_name not in project_dir:
        create_path = get_file_path() + '\\report'
        os.makedirs(create_path)
    # 获取时间
    runner = unittest.TextTestRunner()
    now = time.strftime("%Y-%m-%d %H_%M_%S")

    # 运行生成测试报告
    if run_type == "HTMLTestRunner":
        filename = get_file_path() + "\\report\\" + now + " HTR.html"
        fp = open(filename, "wb")
        runner = HTMLTestRunner(stream=fp, title=u'集采UI自动化测试报告', description=u'用例执行情况:')
        runner.run(discover)
        fp.close()
    elif run_type == "BeautifulReport":
        log_path = get_file_path() + "\\report\\"
        runner = BeautifulReport(discover)
        runner.report(filename=now + "BR", description='用例执行情况', log_path=log_path)

    # 邮件发送测试报告
    # send_report()
Exemplo n.º 18
0
 def check_filtertask_result(self, source='can'):
     """判断用例是否成功"""
     flag, ele = self.dr.judge_element(zc_cantask_result)  # 判断是否有可参与任务
     if flag:
         text = self.dr.get_ele_content(zc_cantask_result)
         print('用例成功,目前无任务,提示文案为:'.format(text))
         log.info('Success filter task case, result:"{0}"'.format(text))
         if source == 'can':
             self.dr.get_page_screenshot(file_path=self.img_path,
                                         case_name='筛选可参与任务_无结果时',
                                         source='other')
             BeautifulReport.add_test_img3('筛选可参与任务_无结果时')
         elif source == 'pro':
             self.dr.get_page_screenshot(file_path=self.img_path,
                                         case_name='筛选进行中任务_无结果时',
                                         source='other')
             BeautifulReport.add_test_img3('筛选进行中任务_无结果时')
         elif source == 'end':
             self.dr.get_page_screenshot(file_path=self.img_path,
                                         case_name='筛选已结束任务_无结果时',
                                         source='other')
             BeautifulReport.add_test_img3('筛选已结束任务_无结果时')
     else:
         if source == 'can':
             print('用例成功,成功筛选出可参与任务!')
             log.info('Success filter canjoin task case,')
             self.dr.get_page_screenshot(file_path=self.img_path,
                                         case_name='筛选可参与任务_有结果时',
                                         source='other')
             BeautifulReport.add_test_img3('筛选可参与任务_有结果时')
         elif source == 'pro':
             print('用例成功,成功筛选出进行中任务!')
             log.info('Success filter processing task case,')
             self.dr.get_page_screenshot(file_path=self.img_path,
                                         case_name='筛选进行中任务_有结果时',
                                         source='other')
             BeautifulReport.add_test_img3('筛选进行中任务_有结果时')
         elif source == 'end':
             print('用例成功,成功筛选出已结束任务!')
             log.info('Success filter end task case,')
             self.dr.get_page_screenshot(file_path=self.img_path,
                                         case_name='筛选已结束任务_有结果时',
                                         source='other')
             BeautifulReport.add_test_img3('筛选已结束任务_有结果时')
         else:
             print('用例失败,判断来源不详,source:"{0}"'.format(source))
             log.info('Fali filter task case,unknown source:"{0}"'.format(
                 source))
             self.dr.get_page_screenshot(file_path=self.img_path,
                                         case_name='筛选任务_来源未知',
                                         source='other')
             BeautifulReport.add_test_img3('筛选任务_来源未知')
             assert flag
Exemplo n.º 19
0
        response_fag = ry.read_node_data('CASE_CONF', 'CASE_FIELD', 'RESPONSE', 'IS_WRITE')
        result_col = ry.read_node_data('CASE_CONF', 'CASE_FIELD', 'RESULT', 'INDEX')
        response_col = ry.read_node_data('CASE_CONF', 'CASE_FIELD', 'RESPONSE', 'INDEX')
        # 向Execl写入结果
        copy_data, table_data_w = operation_excel.copy_execl(index)
        for row, value in row_result_dic.items():
            if result_fag:
                operation_excel.write_data(table_data_w, row, result_col, value)
            else:
                break
        for row, value in row_response_dic.items():
            if response_fag:
                operation_excel.write_data(table_data_w, row, response_col, value)
            else:
                break
        operation_excel.save(copy_data)


if __name__ == '__main__':
    time_str = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    test_suite = unittest.defaultTestLoader.discover(path + r'\\', pattern='test*.py')
    result = BeautifulReport(test_suite)
    result.report(filename='report_' + time_str + '.html', description='测试报告', report_path=path + r'\..\Report')
    print(result.FIELDS['testAll'], result.FIELDS['testFail'], result.FIELDS['testAll'] - result.FIELDS['testFail'],
          result.FIELDS['beginTime'], type(result.FIELDS['beginTime']), result.FIELDS['end_time'])
    # 发送邮件
    send_email = SendEmail(description=u'测试报告', pass_num=result.FIELDS['testAll'] - result.FIELDS['testFail'],
                           fail_num=result.FIELDS['testAll'], start_time=result.FIELDS['beginTime'],
                           end_time=result.FIELDS['end_time'], continue_time=result.FIELDS['totalTime'])
    send_email.send_email()