Exemplo n.º 1
0
 def write_cell_time(self, sheet_name, row_no, column_no):
     """
     向excel某一单元格写入时间
     :param sheet_name:
     :param row_no:
     :param column_no:
     :return:
     """
     try:
         sh = self.wb[sheet_name]
         now_time = datetime.now()
         now_time.strftime('%Y:%m:%d %H:%M:%S')
         sh.cell(row_no, column_no, now_time)
         self.wb.save(self.file_name)
         logger.info('%s写入时间成功,写入时间为:%s' % (self.file_name, now_time))
     except PermissionError:
         msg = '请先关闭用例文件,再运行测试用例'
         logger.warning(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     except Exception as e:
         msg = '写入失败,请检查工作表名以及行,列号, 异常原因:%s' % str(traceback.format_exc())
         logger.error(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     finally:
         self.wb.close()
Exemplo n.º 2
0
    def save_scree_shot(self, file=None, case_name=None):
        """
        屏幕截图
        :return:
        """
        picture_name = SCREENSHOTS_PATH
        if not os.path.exists(picture_name):
            os.makedirs(picture_name)
            picture_name = picture_name + '\\' + DirAndTime.get_current_time(
            ) + '.png'
        else:
            picture_name = picture_name + '\\' + DirAndTime.get_current_time(
            ) + '.png'
        try:
            self.driver.get_screenshot_as_file(picture_name)
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, picture_name,
                                          0)
            logger.info('开始自定义截图: %s' % picture_name)

        except Exception as e:
            msg = '保存截图失败: %s' % str(traceback.format_exc())
            logger.warning(msg, e)
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
        else:
            return picture_name
Exemplo n.º 3
0
 def clear(self, by, locator):
     # 清空输入框
     msg = '清空输入框'
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     ObjectMap(self.driver, self.data).get_element(by, locator).clear()
Exemplo n.º 4
0
 def get_url(self, url):
     # 打开网址
     msg = '进入URL: %s' % url
     logger.info(msg)
     print(msg)
     self.driver.get(url)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
Exemplo n.º 5
0
 def refresh(self):
     # 刷新浏览器
     msg = '刷新浏览器'
     logger.info(msg)
     print(msg)
     self.driver.refresh()
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
Exemplo n.º 6
0
 def forward(self):
     # 前进浏览器上一个页面
     msg = '前进到: %s' % self.driver.current_url
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     self.driver.forward()
Exemplo n.º 7
0
 def clear_cell_value(self, sheet_name, row_no):
     """
     清空EXCEL单元格数据
     :param sheet_name:
     :param row_no:
     :return:
     """
     try:
         end_time = self.get_cell_value(sheet_name, row_no,
                                        TEST_STEP_END_TIME)
         result = self.get_cell_value(sheet_name, row_no, TEST_STEP_RESULT)
         err_info = self.get_cell_value(sheet_name, row_no, TEST_STEP_ERROR)
         err_pic = self.get_cell_value(sheet_name, row_no,
                                       TEST_STEP_PICTURE)
         if end_time is not None or end_time != '' and result is not None or result != '' and \
                 err_info is not None or err_info != '' and err_pic is not None or err_pic != '':
             self.write_cell_value(sheet_name, row_no, TEST_STEP_END_TIME,
                                   '')
             self.write_cell_value(sheet_name, row_no, TEST_STEP_RESULT, '')
             self.write_cell_value(sheet_name, row_no, TEST_STEP_ERROR, '')
             self.write_cell_value(sheet_name, row_no, TEST_STEP_PICTURE,
                                   '')
         self.wb.save(self.file_name)
     except PermissionError:
         msg = '请先关闭用例文件,再运行测试用例'
         logger.warning(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     except Exception as e:
         msg = '数据清空失败, 原因:%s' % str(traceback.format_exc())
         logger.error(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     finally:
         self.wb.close()
Exemplo n.º 8
0
    def get_row_value(self, sheet_name, row_no):
        """
        获取excel某一行的数据
        :param sheet_name:
        :param row_no:
        :return:
        """
        print('get_row_value')
        try:
            # sheet_name
            sheet_names = self.wb[sheet_name]
            # 创建集合,将指定行内的数据添加进集合
            row_value_list = []
            # 循环所有列
            for i in range(1, sheet_names.max_column + 1):
                # 通过行号与列号获取指定单元格信息,并添加进集合
                value = sheet_names.cell(row_no, i).value
                row_value_list.append(value)
            return row_value_list
        except Exception as e:
            msg = '读取失败,请检查工作表名以及行,列号, 异常原因:%s' % str(traceback.format_exc())
            logger.error(msg, e)
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)

        finally:
            self.wb.close()
            print('结束getRowValue')
Exemplo n.º 9
0
 def click(self, by, locator):
     """
     元素点击
     :return:
     """
     msg = '点击元素:%s' % locator
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     ObjectMap(self.driver, self.data).get_element(by, locator).click()
Exemplo n.º 10
0
 def switch_to_window(self, handle):
     """
     切换浏览器窗口
     :return:
     """
     msg = '当前窗口句柄', self.driver.current_window_handle
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     windows = self.driver.window_handles
     self.driver.switch_to.window(windows[int(handle)])
Exemplo n.º 11
0
 def sleep(self, sleep_seconds):
     """
     等待时间
     :param sleep_seconds: 单位秒
     :return:
     """
     msg = '休眠: %s秒' % sleep_seconds
     logger.info(msg)
     print(msg)
     time.sleep(int(sleep_seconds))
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
Exemplo n.º 12
0
 def assert_string_in_page_source(self, ass_string):
     """
     断言字符串是否包含在源码中
     :param ass_string:
     :return:
     """
     msg = '断言: "%s"是否存在页面中' % ass_string
     logger.info(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     assert ass_string in self.driver.page_source, "'%s'在页面中不存在" % ass_string
     print('"%s"存在页面中' % ass_string)
Exemplo n.º 13
0
 def assert_title(self, title_str):
     """
     断言页面标题
     :param title_str:
     :return:
     """
     msg = '断言: "%s"标题是否存在' % title_str
     logger.info(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     assert title_str in self.driver.title, '%s标题不存在' % title_str
     print('"%s"标题存在' % title_str)
Exemplo n.º 14
0
 def upload_file(self, by, locator, value):
     """
     上传单个文件input标签  type="file"
     :param by:
     :param locator:
     :param value:
     :return:
     """
     ObjectMap(self.driver, self.data).get_element(by,
                                                   locator).send_keys(value)
     msg = '上传文件: %s' % value
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
Exemplo n.º 15
0
 def back(self):
     # 退回浏览器上一个页面
     if self.driver.current_url == 'data:,':
         msg = '返回到: %s' % self.driver.current_url
         logger.info(msg)
         print(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
         self.driver.back()
     else:
         msg = '已经是第一个页面,无法在后退了'
         logger.info(msg)
         print(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
         return
Exemplo n.º 16
0
 def input_value(self, by, locator, value):
     """
     输入框输入值
     :param by:
     :param locator:
     :param value:
     :return:
     """
     msg = '输入框输入: %s' % value
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     ObjectMap(self.driver, self.data).get_element(by,
                                                   locator).send_keys(value)
Exemplo n.º 17
0
 def get_title(self):
     """
     获取页面标题
     :return:
     """
     try:
         msg = '获取页面标题:%s' % self.driver.title
         logger.info(msg)
         print(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
         return self.driver.title
     except Exception as e:
         msg = '获取页面标题失败: %s,原因:%s' % e, str(traceback.format_exc())
         logger.error(msg)
         print(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 1)
Exemplo n.º 18
0
 def clear_and_input(self, by, locator, value):
     """
     清除输入框再输入值
     :return:
     """
     msg = '清空输入框'
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     ObjectMap(self.driver, self.data).get_element(by, locator).clear()
     msg = '输入框输入: %s' % value
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     ObjectMap(self.driver, self.data).get_element(by,
                                                   locator).send_keys(value)
Exemplo n.º 19
0
    def __init__(self, file_name, data):
        self.file_name = file_name
        self.data = data
        self.task_obj = TestTask.objects.filter(
            task_id=self.data.get('task_id')).first()

        # 读取excel文件
        try:
            self.wb = load_workbook(self.file_name)
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, '开始读取用例文件', 3)
        except BaseException as e:
            msg = '无法读取或已损坏, 异常原因:%s' % str(traceback.format_exc())
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
            logger.error(
                '文件:%s, 无法读取或已损坏, 异常原因:%s' %
                (self.file_name, str(traceback.format_exc())), e)
Exemplo n.º 20
0
 def upload_files(self, by, locator, value):
     """
     上传多个文件,value为文件夹路径,input标签
     :param by:
     :param locator:
     :param value:
     :return:
     """
     for root, dirs, files in os.walk(value):
         for i in files:
             ObjectMap(self.driver, self.data).get_element(
                 by, locator).send_keys(value + '\\' + i)
             msg = '上传文件: %s' % i
             logger.info(msg)
             print(msg)
             CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
Exemplo n.º 21
0
    def get_merge_column_value(self, sheet_name, column_no):
        """
        读取合并单元格的数据
        :param sheet_name: 工作表
        :param column_no: 列号
        :return:
        """
        try:
            # 获取数据
            data = xlrd.open_workbook(self.file_name)
            # 获取sheet
            sheet_name = data.sheet_by_name(sheet_name)
            # 获取总行数
            n_rows = sheet_name.nrows  # 包括标题
            # 获取总列数
            n_cols = sheet_name.ncols
            # 计算出合并的单元格有哪些
            colspan = {}
            # 如果sheet是合并的单元格 则获取合并单元格的值,并将第一行的数据赋值给合并单元格中的空值
            if sheet_name.merged_cells:
                for item in sheet_name.merged_cells:
                    for row in range(item[0], item[1]):
                        for col in range(item[2], item[3]):
                            # 合并单元格的首格是有值的,所以在这里进行了去重
                            if (row, col) != (item[0], item[2]):
                                colspan.update({
                                    (row, col): (item[0], item[2])
                                })

                col = []
                for i in range(1, n_rows):
                    if colspan.get((i, column_no - 1)):
                        value = sheet_name.cell_value(*colspan.get((i,
                                                                    column_no -
                                                                    1)))
                        col.append(value)
                    else:
                        col.append(sheet_name.cell_value(i, column_no - 1))
                return col
        except Exception as e:
            msg = '合并单元格读取错误, 异常原因:%s' % str(traceback.format_exc())
            logger.error(msg, e)
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
        finally:
            self.wb.close()
Exemplo n.º 22
0
 def get_elements(self, by, locator):
     """
     查找元素组
     :param by:
     :param locator:
     :return: 元素组对象
     """
     try:
         if by.lower() in self.byDic:
             # element_time 元素定位超时时间
             elements = WebDriverWait(self.driver, ELEMENT_TIME).until(
                 EC.presence_of_all_elements_located((by, locator)))
             logger.info('通过: %s定位元素组: %s' % (by, locator))
             return elements
     except Exception as e:
         msg = '元素组定位失败,失败原因:%s' % str(traceback.format_exc())
         logger.info(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 1)
Exemplo n.º 23
0
 def get_cell_object(self, sheet_name, row_no, column_no):
     """
     获取excel某一单元格的数据
     :param sheet_name:
     :param row_no:
     :param column_no:
     :return:
     """
     try:
         sheet_names = self.wb[sheet_name]
         cell_value = sheet_names.cell(row_no, column_no)
         return cell_value
     except Exception as e:
         msg = '读取失败,请检查工作表名以及行,列号, 异常原因:%s' % str(traceback.format_exc())
         logger.error(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     finally:
         self.wb.close()
Exemplo n.º 24
0
 def get_column_value(self, sheet_name, column_no):
     """
     获取excel某一列的数据
     :param sheet_name:
     :param column_no:
     :return:
     """
     try:
         sheet_names = self.wb[sheet_name]
         column_value_list = []
         for i in range(2, sheet_names.max_row + 1):
             value = sheet_names.cell(i, column_no).value
             column_value_list.append(value)
         return column_value_list
     except Exception as e:
         msg = '读取失败,请检查工作表名以及行,列号, 异常原因:%s' % str(traceback.format_exc())
         logger.error(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     finally:
         self.wb.close()
Exemplo n.º 25
0
 def write_cell_values(self,
                       sheet_name,
                       row_no,
                       err_info=None,
                       err_pic=None):
     """
     写入 错误信息 错误图片
     :param sheet_name:
     :param row_no:
     :param err_info:
     :param err_pic:
     :return:
     """
     try:
         self.write_cell_time(sheet_name, row_no, TEST_STEP_END_TIME)
         if err_info:
             self.write_cell_value(sheet_name, row_no, TEST_STEP_ERROR,
                                   err_info)
         elif err_pic:
             self.write_cell_value(sheet_name, row_no, TEST_STEP_PICTURE,
                                   err_pic)
         else:
             self.write_cell_value(sheet_name, row_no, TEST_STEP_ERROR, '')
             self.write_cell_value(sheet_name, row_no, TEST_STEP_PICTURE,
                                   '')
         self.wb.save(self.file_name)
         logger.info('用例测试结果,错误信息,错误图片写入成功')
     except PermissionError:
         msg = '请先关闭用例文件,再运行测试用例'
         logger.warning(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     except Exception as e:
         self.wb.close()
         msg = '用例测试结果,错误信息,错误图片写入失败, 异常原因:%s' % str(traceback.format_exc())
         logger.error(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     finally:
         self.wb.close()
Exemplo n.º 26
0
    def open_browser(self, browser, version):
        """
        获取浏览器类型
        :param browser: 火狐、谷歌
        :param version: 仅谷歌浏览器需要版本
        """
        browser_version = {
            '70': '70.0.3538.97',
            '71': '71.0.3578.137',
            '72': '72.0.3626.6',
            '73': '73.0.3683.68',
            '74': '74.0.3729.6',
            '75': '75.0.3770.1',
            '76': '76.0.3809.126',
            '77': '77.0.3865.40',
            '78': '78.0.3904.11',
            '79': '79.0.3945.16',
            '85': '85.0.4183.87',
            '86': '86.0.4240.22',
            '87': '87.0.4280.88',
        }
        # TODO 设置浏览器版本
        version = browser_version.get(version,
                                      browser_version.get(BROWSER_VERSION))
        msg = "选择的浏览器为: %s浏览器" % browser
        CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)

        if browser == 'Google Chrome':
            print("选择的浏览器为: %s浏览器" % browser, )
            path = DRIVERS_PATH + 'chrome\\' + version + '\\chromedriver.exe'
            if version is not None:
                path = path
                logger.info(path, '驱动目录')
            else:
                logger.warning('浏览器版本不符合,请检查浏览器版本')
                return
            option = Options()
            option.add_experimental_option('w3c', False)
            option.add_argument('--start-maximized')
            self.driver = webdriver.Chrome(executable_path=path,
                                           options=option)
            msg = '启动谷歌浏览器'
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
            logger.info(msg)
            print(msg)
        elif browser == 'FireFox':
            path = DRIVERS_PATH + 'firefox\\' + 'geckodriver.exe'
            self.driver = webdriver.Firefox(executable_path=path)
            self.driver.maximize_window()
            msg = '启动火狐浏览器'
            CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
            logger.info(msg)
            print(msg)
        else:
            # 驱动创建完成后,等待创建实例对象
            WaitUnit(self.driver)
Exemplo n.º 27
0
 def clear_case_column_value(self, sheet_name):
     """
     清除执行时间,错误结果,错误信息,错误截图信息
     :param sheet_name:
     :return:
     """
     try:
         msg = '清除"%s"工作表测试结果中,请稍等....' % sheet_name
         logger.info(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
         # 清除用例的测试结果
         for l in range(5):
             case_result = self.get_column_value(sheet_name,
                                                 TEST_CASE_RESULT + l)
             none_case_result = list(
                 filter(
                     None,
                     self.get_column_value(sheet_name,
                                           TEST_CASE_RESULT + l)))
             if len(none_case_result) == 1:
                 continue
             else:
                 for i, v in enumerate(case_result):
                     if '执行结果1' == v or '执行结果2' == v or '执行结果3' == v or '执行结果4' == v or '执行结果5' == v:
                         continue
                     elif type(
                             self.get_cell_object(
                                 sheet_name, i + 2, TEST_CASE_RESULT +
                                 l)).__name__ == 'MergedCell':
                         continue
                     elif v != '' or v is not None:
                         self.wb[sheet_name].cell(i + 2,
                                                  TEST_CASE_RESULT + l, '')
         # 清除执行时间
         case_time = self.get_column_value(sheet_name, TEST_CASE_END_TIME)
         for s, d in enumerate(case_time):
             if d == '执行结束时间':
                 continue
             elif type(
                     self.get_cell_object(
                         sheet_name, s + 2,
                         TEST_CASE_END_TIME)).__name__ == 'MergedCell':
                 continue
             elif d != '' or d is not None:
                 self.wb[sheet_name].cell(s + 2, TEST_CASE_END_TIME, '')
         self.wb.save(self.file_name)
     except PermissionError:
         msg = '请先关闭用例文件,再运行测试用例'
         logger.warning(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     except Exception as e:
         msg = '数据清空失败, 异常原因:%s' % str(traceback.format_exc())
         logger.error(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     finally:
         self.wb.close()
Exemplo n.º 28
0
 def write_cell_value(self, sheet_name, row_no, column_no, value):
     """
     向excel某一单元格写入数据
     :param sheet_name:
     :param row_no:
     :param column_no:
     :param value:
     :return:
     """
     try:
         sheet_names = self.wb[sheet_name]
         sheet_names.cell(row_no, column_no, value)
         self.wb.save(self.file_name)
     except PermissionError:
         msg = '请先关闭用例文件,再运行测试用例'
         logger.warning(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
         raise
     except Exception as e:
         msg = '写入失败,请检查工作表名以及行,列号, %s' % str(traceback.format_exc())
         logger.error(msg, e)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     finally:
         self.wb.close()
Exemplo n.º 29
0
 def close_browser(self):
     msg = '关闭当前页面'
     logger.info(msg)
     print(msg)
     CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     self.driver.close()
Exemplo n.º 30
0
 def clear_step_column_value(self, sheet_name):
     """
     清除执行时间,错误结果,错误信息,错误截图信息
     :param sheet_name:
     :return:
     """
     try:
         msg = '清除"%s"工作表测试结果中,请稍等...' % sheet_name
         logger.info(msg)
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
         end_times = self.get_column_value(sheet_name, TEST_STEP_END_TIME)
         err_infos = self.get_column_value(sheet_name, TEST_STEP_ERROR)
         err_pics = self.get_column_value(sheet_name, TEST_STEP_PICTURE)
         for a, b in enumerate(end_times):
             if b == '测试执行时间':
                 continue
             elif b != '' or b is not None:
                 self.wb[sheet_name].cell(a + 2, TEST_STEP_END_TIME, '')
         for e, f in enumerate(err_infos):
             if f == '错误信息':
                 continue
             elif f != '' or f is not None:
                 self.wb[sheet_name].cell(e + 2, TEST_STEP_ERROR, '')
         for g, h in enumerate(err_pics):
             if h == '测试截图':
                 continue
             elif h != '' or h is not None:
                 self.wb[sheet_name].cell(g + 2, TEST_STEP_PICTURE, '')
         # 清除用例的测试结果
         for l in range(5):
             results = self.get_column_value(sheet_name,
                                             TEST_STEP_RESULT + l)
             none_results = list(
                 filter(
                     None,
                     self.get_column_value(sheet_name,
                                           TEST_STEP_RESULT + l)))
             if len(none_results) == 0:
                 continue
             else:
                 for c, d in enumerate(results):
                     if '测试结果1' == d or '测试结果2' == d or '测试结果3' == d or '测试结果4' == d or '测试结果5' == d:
                         continue
                     elif type(
                             self.get_cell_object(
                                 sheet_name, c + 2, TEST_STEP_RESULT +
                                 l)).__name__ == 'MergedCell':
                         continue
                     elif d != '' or d is not None:
                         self.wb[sheet_name].cell(c + 2,
                                                  TEST_STEP_RESULT + l, '')
         self.wb.save(self.file_name)
     except PermissionError:
         msg = '请先关闭用例文件,再运行测试用例'
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
     except Exception as e:
         msg = '数据清空失败, 异常原因:%s' % str(traceback.format_exc())
         CaseInsertLogs.test_case_logs(self.task_obj.task_id, msg, 3)
         logger.error(msg, e)
     finally:
         self.wb.close()