UI封装断言

UI封装断言

前置条件

pip install selenium
pip install pytest

断言预期的元素是否可见

 def wait_element_visibility(self, locator, timeout=15, poll=0.3, extra_wait=None):
        """
        等待元素可见(浏览器窗口显示范围内)
        :param extra_wait: 智能等待结束后的额外等待时间/秒
        :param locator: 元素定位信息
        :param timeout: 超时时间
        :param poll: 轮询间隔时间/秒
        :return:
        """
        mes = 'xxx'
        try:
            WebDriverWait(self.driver, timeout, poll).until(ec.visibility_of_element_located(locator))
            if extra_wait:
                sleep_wait(extra_wait)
            print(f"{mes}可见")
            return True
        except Exception as e:
            print(f"{mes}不可见.{e}")
            return False

    def assert_element_visible(self, assert_locator, timeout=15):
        """断言元素是否可见"""
        assert self.wait_element_visibility(assert_locator, timeout)

断言实际值是否包含预期值

    def assert_contains2(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否包含@expected
        """
        mes = f'实际值:[{actual}]包含预期值:[{expected}]'
        try:
            assert expected in actual
        except AssertionError:
            raise AssertionError(f'{mes};不包含')

断言实际值是否包含多个预期的文本中的一个(模糊断言)

        def assert_contains(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否包含@expected
        """
	        mes = f'实际值:[{actual}]包含预期值:[{expected}]'
	
	        def __assert_c(act, exp_val):
	            try:
	                TeCa().assertIn(str(exp_val), str(act))
	            except AssertionError:
	                raise AssertionError(f'{mes};不包含')
	
	        if isinstance(expected, tuple) or isinstance(expected, list):
	            exp = ''
	            for val in expected:
	                exp = val
	                if actual == val:
	                    break
	            __assert_c(actual, exp)
	        else:
	            __assert_c(actual, expected)

断言实际值是否等于预期值

    def assert_equals(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否等于@expected
        """
        mes = f'实际值:[{actual}]等于预期值:[{expected}]'
        try:
            assert expected == actual
        except AssertionError:
            raise AssertionError(f'{mes};不包含')

    def assert_equals2(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否等于@expected
        """
        mes = f'实际值:[{actual}]等于预期值:[{expected}]'
        try:
            TeCa().assertEqual(actual, expected)
        except AssertionError:
            raise AssertionError(f'{mes};不包含')

断言为真

    def assert_ture(self, exp):
        """
        
        :param exp:
        :return: 断言是否为真
        """
        TeCa().assertTrue(exp)

    def assert_ture2(self, exp):
        """

        :param exp:
        :return: 断言是否为真
        """
        assert exp is True

断言为假

    def assert_false(self, exp):
        """

        :param exp:
        :return: 断言是否为假
        """
        assert exp is False

    def assert_false2(self, exp):
        """

        :param exp:
        :return: 断言是否为假
        """
        TeCa().assertFalse(exp)

断言预期文件是否存在(导出/下载后的等)

        output_path = r'xxx\xxx\xxx'

    def assert_output_file_exist(self, expect_file_path: str, timeout=60, poll=10, contrast_num=None):
        """

        :param contrast_num: 导出文件前的目标文件夹的文件数量
        :param expect_file_path: 预期的下载的文件的路径
        :param timeout: 超时时间/s
        :param poll: 轮询间隔/s
        :return: 断言是否已经发现预期文件
        """
        if self.output_path not in expect_file_path:
            expect_file_path = os.path.join(self.output_path, expect_file_path)
        end_time = time.time() + timeout
        while True:
            bool_file = FileUtils.file_if_exist(expect_file_path)
            # 若文件存在
            if bool_file is True:
                print(f"发现预期文件:{expect_file_path},创建时间:{os.path.getctime(expect_file_path)}")
                return bool_file
            # 若文件数量增加了,但是还是没有找到预期文件则停止,处理文件已经导出但是文件名称不对的情况--避免傻等
            if contrast_num is not None and self.get_current_output_dir_file_account() > contrast_num and \
                    FileUtils.file_if_exist(expect_file_path) is False:
                raise AssertionError(
                    f"导出文件:{expect_file_path}不存在,发现其他文件{os.listdir(self.em_output_path)};"
                    f"超时时间:{int(time.time() - start_time)}秒")
            sleep_wait(poll)
            # 超时则停止然后抛出异常
            if time.time() > end_time:
                break
        raise AssertionError(f"导出文件:{expect_file_path}不存在;超时时间:{timeout}")

    def get_current_output_dir_file_account(self):
        return FileUtils.get_file_amount_by_dir(self.output_path)


class FileUtils:
    @classmethod
    def file_if_exist(cls, file_path):
        """文件是否存在"""
        if os.path.exists(file_path) and os.path.isfile(file_path):
            return True
        return False

    @classmethod
    def get_file_amount_by_dir(cls, dir_path):
        """

        :param dir_path: 文件夹路径
        :return: 文件夹下有多少文件
        """
        gf_list = os.listdir(dir_path)
        file_list = []
        for rf in gf_list:
            file_path = os.path.join(dir_path, rf)
            if os.path.isfile(file_path):
                file_list.append(file_path)
        return len(file_list)

调试代码

import os
import time
from unittest import TestCase as TeCa

from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait


def sleep_wait(poll):
    time.sleep(poll)


class AssertUtils:

    def __init__(self):
        # 浏览器驱动
        self.driver = None

    def assert_contains(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否包含@expected
        """
        mes = f'实际值:[{actual}]包含预期值:[{expected}]'

        def __assert_c(act, exp_val):
            try:
                TeCa().assertIn(str(exp_val), str(act))
            except AssertionError:
                raise AssertionError(f'{mes};不包含')

        if isinstance(expected, tuple) or isinstance(expected, list):
            exp = ''
            for val in expected:
                exp = val
                if actual == val:
                    break
            __assert_c(actual, exp)
        else:
            __assert_c(actual, expected)

    def assert_contains2(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否包含@expected
        """
        mes = f'实际值:[{actual}]包含预期值:[{expected}]'
        try:
            assert expected in actual
        except AssertionError:
            raise AssertionError(f'{mes};不包含')

    def assert_equals(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否等于@expected
        """
        mes = f'实际值:[{actual}]等于预期值:[{expected}]'
        try:
            assert expected == actual
        except AssertionError:
            raise AssertionError(f'{mes};不包含')

    def assert_equals2(self, actual, expected):
        """
        :param actual:
        :param expected:
        :return:断言@actual是否等于@expected
        """
        mes = f'实际值:[{actual}]等于预期值:[{expected}]'
        try:
            TeCa().assertEqual(actual, expected)
        except AssertionError:
            raise AssertionError(f'{mes};不包含')

    def assert_ture(self, exp):
        """
        
        :param exp:
        :return: 断言是否为真
        """
        TeCa().assertTrue(exp)

    def assert_ture2(self, exp):
        """

        :param exp:
        :return: 断言是否为真
        """
        assert exp is True

    def assert_false(self, exp):
        """

        :param exp:
        :return: 断言是否为假
        """
        assert exp is False

    def assert_false2(self, exp):
        """

        :param exp:
        :return: 断言是否为假
        """
        TeCa().assertFalse(exp)

    def wait_element_visibility(self, locator, timeout=15, poll=0.3, extra_wait=None):
        """
        等待元素可见(浏览器窗口显示范围内)
        :param extra_wait: 智能等待结束后的额外等待时间/秒
        :param locator: 元素定位信息
        :param timeout: 超时时间
        :param poll: 轮询间隔时间/秒
        :return:
        """
        mes = 'xxx'
        try:
            WebDriverWait(self.driver, timeout, poll).until(ec.visibility_of_element_located(locator))
            if extra_wait:
                sleep_wait(extra_wait)
            print(f"{mes}可见")
            return True
        except Exception as e:
            print(f"{mes}不可见.{e}")
            return False

    def assert_element_visible(self, assert_locator, timeout=15):
        """断言元素是否可见"""
        assert self.wait_element_visibility(assert_locator, timeout)

    output_path = r'xxx\xxx\xxx'

    def assert_output_file_exist(self, expect_file_path: str, timeout=60, poll=10, contrast_num=None):
        """

        :param contrast_num: 导出文件前的目标文件夹的文件数量
        :param expect_file_path: 预期的下载的文件的路径
        :param timeout: 超时时间/s
        :param poll: 轮询间隔/s
        :return: 断言是否已经发现预期文件
        """
        if self.output_path not in expect_file_path:
            expect_file_path = os.path.join(self.output_path, expect_file_path)
        end_time = time.time() + timeout
        while True:
            bool_file = FileUtils.file_if_exist(expect_file_path)
            # 若文件存在
            if bool_file is True:
                print(f"发现预期文件:{expect_file_path},创建时间:{os.path.getctime(expect_file_path)}")
                return bool_file
            # 若文件数量增加了,但是还是没有找到预期文件则停止,处理文件已经导出但是文件名称不对的情况--避免傻等
            if contrast_num is not None and self.get_current_output_dir_file_account() > contrast_num and \
                    FileUtils.file_if_exist(expect_file_path) is False:
                raise AssertionError(
                    f"导出文件:{expect_file_path}不存在,发现其他文件{os.listdir(self.em_output_path)};"
                    f"超时时间:{int(time.time() - start_time)}秒")
            sleep_wait(poll)
            # 超时则停止然后抛出异常
            if time.time() > end_time:
                break
        raise AssertionError(f"导出文件:{expect_file_path}不存在;超时时间:{timeout}")

    def get_current_output_dir_file_account(self):
        return FileUtils.get_file_amount_by_dir(self.output_path)


class FileUtils:
    @classmethod
    def file_if_exist(cls, file_path):
        """文件是否存在"""
        if os.path.exists(file_path) and os.path.isfile(file_path):
            return True
        return False

    @classmethod
    def get_file_amount_by_dir(cls, dir_path):
        """

        :param dir_path: 文件夹路径
        :return: 文件夹下有多少文件
        """
        gf_list = os.listdir(dir_path)
        file_list = []
        for rf in gf_list:
            file_path = os.path.join(dir_path, rf)
            if os.path.isfile(file_path):
                file_list.append(file_path)
        return len(file_list)


if __name__ == '__main__':
    # AssertUtils().assert_ture(1 > 1)
    AssertUtils().assert_contains(1, (3, 2, 2))


在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java Selenium TestNG中,可以封装断言方法来验证测试结果。根据提供的引用内容,可以看到有三个封装断言方法。 第一个引用\[1\]中的方法是assertElementTextContains,它用于验证指定元素的文本是否包含预期的内容。该方法首先获取元素的文本,然后使用assertContains方法进行断言。 第二个引用\[2\]中的方法是assertNotEquals,它用于验证两个对象是否不相等。该方法首先使用assertFalse方法判断实际值和预期值是否相等,如果相等则抛出AssertionError异常。 第三个引用\[2\]中的方法是assertElementVisible和assertElementNotVisible,它们分别用于验证元素是否可见和不可见。这两个方法使用waitElementIsVisible方法等待元素的可见性,并使用assertTrue和assertFalse方法进行断言。 因此,可以根据需要选择合适的断言方法来验证测试结果。 #### 引用[.reference_title] - *1* *2* [Java版UI自动化测试的断言方法/selenium Testng方法封装断言](https://blog.csdn.net/Franciz777/article/details/114063739)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [JAVA+selenium+testng 断言封装及调用](https://blog.csdn.net/weixin_44242153/article/details/117709979)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值