示例#1
0
    def check(self, step, element):
        if Path(self.expected.get('#ScreenShot', '')).is_file():
            # 屏幕截图比较
            image1 = Image.open(step['ScreenShot'])
            image2 = Image.open(step['ScreenShot'])
            histogram1 = image1.histogram()
            histogram2 = image2.histogram()
            differ = math.sqrt(reduce(operator.add, list(
                map(lambda a, b: (a - b)**2, histogram1, histogram2))) / len(histogram1))
            diff = ImageChops.difference(image1, image2)
            if differ == 0.0:
                # 图片间没有任何不同
                logger.info('SnapShot: ScreenShot is the same')
            else:
                file_name = '#' + self.label + now() + '.png'
                step['diffScreen'] = str(
                    Path(self.snapshot_folder) / file_name)
                diff.save(step['diffScreen'])
                raise Exception('SnapShot: ScreenShot is diff: %s' % differ)
        elif self.expected.get('ScreenShot'):
            g.driver.get_screenshot_as_file(self.expected['ScreenShot'])

        if Path(self.expected.get('#ElementShot', '')).is_file():
            file_name = self.label + now() + '#Element' + '.png'
            step['ElementShot'] = str(Path(self.snapshot_folder) / file_name)
            crop(element, step['ScreenShot'], step['ElementShot'])

            # 屏幕截图比较
            image1 = Image.open(self.expected['#ElementShot'])
            image2 = Image.open(step['ElementShot'])
            histogram1 = image1.histogram()
            histogram2 = image2.histogram()
            differ = math.sqrt(reduce(operator.add, list(
                map(lambda a, b: (a - b)**2, histogram1, histogram2))) / len(histogram1))
            diff = ImageChops.difference(image1, image2)
            if differ == 0.0:
                logger.info('SnapShot: ElementShot is the same')
            else:
                file_name = '#' + self.label + now() + '#Element' + '.png'
                step['diffElement'] = str(
                    Path(self.snapshot_folder) / file_name)
                diff.save(step['diffElement'])
                raise Exception('SnapShot: ElementShot is diff: %s' % differ)
        elif self.expected.get('#ElementShot'):
            crop(element, step['ScreenShot'], self.expected['#ElementShot'])
示例#2
0
    def web_screen(self, step, element):
        # 截图
        screen_v = self.output.get('#ScreenShot', '')
        element_v = self.output.get('#ElementShot', '')

        if g.snapshot or self.screen_flag or self.element_flag:
            from selenium.webdriver.support import expected_conditions as EC
            if not EC.alert_is_present()(g.driver):
                file_name = self.label + now() + '.png'
                step['#ScreenShot'] = str(
                    Path(self.snapshot_folder) / file_name)
                get_screenshot(step['#ScreenShot'])
                if screen_v:
                    g.var[screen_v] = step['#ScreenShot']

        if element_v:
            file_name = self.label + now() + '#Element' + '.png'
            step['#ElementShot'] = str(Path(self.snapshot_folder) / file_name)
            crop(element, step['#ScreenShot'], step['#ElementShot'])
            g.var[element_v] = step['#ElementShot']
示例#3
0
    def windwos_capture(self, dialog, step):
        # 截图
        screen_v = self.output.get('#ScreenShot', '')
        element_v = self.output.get('#ElementShot', '')

        if g.snapshot or self.screen_flag:
            if self.expected.get('#ScreenName'):
                screen_name = self.expected['#ScreenName']
            elif screen_v:
                screen_name = screen_v
            else:
                screen_name = ''
            if screen_name:
                file_name = self.label + now(
                ) + '#Screen' + '[' + screen_name + ']' + '.png'
            else:
                file_name = self.label + now() + '#Screen' + '.png'
            step['snapshot']['Real_Screen'] = str(
                Path(self.snapshot_folder) / file_name)
            pic = dialog.capture_as_image()
            pic.save(step['snapshot']['Real_Screen'])
            if screen_v:
                g.var[screen_v] = step['snapshot']['Real_Screen']

        if element_v:
            file_name = self.label + now(
            ) + '#Element' + '[' + element_v + ']' + '.png'
            step['snapshot']['Real_Element'] = str(
                Path(self.snapshot_folder) / file_name)

            element = step['element']
            if dialog.backend.name == 'win32':
                pic = dialog.window(best_match=element).capture_as_image()
            elif dialog.backend.name == 'uia':
                pic = dialog.child_window(
                    best_match=element).capture_as_image()
            pic.save(step['snapshot']['Real_Screen'])
            g.var[element_v] = step['snapshot']['Real_Element']
示例#4
0
    def windwos_check(self, dialog, step):
        element = step['element']
        if Path(self.expected.get('#ScreenShot', '')).is_file():
            # 屏幕截图比较
            image1 = Image.open(self.expected['#ScreenShot'])
            image2 = Image.open(step['#ScreenShot'])
            histogram1 = image1.histogram()
            histogram2 = image2.histogram()
            differ = math.sqrt(
                reduce(
                    operator.add,
                    list(map(lambda a, b:
                             (a - b)**2, histogram1, histogram2))) /
                len(histogram1))
            diff = ImageChops.difference(image1, image2)
            if differ == 0.0:
                # 图片间没有任何不同
                logger.info('SnapShot: ScreenShot is the same')
            else:
                file_name = '#' + self.label + now() + '.png'
                step['#diffScreen'] = str(
                    Path(self.snapshot_folder) / file_name)
                diff.save(step['#diffScreen'])
                raise Exception('SnapShot: ScreenShot is diff: %s' % differ)
        elif self.expected.get('#ScreenShot'):
            pic = dialog.capture_as_image()
            pic.save(self.expected['#ScreenShot'])

        if Path(self.expected.get('#ElementShot', '')).is_file():
            file_name = self.label + now() + '#Element' + '.png'
            step['#ElementShot'] = str(Path(self.snapshot_folder) / file_name)
            if dialog.backend.name == 'win32':
                pic = dialog.window(best_match=element).capture_as_image()
            elif dialog.backend.name == 'uia':
                pic = dialog.child_window(
                    best_match=element).capture_as_image()
            pic.save(step['#ElementShot'])

            # 屏幕截图比较
            image1 = Image.open(self.expected['#ElementShot'])
            image2 = Image.open(step['#ElementShot'])
            histogram1 = image1.histogram()
            histogram2 = image2.histogram()
            differ = math.sqrt(
                reduce(
                    operator.add,
                    list(map(lambda a, b:
                             (a - b)**2, histogram1, histogram2))) /
                len(histogram1))
            diff = ImageChops.difference(image1, image2)
            if differ == 0.0:
                logger.info('SnapShot: ElementShot is the same')
            else:
                file_name = '#' + self.label + now() + '#Element' + '.png'
                step['#diffElement'] = str(
                    Path(self.snapshot_folder) / file_name)
                diff.save(step['#diffElement'])
                raise Exception('SnapShot: ElementShot is diff: %s' % differ)
        elif self.expected.get('#ElementShot'):
            if dialog.backend.name == 'win32':
                pic = dialog.window(best_match=element).capture_as_image()
            elif dialog.backend.name == 'uia':
                pic = dialog.child_window(
                    best_match=element).capture_as_image()
            pic.save(self.expected['#ElementShot'])
示例#5
0
    def run(self):
        logger.info('Run the TestCase: %s|%s' %
                    (self.testcase['id'], self.testcase['title']))
        self.testcase['result'] = 'success'
        self.testcase['report'] = ''
        if_result = ''

        for index, step in enumerate(self.testcase['steps']):
            # 统计开始时间
            step['start_timestamp'] = timestamp()

            # if 为否,不执行 then 语句
            if step['control'] == '>' and not if_result:
                step['score'] = '-'
                step['end_timestamp'] = timestamp()
                continue

            # if 为真,不执行 else 语句
            if step['control'] == '<' and if_result:
                step['score'] = '-'
                step['end_timestamp'] = timestamp()
                continue

            logger.info('Run the Step: %s|%s|%s' %
                        (step['no'], step['keyword'], step['element']))

            if not (g.platform.lower() in ('windows', )
                    and step['keyword'].upper() in windows_keywords):
                step['page'], step['custom'], step[
                    'element'] = elements_format(step['page'], step['element'])
            label = g.sheet_name + '#' + \
                self.testcase['id'] + '#' + str(step['no']).replace('<', '(').replace('>', ')').replace('*', 'x')
            snap = Snapshot()
            try:
                after_function = step['data'].pop('AFTER_FUNCTION', '')

                # 处理强制等待时间
                t = step['data'].pop('等待时间', 0)
                sleep(float(t))

                # 变量替换
                replace_dict(step['data'])
                replace_dict(step['expected'])

                step['data'].pop('BEFORE_FUNCTION', '')

                if isinstance(step['element'], str):
                    step['element'] = replace(step['element'])
                    step['_element'] = step['element']
                elif isinstance(step['element'], list):
                    for i in range(len(step['element'])):
                        step['element'][i] = replace(step['element'][i])
                    step['_element'] = '|'.join(step['element'])

                step['vdata'] = v_data(step['data'])

                if g.platform.lower(
                ) in ('desktop', ) and step['keyword'].upper() in web_keywords:
                    # 处理截图数据
                    snap.pre(step, label)

                    if step['keyword'].upper() not in ('MESSAGE', '对话框'):
                        # 判断页面是否已和窗口做了关联,如果没有,就关联当前窗口,如果已关联,则判断是否需要切换
                        w.switch_window(step['page'])
                        # 切换 frame 处理,支持变量替换
                        frame = replace(step['custom'])
                        w.switch_frame(frame)

                    # 根据关键字调用关键字实现
                    element = getattr(web, step['keyword'].lower())(step)
                    snap.web_shot(step, element)

                elif g.platform.lower() in (
                        'ios', 'android'
                ) and step['keyword'].upper() in mobile_keywords:
                    # 切換 context 處理
                    context = replace(step['custom']).strip()
                    w.switch_context(context)

                    if w.current_context.startswith('WEBVIEW'):
                        # 切换标签页
                        tab = step['data'].get('标签页')
                        if tab:
                            del step['data']['标签页']
                            g.driver.switch_to_window(w.windows[tab])
                        logger.info('Current Context: %s' %
                                    repr(w.current_context))

                    # 根据关键字调用关键字实现
                    getattr(mobile, step['keyword'].lower())(step)

                elif g.platform.lower() in (
                        'windows',
                ) and step['keyword'].upper() in windows_keywords:
                    from sweetest.keywords import windows
                    _page = ''
                    if step['page'].startswith('#'):
                        _page = step['page'][1:]
                        page = [
                            x for x in re.split(r'(<|>)', _page) if x != ''
                        ]
                    else:
                        page = [
                            x for x in re.split(r'(<|>)', step['page'])
                            if x != ''
                        ]

                    if _page:
                        dialog = g.windows['#'].dialog(page)
                    else:
                        dialog = g.windows['default'].dialog(page)
                    #dialog.wait('ready')

                    snap.pre(step, label)

                    # 根据关键字调用关键字实现
                    getattr(windows, step['keyword'].lower())(dialog, step)
                    snap.windows_shot(dialog, step)

                elif step['keyword'].upper() in http_keywords:
                    # 根据关键字调用关键字实现
                    getattr(http, step['keyword'].lower())(step)

                elif step['keyword'].upper() in files_keywords:
                    # 根据关键字调用关键字实现
                    getattr(files, step['keyword'].lower())(step)

                elif step['keyword'].lower() == 'execute':
                    result, steps = getattr(common,
                                            step['keyword'].lower())(step)
                    self.testcase['result'] = result
                    if step['page'] in ('SNIPPET', '用例片段'):
                        self.snippet_steps[index + 1] = steps
                    if result != 'success':
                        step['end_timestamp'] = timestamp()
                        break

                    # elif step['page'] in ('SCRIPT', '脚本'):
                    #     # 判断页面是否已和窗口做了关联,如果没有,就关联当前窗口,如果已关联,则判断是否需要切换
                    #     w.switch_window(step['page'])
                    #     # 切换 frame 处理,支持变量替换
                    #     frame = replace(step['custom'])
                    #     w.switch_frame(frame)
                    #     common.script(step)

                else:
                    # 根据关键字调用关键字实现
                    getattr(common, step['keyword'].lower())(step)
                logger.info('Run the Step: %s|%s|%s is success' %
                            (step['no'], step['keyword'], step['element']))
                step['score'] = 'OK'

                # if 语句结果赋值
                if step['control'] == '^':
                    if_result = True

                if after_function:
                    replace_dict({'after_function': after_function})
                # 操作后,等待0.2秒
                sleep(0.2)
            except Exception as exception:
                file_name = '^' + label + now() + '.png'
                step['snapshot'] = str(snap.snapshot_folder / file_name)

                if g.platform.lower(
                ) in ('desktop', ) and step['keyword'].upper() in web_keywords:
                    try:
                        if w.frame != 0:
                            g.driver.switch_to.default_content()
                            w.frame = 0
                        g.driver.get_screenshot_as_file(step['snapshot'])
                    except:
                        logger.exception(
                            '*** save the screenshot is failure ***')

                elif g.platform.lower() in (
                        'ios', 'android'
                ) and step['keyword'].upper() in mobile_keywords:
                    try:
                        g.driver.switch_to_default_content()
                        w.current_context = 'NATIVE_APP'
                        g.driver.get_screenshot_as_file(snapshot_file)
                    except:
                        logger.exception(
                            '*** save the screenshot is failure ***')

                logger.exception(
                    'Run the Step: %s|%s|%s is failure' %
                    (step['no'], step['keyword'], step['element']))
                step['score'] = 'NO'

                # if 语句结果赋值
                if step['control'] == '^':
                    if_result = False
                    step['end_timestamp'] = timestamp()
                    continue

                self.testcase['result'] = 'failure'
                self.testcase['report'] = 'step-%s|%s|%s: %s' % (
                    step['no'], step['keyword'], step['element'], exception)
                step['remark'] += str(exception)
                step['end_timestamp'] = timestamp()
                break

            # 统计结束时间
            step['end_timestamp'] = timestamp()

        steps = []
        i = 0
        for k in self.snippet_steps:
            steps += self.testcase['steps'][i:k] + self.snippet_steps[k]
            i = k
        steps += self.testcase['steps'][i:]
        self.testcase['steps'] = steps
示例#6
0
    def web_check(self, step, element):
        def deep(src):
            # 把不需要比较的部分贴白
            if self.expected.get('#blank'):
                blank(src, eval(self.expected.get('#blank')))
            # 裁剪需要比较的部分
            if self.expected.get('#cut'):
                cut(src, src, eval(self.expected.get('#cut')))

        if Path(step['snapshot'].get('Expected_Screen', '')).is_file():
            # 屏幕截图比较
            image1 = Image.open(step['snapshot']['Expected_Screen'])
            image2 = Image.open(step['snapshot']['Real_Screen'])
            deep(step['snapshot']['Real_Screen'])
            histogram1 = image1.histogram()
            histogram2 = image2.histogram()
            differ = math.sqrt(
                reduce(
                    operator.add,
                    list(map(lambda a, b:
                             (a - b)**2, histogram1, histogram2))) /
                len(histogram1))
            diff = ImageChops.difference(image1.convert('RGB'),
                                         image2.convert('RGB'))
            if differ == 0.0:
                # 图片间没有任何不同
                logger.info('SnapShot: ScreenShot is the same')
            else:
                file_name = self.label + now() + 'Diff_Screen' + '.png'
                step['snapshot']['Diff_Screen'] = str(
                    Path(self.snapshot_folder) / file_name)
                diff.save(step['snapshot']['Diff_Screen'])
                raise Exception('SnapShot: ScreenShot is diff: %s' % differ)
        elif step['snapshot'].get('Expected_Screen'):
            get_screenshot(step['snapshot']['Expected_Screen'])
            deep(step['snapshot']['Expected_Screen'])

        if Path(step['snapshot'].get('Expected_Element', '')).is_file():
            file_name = self.label + now(
            ) + '#Element' + '[' + self.expected['#ElementName'] + ']' + '.png'
            step['snapshot']['Real_Element'] = str(
                Path(self.snapshot_folder) / file_name)
            crop(element, step['snapshot']['Real_Screen'],
                 step['snapshot']['Real_Element'])
            deep(step['snapshot']['Real_Element'])

            # 屏幕截图比较
            image1 = Image.open(step['snapshot']['Expected_Element'])
            image2 = Image.open(step['snapshot']['Real_Element'])
            histogram1 = image1.histogram()
            histogram2 = image2.histogram()
            differ = math.sqrt(
                reduce(
                    operator.add,
                    list(map(lambda a, b:
                             (a - b)**2, histogram1, histogram2))) /
                len(histogram1))
            diff = ImageChops.difference(image1.convert('RGB'),
                                         image2.convert('RGB'))
            if differ == 0.0:
                logger.info('SnapShot: ElementShot is the same')
            else:
                file_name = self.label + now() + 'Diff_Element' + '.png'
                step['snapshot']['Diff_Element'] = str(
                    Path(self.snapshot_folder) / file_name)
                diff.save(step['snapshot']['Diff_Element'])
                raise Exception('SnapShot: ElementShot is diff: %s' % differ)
        elif step['snapshot'].get('Expected_Element'):
            crop(element, step['snapshot']['Real_Screen'],
                 step['snapshot']['Expected_Element'])
            deep(step['snapshot']['Expected_Element'])