Esempio n. 1
0
    def OnKeyPress(self, evt):
        """
        :param evt: 窗口响应键盘鼠标事件句柄(ctrl+r 运行)
        :return: 调用TestRunAuto函数执行生成的default.py脚本
        """
        log_flag = 0  # 此处控制ctrl+r执行代码是否需要记录log, 默认不需要
        key_code = evt.GetKeyCode()
        if key_code == 18:  # Ctrl+R

            cmd = '\n'.join([
                '# -*- coding: UTF-8 -*-',
                'from dcntestlibrary.dcnlibrary.dreceiver import *',
                'from dcntestlibrary.dcnlibrary.lib_all import * ',
                self.GetValue()
            ])
            path = os.path.join(self.local_dir, 'default.py')
            with open(path, 'w+') as f:
                f.writelines(cmd)
            if self.Parent.thread and self.Parent.thread.isAlive():
                printRes(
                    '[One test is running,please stop it and then start a new one!]'
                )
            else:
                self.Parent.TestRunAuto(path, log_flag)
        evt.Skip()  # 释放句柄 以方便后面的脚本执行
Esempio n. 2
0
def printCheckStepDebug(test_name, step, *res_1):
    """
    # 检查测试例step对错,打印 如果fail则暂停脚本
    :param test_name: test name
    :param step: step 1 2
    :param res_1: other args
    :return: 0 or 1
    """
    time.sleep(0.5)
    _res = 0
    global FILEDSTEPLIST
    for i in res_1:
        if i == 0:
            printRes('[res = ' + str(i) + ']Check res = 0,OK!')
        else:
            printResError('[res = ' + str(i) + ']Check res = 0,Failed!')
            _res = 1
    
    if _res == 1:
        FILEDSTEPLIST.append(step)
        if wx.FindWindowById(10).nowrunning not in wx.FindWindowById(10).faillist:
            if wx.FindWindowById(10).nowrunning != '':
                wx.FindWindowById(10).faillist.append(wx.FindWindowById(10).nowrunning)
        printResError(test_name + ' ' + step + ' is FAILED!')
        wx.MessageBox('该Step不通过,已停止脚本保留现场')
        wx.FindWindowById(10).PauseTestAuto()
    else:
        printRes(test_name + ' ' + step + ' is PASSED!')
    time.sleep(0.5)
    return _res
Esempio n. 3
0
def CheckLineList(data, checklist, **flag):
    """
##################################################################################
#
# CheckLineList :检查表项中是否含有指定的多行
#
# args:
#     data: 要检查匹配的值
#     checklist : 需要匹配的字符串列表,类型为由元组组成的列表[(tuple),(tuple),(tuple)]
#     **flag: 可选的标志位[RS:列敏感]
#
# return:
#     成功:返回0
#     失败:返回-1
#
# addition:
#
# examples:
#    data:
#    1    00-00-01-00-00-02           DYNAMIC Hardware Ethernet1/0/1
#    1    00-00-01-00-00-03           DYNAMIC Hardware Ethernet1/0/1
#    1    00-00-01-00-00-04           DYNAMIC Hardware Ethernet1/0/1
#    1    00-00-01-00-00-05           DYNAMIC Hardware Ethernet1/0/1
#    1    00-00-01-00-00-06           DYNAMIC Hardware Ethernet1/0/1
#
#    checklist1 = []
#    checklist1.append(('00-00-01-00-00-02','DYNAMIC'))
#    checklist1.append(('00-00-01-00-00-03','DYNAMIC'))
#    checklist1.append(('00-00-01-00-00-06','DYNAMIC'))
#
#    CheckLineList(data,checklist1)
#    return 0
#    CheckLineList(data,checklist1,RS=True)
#    return -1
###################################################################################
    modified by yanwh 2017/12/28
    给rx赋予初始值,用isinstance的方式判断数据类型取代之前的type方式,兼容支持string和unicode类型
    :param data: 要检查匹配的值
    :param checklist: 需要匹配的字符串列表,类型为由元组组成的列表[(tuple),(tuple),(tuple)]
    :param flag: 可选的标志位[RS:列敏感]
    :return: 成功:返回0
             失败:返回-1
    """
    res, rx = 0, -1
    if not isinstance(checklist, list):
        printRes('Error:Require a list type!')
        return -3
    for checkline in checklist:
        if isinstance(checkline, tuple):
            rx = CheckLine(data, *checkline, **flag)
        elif isinstance(checkline, str):
            rx = CheckLine(data, checkline, **flag)
        if rx == -1:
            res = -1
    return res
Esempio n. 4
0
def newweb_init(host, port='11999'):
    try:
        profile = webdriver.FirefoxProfile()
        profile.accept_untrusted_certs = True
        url = 'http://' + host + ':' + port + '/wd/hub'
        driver = webdriver.Remote(command_executor=url, desired_capabilities=DesiredCapabilities.FIREFOX,
                                  browser_profile=profile)
        return driver
    except (TimeoutException, Exception) as e:
        printRes(str({'status': False, 'Message': str(e)}))
        return None
Esempio n. 5
0
 def PrintLogInfoAuto(self, msg=''):
     """
     alt+t 打印时间
     :param msg: 要打印到屏幕的信息
     :return:
     """
     page_list = self.GetPages()
     for page in page_list:
         sut = str(page)
         printScr(sut, msg)
     printRes(msg)
Esempio n. 6
0
def CheckLineInOneRow(data, checklist, **flag):
    patten = []
    if not isinstance(checklist, list):
        printRes('Error:Require a list type!')
        return -3
    for checkline in checklist:
        if isinstance(checkline, tuple):
            for i in checkline:
                patten.append(i)
        elif isinstance(checkline, str):
            patten.append(checkline)

        patten.append('\n')
    patten = tuple(patten)
    res = CheckLine(data, PM=False, *patten, **flag)
    return res
Esempio n. 7
0
def CheckNoLineList(data, checklist, **flag):
    res = 0
    # if type(checklist) != type([]):
    if not isinstance(checklist, list):
        printRes('Error:Require a list type!')
        return -3
    for checkline in checklist:
        rx = 0
        # rx = CheckNoLine(data,*checkline,**flag)
        # if type(checkline) == type(()):
        if isinstance(checkline, tuple):
            rx = CheckLine(data, *checkline, **flag)
        # elif type(checkline) == type(''):
        elif isinstance(checkline, str):
            rx = CheckLine(data, checkline, **flag)
        if rx == 0:
            res = -1
    return res
Esempio n. 8
0
def CheckLineInOrder(data, checklist, **flag):
    patten = []
    if not isinstance(checklist, list):
        # if type(checklist) != type([]):
        printRes('Error:Require a list type!')
        return -3

    for checkline in checklist:
        # if type(checkline) == type(()):
        if isinstance(checkline, tuple):
            for i in checkline:
                patten.append(i)
        elif isinstance(checkline, str):
            # elif type(checkline) == type(''):
            patten.append(checkline)

    patten = tuple(patten)
    res = CheckLine(data, ML=True, *patten, **flag)
    return res
Esempio n. 9
0
def printCheckStep(test_name, step, *res_1):
    """
    检查测试例step对错,打印并记录
    :param test_name: test name
    :param step: 步骤 step 1 2
    :param res_1: other args
    :return: 0 or 1 success or fail
    """
    time.sleep(0.5)
    _res = 0
    global FILEDSTEPLIST
    for i in res_1:
        if i == 0:
            printRes('[res = ' + str(i) + ']Check res = 0,OK!')
        else:
            printResError('[res = ' + str(i) + ']Check res = 0,Failed!')
            _res = 1
    
    if _res == 1:
        FILEDSTEPLIST.append(step)
        if wx.FindWindowById(10).nowrunning not in wx.FindWindowById(10).faillist:
            if wx.FindWindowById(10).nowrunning != '':
                wx.FindWindowById(10).faillist.append(wx.FindWindowById(10).nowrunning)
        printResError(test_name + ' ' + step + ' is FAILED!')
        if LoadErrorStopConfig():
            def errorPause():
                """
                遇错暂停
                :return:
                """
                window = wx.FindWindowByName('Main')
                window.PauseTestAuto()
            
            errorPause()
    else:
        printRes(test_name + ' ' + step + ' is PASSED!')
    time.sleep(0.5)
    return _res
Esempio n. 10
0
def GetValueBetweenTwoValuesInData(data,
                                   beforevalue,
                                   behindvalue,
                                   mode='line'):
    if mode == 'line':
        temp1 = str(beforevalue) + '(.*)' + str(behindvalue)
        temp2 = re.search(temp1, data)
        if temp2 is not None:
            temp3 = temp2.group(1)
            # strinfo = 'The value between ' + beforevalue + ' and ' + behindvalue + ' is: ' + temp3
            # printRes(strinfo)
            return temp3
        else:
            strinfo = 'There may be no value between ' + beforevalue + ' and ' + behindvalue
            printRes(strinfo)
            printRes('The data is:')
            printRes(data)
            printRes('The beforevalue is:')
            printRes(beforevalue)
            printRes('The behindvalue is:')
            printRes(behindvalue)
            return 0
    if mode == 'moreline':
        temp1 = str(beforevalue) + '([\s\S]+)' + str(behindvalue)
        temp2 = re.search(temp1, data)
        if temp2 is not None:
            temp3 = temp2.group(1)
            # strinfo = 'The value between ' + beforevalue + ' and ' + behindvalue + ' is: ' + temp3
            # printRes(strinfo)
            return temp3
        else:
            strinfo = 'There may be no value between ' + beforevalue + ' and ' + behindvalue
            printRes(strinfo)
            printRes('The data is:')
            printRes(data)
            printRes('The beforevalue is:')
            printRes(beforevalue)
            printRes('The behindvalue is:')
            printRes(behindvalue)
            return 0
Esempio n. 11
0
def CheckLine(data, *args, **flag):
    """
##################################################################################
#
# CheckLine :检查表项中是否含有指定行
#
# args:
#     data: 要检查匹配的值
#     *args : 需要匹配的字符串,以逗号分隔
#     **flag: 可选的标志位[RS:列敏感]
#
# return:
#     成功:返回0
#     失败:返回-1
#
# addition:
#
# examples:
#    在某一行中按先后顺序存在1、2、5
#    CheckLine('1 2 3 4 5','1','2')
#    return 0
#
#    列敏感
#    CheckLine('1 2 3 4 5','1','2',RS = True)
#    return 0
#    CheckLine('1 2 3 4 5','1','5',RS = True)
#    return -1
#    CheckLine('1 2 3 4 5','1','','','','5',RS = True)
#    return 0
###################################################################################
    :param data: 要检查匹配的值
    :param args: 需要匹配的字符串,以逗号分隔
    :param flag: 可选的标志位[RS:列敏感]
    :return: 成功:返回0, 失败:返回-1
    """
    rowSensitive = False
    printMatch = True
    moreLine = False
    ignoreCase = False
    for j in list(flag.keys()):
        if j == 'RS':
            rowSensitive = flag[j]
        elif j == 'PM':
            printMatch = flag[j]
        elif j == 'ML':
            moreLine = flag[j]
        elif j == 'IC':
            ignoreCase = flag[j]

    if not rowSensitive:
        pat = '.*?'
        patstr = '.*?'
    else:
        pat = '\s*'
        patstr = '\s*'

    for i in args:
        if i == '':
            i = '[\S]+'
        patstr += str(i) + pat
    if moreLine:
        compilerule = re.compile(patstr, re.S)
    elif ignoreCase:
        compilerule = re.compile(patstr, re.I)
    else:
        compilerule = re.compile(patstr)
    match = compilerule.search(data)
    if match:
        try:
            if printMatch:
                printRes('[Match Line:]' + str(match.group()))
            res = 0
        except BaseException as e:
            print(e)
            res = -2
    else:
        if printMatch:
            printResWarn('[Match Line Fail:]' + patstr)
        res = -1
    return res
Esempio n. 12
0
def printGlobal(title, switch, msg='', logprefix=''):
    """
    方案脚本控制-开始计时/结束计时,统计执行信息
    说明:此处的函数实现不合理,但是为了兼容原有的实现方式不得已保留,后续可对此进行重构
    :param title: s1 s2
    :param switch:控制start stop end tlend
    :param msg: 打印的信息
    :param logprefix: 日志前缀
    :return: None
    """
    global TESTNAME
    global TESTNUM
    global tempTESTNUM
    global TOTALTESTNUM
    global tempTOTALTESTNUM
    global RERUNTESTNUM
    global FAILLIST
    global TOTALFAILLIST
    global STARTTIME
    global TOTALSTARTTIME
    global RERUNSTARTTEME
    global ENDTIME
    global TOTALENDTIME
    global RERUNENDTIME
    global TESTID
    
    TESTNAME = title
    thistime = datetime.datetime.now()
    mainWin = wx.FindWindowById(10)
    affirm_tl_operate = mainWin.tl  # 获取跟testlink服务器交互句柄
    if (switch == 'start') or (switch == 'Start'):
        TESTID = time.strftime("%Y%m%d", time.localtime()) + str(int(time.time()))
        mainWin.dbInfo['id'] = TESTID
        STARTTIME = thistime
        TESTNUM = 0
        FAILLIST = []
        res = printFormat(title + ' ' + switch + ' ' + str(thistime), msg)
        # 开始记录console的log
        if mainWin.logger:
            mainWin.logger = close_logger(mainWin.logger)
        mainWin.logger = DcnLog(log_base_path=mainWin.log_base_path,
                                log_define_type='run',
                                prefix_log_name=logprefix,
                                console_name='console',
                                test_name=TESTNAME).create_log()
        printAll(res)
    elif (switch == 'Rerunstart') or (switch == 'RerunStart'):
        TESTID = time.strftime("%Y%m%d", time.localtime()) + str(int(time.time()))
        mainWin.dbInfo['id'] = TESTID
        RERUNSTARTTEME = thistime
        RERUNTESTNUM = 0
        tempTESTNUM = TESTNUM
        tempTOTALTESTNUM = TOTALTESTNUM
        FAILLIST = []
        res = printFormat(title + ' ' + switch + ' ' + str(thistime), msg)
        printAll(res)
        if mainWin.logger:
            mainWin.logger = close_logger(mainWin.logger)
        mainWin.logger = DcnLog(log_base_path=mainWin.log_base_path,
                                log_define_type='run',
                                prefix_log_name=logprefix + '[ReRun]',
                                console_name='console',
                                test_name=TESTNAME).create_log()
    elif (switch == 'end') or (switch == 'End'):
        ENDTIME = thistime
        duration = timediff(STARTTIME, ENDTIME)
        res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration)
        printAll(res)
        res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str(STARTTIME) + '\n' + 'End Time   :' + str(
            ENDTIME) + '\n' + 'Duration Time :' + str(duration)
        failnum = len(FAILLIST)
        printAll(res_str)
        printAll('TestCase : Total ' + str(TESTNUM) + '\n           Pass  ' + str(
            TESTNUM - failnum) + '\n           Fail  ' + str(failnum))
        if failnum > 0:
            printstr = ''
            printAll('Failed TestCase :')
            for j in FAILLIST:
                printstr += str(j) + '\n'
            printAll(printstr)
        
        printAll('')
        mainWin.dbInfo['totalcases'] = str(TESTNUM)
        mainWin.dbInfo['passed'] = str(TESTNUM - failnum)
        mainWin.dbInfo['failed'] = str(failnum)
        mainWin.dbInfo['knownbugs'] = 'Not available'
        mainWin.dbInfo['unknowbugs'] = 'Not available'
        mainWin.dbInfo['failsummary'] = str(FAILLIST)
        mainWin.dbInfo['suggestions'] = 'Not available'
        mainWin.dbInfo['starttime'] = str(STARTTIME)
        mainWin.dbInfo['stoptime'] = str(ENDTIME)
        mainWin.dbInfo['totaltime'] = str(duration)
        
        time.sleep(3)
        printRes(res_str)
        printRes('TestCase : Total ' + str(TESTNUM) + '\n           Pass  ' + str(
            TESTNUM - failnum) + '\n           Fail  ' + str(failnum))
        if failnum > 0:
            printstr = ''
            printResWarn('Failed TestCase :')
            for j in FAILLIST:
                printstr += str(j) + '\n'
            printResWarn(printstr)
    elif (switch == 'Rerunend') or (switch == 'RerunEnd'):
        TESTNUM = tempTESTNUM
        TOTALTESTNUM = tempTOTALTESTNUM
        RERUNENDTIME = thistime
        TOTALFAILLIST.extend(FAILLIST)
        printRes('TOTALFAILLIST={}'.format(TOTALFAILLIST))
        duration = timediff(RERUNSTARTTEME, RERUNENDTIME)
        res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration)
        printAll(res)
        res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str(
            RERUNSTARTTEME) + '\n' + 'End Time   :' + str(RERUNENDTIME) + '\n' + 'Duration Time :' + str(duration)
        failnum = len(FAILLIST)
        printAll(res_str)
        printAll('TestCase : Total ' + str(RERUNTESTNUM) + '\n           Pass  ' + str(
            RERUNTESTNUM - failnum) + '\n           Fail  ' + str(failnum))
        if failnum > 0:
            printstr = ''
            printAll('Failed TestCase :')
            for j in FAILLIST:
                printstr += str(j) + '\n'
            printAll(printstr)
        duration = timediff(STARTTIME, RERUNENDTIME)
        res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration)
        printAll(res)
        res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str(STARTTIME) + '\n' + 'End Time   :' + str(
            RERUNENDTIME) + '\n' + 'Duration Time :' + str(duration)
        printAll(res_str)
        printAll('TestCase : Total ' + str(TESTNUM) + '\n           Pass  ' + str(
            TESTNUM - failnum) + '\n           Fail  ' + str(failnum))
        if failnum > 0:
            printstr = ''
            printAll('Failed TestCase :')
            for j in FAILLIST:
                printstr += str(j) + '\n'
            printAll(printstr)
        printAll('')
        mainWin.dbInfo['totalcases'] = str(TESTNUM)
        mainWin.dbInfo['passed'] = str(TESTNUM - failnum)
        mainWin.dbInfo['failed'] = str(failnum)
        mainWin.dbInfo['knownbugs'] = 'Not available'
        mainWin.dbInfo['unknowbugs'] = 'Not available'
        mainWin.dbInfo['failsummary'] = str(FAILLIST)
        mainWin.dbInfo['suggestions'] = 'Not available'
        mainWin.dbInfo['starttime'] = str(STARTTIME)
        mainWin.dbInfo['stoptime'] = str(ENDTIME)
        mainWin.dbInfo['totaltime'] = str(duration)
        time.sleep(3)
        printRes(res_str)
        printRes('TestCase : Total ' + str(TESTNUM) + '\n           Pass  ' + str(
            TESTNUM - failnum) + '\n           Fail  ' + str(failnum))
        if failnum > 0:
            printstr = ''
            printResWarn('Failed TestCase :')
            for j in FAILLIST:
                printstr += str(j) + '\n'
            printResWarn(printstr)
    elif switch == 'TlEnd':
        if mainWin.logger:
            mainWin.logger = close_logger(mainWin.logger)
        mainWin.logger = DcnLog(log_base_path=mainWin.log_base_path,
                                log_define_type='run',
                                prefix_log_name=logprefix,
                                console_name='summary',
                                test_name=TESTNAME).create_log()  # 创建一个汇总结果的日志文件summary
        printRes('TOTALFAILLIST{}'.format(TOTALFAILLIST))
        TOTALENDTIME = thistime
        duration = timediff(TOTALSTARTTIME, TOTALENDTIME)
        res = printFormat(title + ' ' + switch + ' ' + str(thistime), 'TestCase Duration Time:' + duration)
        printAll(res)
        res_str = 'AutoTest Name :' + TESTNAME + '\n' + 'Start Time :' + str(
            TOTALSTARTTIME) + '\n' + 'End Time   :' + str(TOTALENDTIME) + '\n' + 'Duration Time :' + str(duration)
        failnum = len(TOTALFAILLIST)
        printAll(res_str)
        printAll('TestCase : Total ' + str(TOTALTESTNUM) + '\n           Pass  ' + str(
            TOTALTESTNUM - failnum) + '\n           Fail  ' + str(failnum))
        if failnum > 0:
            printstr = ''
            printAll('Failed TestCase :')
            for j in TOTALFAILLIST:
                printstr += str(j) + '\n'
            printAll(printstr)
        DcnCommonFtp(ftp_config=mainWin.ftp_config_file).upload(
            mainWin.logfiles)  # 日志上传到用户指定服务器,指定服务器配置在config/ftpconfig.json
        try:
            if 'job_id' in affirm_tl_operate.tl.__args__ and mainWin.logger and mainWin.logfiles:
                printResDebug('\ntestlink args are:\n{arg}'.format(
                    arg=json.dumps(affirm_tl_operate.tl.__args__, ensure_ascii=False,
                                   indent=4, sort_keys=True)))
                DcnTestlinkFtp(affirm_tl_operate.tl.__args__, ip=mainWin.ftp_server_ip).upload(
                    mainWin.logfiles)  # 日志上传到testlink ftp服务器
                recover_args()  # testlink/args.py文件恢复初始状态
                affirm_tl_operate.set_waffirm_end()  # 关闭确认测试平台窗口
        except Exception as ex:
            printResError('error %s' % ex)
        TOTALTESTNUM = 0
        TOTALFAILLIST = []