Example #1
0
 def _receive_response(self):
     """
         接收数据
     :return:
     """
     length_buffer = self.get_socket.recv(4)
     if length_buffer:
         total = struct.unpack_from("i", length_buffer)[0]
     else:
         raise Exception('receive length is None?')
     view = memoryview(bytearray(total))
     next_offset = 0
     while total - next_offset > 0:
         receive_size = self.get_socket.recv_into(view[next_offset:],
                                                  total - next_offset)
         next_offset += receive_size
     try:
         deserialized = json.loads(view.tobytes())
         get_logger().info("receive response : %s" % deserialized)
     except (TypeError, ValueError):
         raise Exception('Data received was not in JSON format')
     if deserialized['ResponseStatus'] != 0:
         raise Exception("ResponseStatus: " +
                         str(deserialized['ResponseStatus']) + ", Obj: " +
                         str(deserialized['Obj']))
     return deserialized['Obj']
Example #2
0
    def unittest(self, modules):
        """
            运行用例
            :return:
        """
        module = modules.split(",")
        if module is not None and module != "":
            get_logger().info("unittest module %s" % module)
            suite = unittest.TestLoader().loadTestsFromNames(module)
        else:
            module = self._get_modules()
            get_logger().info("unittest modules %s" % module)
            suite = unittest.TestLoader().loadTestsFromNames(module)

        # insert_task(module)
        html_name = time.strftime("%Y-%m-%d_%H-%M-%S.html", self.timeReport)
        self._html_report(suite, html_name)

        dirname = html_name.split(".")[0]
        if os.environ[Environment.isTransSTAF] == "Y":
            for i in range(5):
                try:
                    self.staf_action.CopyDir(path=os.path.dirname(
                        os.path.dirname(self.staf_action.current_directory()))
                                             + "\\report",
                                             name=dirname)
                    break
                except:
                    print "传递数据到服务端失败%d次" % (i + 1)
            # Staf_Action.CloseHandle()
            print "********************************结束*****************************"
 def __cmd_timer(self, cmd, timer=10):
     """
         调用进程发送adb命令
     :param cmd: 命令
     :param timer: 超时时间
     :return:
     """
     get_logger().info(cmd)
     return self.runProcess.create_process_wait_timer(cmd, timer=timer)
Example #4
0
 def imageIsExist(self,
                  pngModelNum,
                  x=1680,
                  y=1050,
                  Accurate=0.5):  #判断图片是否存在,返回boolean,并复制图片
     try:
         return self.imageAll(pngModelNum, x, y, Accurate)[0]
     except Exception, e:
         get_logger().info("%s-PC_UI.UI.imageIsExist:%s" %
                           (self.scriptName, str(e)))
Example #5
0
 def showMyWindow(self, hWnd, t=1):
     try:
         win32gui.ShowWindow(hWnd, win32con.SW_NORMAL)
         shell = win32com.client.Dispatch("WScript.Shell")
         shell.SendKeys('%')
         win32gui.SetForegroundWindow(hWnd)
         time.sleep(t)
     except Exception, e:
         get_logger().info("%s-PC_UI.UI.showMyWindow:%s" %
                           (self.scriptName, str(e)))
Example #6
0
 def addSuccess(self, test):
     self.success_count += 1
     TestResult.addSuccess(self, test)
     output = self.complete_output()
     st = self.spendTime()
     self.result.append((0, test, output, '', st))
     if self.verbosity > 1:
         get_logger().info("%s ... ok" % str(test))
     else:
         sys.stderr.write('.')
Example #7
0
 def addError(self, test, err):
     self.error_count += 1
     TestResult.addError(self, test, err)
     _, _exc_str = self.errors[-1]
     output = self.complete_output()
     st = self.spendTime()
     # print "errortest:", test, "output:", output, "_exc_str:", _exc_str, "str:", str
     self.result.append((2, test, output, _exc_str, st))
     if self.verbosity > 1:
         get_logger().info("%s ...Error" % str(test))
     else:
         sys.stderr.write('E')
Example #8
0
 def addFailure(self, test, err):
     self.failure_count += 1
     TestResult.addFailure(self, test, err)
     _, _exc_str = self.failures[-1]
     output = self.complete_output()
     st = self.spendTime()
     # print "failuretest:", test, "output:", output, "_exc_str:", _exc_str, "str:", str
     self.result.append((1, test, output, _exc_str, st))
     if self.verbosity > 1:
         get_logger().info("%s ... Failure" % str(test))
     else:
         sys.stderr.write('F')
Example #9
0
 def getHandle(self, name):
     try:
         self.titles = []
         self.handle = []
         myhwnd = []
         win32gui.EnumWindows(self.callback, None)
         for i, v in enumerate(self.titles):
             if name.decode("utf-8").encode("gbk") in v:
                 myhwnd.append(self.handle[i])
         return myhwnd
     except Exception, e:
         get_logger().info("PC_UI.UI.getHandle:%s" % str(e))
Example #10
0
 def connect(self):
     get_logger().info("connect host : %s ,port : %d" %
                       (self.__host, self.__port))
     for i in xrange(5):
         get_logger().info("try to connect server : %d" % i)
         self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
         self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         value = self.__socket.connect_ex((self.__host, self.__port))
         if value == 0:
             return
         time.sleep(1)
     raise Exception("socket error")
Example #11
0
 def imagePos(self, pngModelNum, x=1680, y=1050, Accurate=0.5):  #获取图片中心坐标
     try:
         imagematch, imagex, imagey = self.imageAll(pngModelNum, x, y,
                                                    Accurate)
         if imagematch == True:
             return imagex, imagey
         else:
             #print "%s %s.png not find element"%(self.scriptPath,self.pngNum)
             get_logger().info("%s %s.png not find element" %
                               (self.scriptPath, self.pngNum))
             sys.exit()
     except Exception, e:
         get_logger().info("%s-PC_UI.UI.imageIsExist:%s" %
                           (self.scriptName, str(e)))
 def addSuccess(self, test):
     self.success_count += 1
     TestResult.addSuccess(self, test)
     output = self.complete_output()
     use_time = round(self.test_end_time - self.test_start_time, 2)
     self.result.append((0, test, output, '', use_time))
     if self.verbosity > 1:
         get_logger().info("%s ... ok" % str(test))
         sys.stderr.write('  S  ')
         sys.stderr.write(str(test))
         sys.stderr.write('\n')
     else:
         sys.stderr.write('  S  ')
         sys.stderr.write('\n')
Example #13
0
 def findClient(self, pngModelNum, myAccurate=0.5, t=1.0, processname='魔域'):
     try:
         hand = []
         hand = self.getHandle(processname)
         for i in hand:
             self.showMyWindow(i)
             time.sleep(1.0)
             match, x, y = self.imageAll(pngModelNum, Accurate=myAccurate)
             if match:
                 self.mouse_click(x, y)
                 break
         time.sleep(t)
     except Exception, e:
         get_logger().info("%s-PC_UI.UI.findClient:%s" %
                           (self.scriptName, str(e)))
Example #14
0
 def getMyhwndByName(self,
                     processname='【魔域】'
                     ):  #获取所有应用名字对应的获取窗口句柄列表,该句柄列表是通过时间排序的
     try:
         hwnd = self.getHandle(processname)
         ph = {}
         hw = []
         for h in hwnd:
             hreadID, pid = win32process.GetWindowThreadProcessId(h)
             ph[Process().getProCreatTime(pid)] = h
         for v in sorted(ph.keys()):  #字典按进城时间排序  返回对应的值列表
             hw.append(ph[v])
         return hw
     except Exception as e:
         get_logger().info("PC_UI.UI.GetMyhwndByName:%s" % str(e))
    def addFailure(self, test, err):
        self.failure_count += 1
        TestResult.addFailure(self, test, err)
        _, _exc_str = self.failures[-1]
        output = self.complete_output()
        use_time = round(self.test_end_time - self.test_start_time, 2)
        self.result.append((1, test, output, _exc_str, use_time))
        if self.verbosity > 1:
            get_logger().info("%s ... Failure" % str(test))
            sys.stderr.write('  F  ')
            sys.stderr.write(str(test))
            sys.stderr.write('\n')
        else:
            sys.stderr.write('  F  ')
            sys.stderr.write('\n')

        # 添加收集失败用例名字 -- Gelomen
        self.failCase += "<li>" + str(test) + "</li>"
Example #16
0
    def _send_request(self, data):
        """
            发送数据
        :param data:
        :return:
        """
        try:
            serialized = json.dumps(data, ensure_ascii=False)
            # print "serialized", serialized
        except (TypeError, ValueError):
            raise Exception('You can only send JSON-serializable data')

        length = len(serialized)
        buff = struct.pack("i", length)
        self.get_socket.send(buff)
        get_logger().info("send cmd : %s" % serialized)
        send_size = self.get_socket.send(serialized)
        if length != send_size:
            raise Exception("send size error:length=%d , send_size=%d" %
                            (length, send_size))
Example #17
0
 def imageAll(self,
              pngModelNum,
              x=1680,
              y=1050,
              Accurate=0.5):  #输出图片的math,x,y
     try:
         self.pngNum += 1
         self.screenCap(self.pngNum)
         dict = ImageRecognize.proxy(
             self.modelInagePath(self.scriptName + os.sep +
                                 "%s.png" % pngModelNum),
             self.tempImagePath("%s.png" % self.pngNum),
             Path.resultImagePath(self.scriptName, "%s.png" % self.pngNum),
             srcX=x,
             srcY=y,
             defaultAccurate=Accurate)
         return dict["match"], dict["maxLocX"], dict["maxLocY"]
     except Exception, e:
         get_logger().info("%s-PC_UI.UI.imageAll:%s-%s" %
                           (self.scriptName, str(e), pngModelNum))
Example #18
0
 def send_command(self, cmd, params=None, timeout=30):
     """
         发送命令
     :param cmd:
     :param params:
     :param timeout:
     :return:
     """
     if params and not (isinstance(params, dict) or isinstance(
             params, list) or isinstance(params, str)
                        or isinstance(params, unicode)):
         raise Exception('Params should be dict')
     if not params:
         params = ""
     mutex.acquire(10)  # 可以加等待时间,不加就一直等待(堵塞)
     command = dict()
     command["Cmd"] = cmd
     command["Json"] = str(params)
     try:
         for retry in range(2):
             try:
                 self.get_socket.settimeout(timeout)
                 self._send_request(command)
                 return self._receive_response()
             except socket.timeout:
                 self.shutdown()
                 time.sleep(10)
                 self.connect()
                 raise Exception("Received Data From SDK timeout")
             except socket.error as e:
                 get_logger().info("Retry...%d" % e.errno)
                 self.shutdown()
                 time.sleep(10)
                 self.connect()
                 continue
             except Exception as e:
                 raise e
         raise Exception('Socket Error')
     finally:
         mutex.release()
Example #19
0
 def getReportAttributes(self, result):
     """
     Return report attributes as a list of (name, value).
     Override this to add custom attributes.
     """
     startTime = str(self.startTime)[:19]
     duration = str(self.stopTime - self.startTime)
     status = []
     if result.success_count:
         status.append('Pass %s' % result.success_count)
     if result.failure_count:
         status.append('Failure %s' % result.failure_count)
     if result.error_count: status.append('Error %s' % result.error_count)
     if status:
         status = ' '.join(status)
     else:
         status = 'none'
     get_logger().info("Start Time: %s" % startTime)
     get_logger().info("Duration: %s" % duration)
     get_logger().info("Status: %s" % status)
     return [
         ('Start Time', startTime),
         ('Duration', duration),
         ('Status', status),
     ]
    def open_process(self):
        """
            打开应用
        :return:
        """
        try:

            os.system(SourcePath.File_3DPPT_Kill)
        except:
            pass
            raise Exception(u"关闭应用失败")  # 开始运行前先排除上一次运行未杀进程情况
        time.sleep(5)
        if not os.path.exists(self.path):
            get_logger().error("open_process Error not such file:%s" %
                               self.path)
            return False
        get_logger().info("open_test_application : %s " % self.path)
        try:
            self.process = win32process.CreateProcess(
                self.path, '', None, None, 0, win32process.CREATE_NO_WINDOW,
                None, None, win32process.STARTUPINFO())
            time.sleep(1)
            self.set_foreground_window()
            self.set_window_max()
            return True
        except Exception, e:

            get_logger().error("open_process Error  " + str(e.message))

            return False
    def close_process(self):
        """
            关闭应用
        :return:
        """
        get_logger().info("close_test_application : %s " % self.path)
        self.hwnd = None
        if self.process:
            try:
                win32process.TerminateProcess(self.process[0], 0)
                self.process = None
            except:
                try:

                    os.system(SourcePath.File_3DPPT_Kill)
                except:
                    pass
                raise Exception(u"关闭应用失败")
        else:
            try:
                os.system(SourcePath.File_3DPPT_Kill)
            except:
                pass
Example #22
0
 def printScreen(self, file, resultPath=False, x=1680, y=1050):
     try:
         if resultPath == True:  #在image下的脚本文件夹
             path = Path.resultImagePath(self.scriptName, "%s.png" % file)
         elif resultPath == False:  #默认在case下的temp
             path = self.tempImagePath("%s.png" % file)
         else:
             path = resultPath
         self.key_event('print_screen')
         im = ImageGrab.grabclipboard()
         n = 15
         while (n >= 0):
             if im != None:
                 break
             else:
                 self.key_event('print_screen')
                 im = ImageGrab.grabclipboard()
                 n = n - 1
                 time.sleep(1)
         region = im.crop((0, 0, x, y))  #裁剪图片
         region.save(path)
     except Exception, e:
         get_logger().info("PC_UI.UI.printScreen:%s" % str(e))
Example #23
0
 def proxy(templatePath,
           sourcePath,
           targetPath,
           srcX,
           srcY,
           orientation=0,
           defaultAccurate=0.5,
           isDel=False):
     """
     判断给定的小图片在大图片中存在的概率(圈出一个)
     :param templatePath: 小图片
     :param sourcePath: 大图片
     :param targetPath: 在大图片中圈出小图片
     :param srcX: 当前分辨率X
     :param srcY: 当前分辨率Y
     :param orientation: 方向  1—》旋转90, 0-》不变
     :param defaultAccurate: 相似度
     :return:
     """
     target_x, target_y = ImageRecognize.__unite_resolution(
         sourcePath, srcX, srcY, orientation)
     template_x, template_y = ImageRecognize.__unite_resolution_template(
         templatePath, srcX, srcY, orientation)
     result = ImageRecognize.__image_comparison(templatePath, sourcePath,
                                                targetPath, defaultAccurate)
     try:
         if isDel == True:
             delete_file(sourcePath)
         else:
             if result["match"] == False:
                 print "删除"
                 print delete_file(sourcePath)
     except Exception, e:
         print "删除图片失败", str(e)
         get_logger().info("%s-imgPair:%s-%s" %
                           ("删除匹配不成功图片失败", str(e), sourcePath))
Example #24
0
 def screenCap(self, file, resultPath=False, x=1680, y=1050):  #截屏
     try:
         self.printScreen(file, resultPath, x, y)
     except Exception, e:
         get_logger().info("PC_UI.UI.screenCap:%s" % str(e))