自动化测试实现案例失败截图重试机制

脚本编写采用的python语言,编写testcase装饰器实现案例失败重试的机制

  • testcase
from functools import wraps
from App.Driver import Driver

def testcase(reruns:int,exceptions=Exception):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            module = __import__('App.TestCase',fromlist=['TestCase'])
            classname = func.__qualname__.split('.')[0]
            cls = getattr(module,classname)
            total = reruns
            while total>=0:
                try:
                    ret = func(*args, **kwargs)
                    return ret
                except exceptions as e:
                    if total == 0:
                        date = time.strftime('%Y%m%d-%H%M%S',time.localtime())
                        name = func.__qualname__ +date+'.PNG'
                        Driver.screenshot(name)
                        raise e
                    total -= 1
                    time.sleep(1)
                    print("failed,try again....\n failed reason:\n{}".format(e))
                    cls().setUp()
        return wrapper
    return decorator

案例管理采用的python自带的unittest单元测试框架,BaseTest基础测试类继承于unittest.TestCase,封装好测试的Hook方法:setUpClasssetUptearDowntearDownClass,业务测试集继承BaseTest,使用testcase装饰器装饰所有测试案例:

  • BaseTest
from unittest import TestCase
class BaseTest(TestCase):
    @classmethod
    def setUpClass(cls):
        '''重置应用'''
        pass
  
    def setUp(self):
        '''每次运行案例前重启应用'''
        pass

    def tearDown(self):
        '''执行结束,数据处理'''
        pass

    @classmethod
    def tearDownClass(cls):
          '''执行结束,数据处理'''
        pass
  • TestLoginSuite
from App.TestCase.conftest import BaseTest,testcase
class TestLoginSuite(BaseTest):
    @testcase(reruns=2)
    def test_01_register_and_login(self):
        '''注册并登录'''
        pass

    @testcase(reruns=2)
    def test_02_check_my_welfare(self):
        '''新手福利检查'''
        pass

    @testcase(reruns=2)
    def test_03_logout(self):
        '''退出登录'''
        pass

    @testcase(reruns=2)
    def test_04_login_by_old_user(self):
        '''老用户登录-退出'''
        pass

    @testcase(reruns=2)
    def test_05_login_by_code(self):
        '''用户首次验证码登录'''
        pass

你可能感兴趣的:(自动化测试实现案例失败截图重试机制)