Esempio n. 1
0
    def initProcess(self):
        global win, browser
        # 初始化全局变量
        cf._init()
        path = os.getcwd()
        cf.set_value("path", path)

        win = tk.Tk()
        # win.geometry("300x150+500+200")  # 大小和位置
        win.title("请确认")
        ttk.Label(win, text="请选择浏览器类型:").grid(column=1,
                                              row=0)  # 添加一个标签,并将其列设置为1,行设置为0

        # 按钮
        action = ttk.Button(win, text="选择", command=self.clickMe)
        action.grid(column=2, row=1)

        # 创建一个下拉列表
        browser = tk.StringVar()
        browserChosen = ttk.Combobox(win, width=12, textvariable=browser)
        browserChosen['values'] = ("", "Chrome", "IE", "Firefox", "Windows")
        browserChosen.grid(column=1, row=1)
        # 设置下拉列表默认显示的值,0为 numberChosen['values'] 的下标值
        browserChosen.current(0)
        # 当调用mainloop()时,窗口才会显示出来
        win.mainloop()
Esempio n. 2
0
def handleErr(err):
    ''' 处理报错信息并写入日志文件
    :param err: 报错信息
    '''
    err = "[报错文件] %s\n[错误行] %s" \
              %(err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
    # auto.Logger.WriteLine(err, auto.ConsoleColor.Cyan, writeToFile = True)
    cf.set_value("err", err)
Esempio n. 3
0
    def __resolve_filename(cls, get_local_filename_func, script_name, default_directory):
            """ Retourne le chemin absolu du script d'après son nom.
            Suit ce pseudo-code :
                Le nom du script est-il absolu ?
                ✓ Oui
                    Le script est celui définit.
                x Non
                    Le script est-il présent dans le dossier du fichier *.json ?
                    ✓ Oui
                        Le script est le script local.
                    x Non
                        Le script est un script par défaut

            En cas d'erreur, une ScriptNotFoundError est levée contenant le nom du script introuvable.
            """
            ex = ScriptNotFoundError()
            script_path = None
            if script_name.startswith("/") or script_name.startswith("\\") :
                # Nom de script absolu
                try:
                    script_path = Globals.user_abs_path() + os.sep + script_name
                    with open(script_path, "r"):
                        return os.path.abspath(script_path)
                except IOError as e:
                    # Le fichier n'existe pas, ou n'est pas disponible en lecture.
                    ex.add_message("Exception Message", e)
                    ex.add_message("Script Mode", "Absolute Script")
                    ex.add_message("Filename", script_path)
                    raise ex

            try:
                # Le script dans le dossier courant
                script_path = get_local_filename_func(script_name)
                with open(script_path, "r"):
                    return os.path.abspath(script_path)
            except IOError as e:
                ex.add_title("", "=")
                ex.add_message("Exception Message", e)
                ex.add_message("Script Filename", script_path)
                ex.add_title("Relative Script Lookup", "=")
                pass # il s'agit peut-être d'un script par défaut

            try:
                script_path = Globals.user_abs_path() + default_directory + os.sep + script_name
                with open(script_path, "r"):
                    return os.path.abspath(script_path)
            except IOError as e:
                ex.add_title("", "=")
                ex.add_message("Exception Message", e)
                ex.add_message("Script Filename", script_path)
                ex.add_title("Default Script Lookup", "=")
                raise ex
Esempio n. 4
0
    def wrapper(*args, **kwargs):
        try:
            try:
                funcStr = "[%s %s] 执行语句 %s(" % (
                    getCurrentDate(), getCurrentTime(), func.__name__)
                if args:
                    for count, string in enumerate(args):
                        if count == 0:
                            continue
                        if count == 1:
                            funcStr += "'%s'" % string if isinstance(
                                string, str) else "%s" % str(string)
                        else:
                            funcStr += ", '%s'" % string if isinstance(
                                string, str) else ", %s" % str(string)
                if kwargs:
                    for key in kwargs.keys():
                        addStr = ", %s='%s'" % (key, kwargs[key])
                        funcStr += addStr
                funcStr += ")"
                auto.Logger.WriteLine(funcStr)

                return func(*args, **kwargs)
            except Exception as e:
                if "projectName" in cf._global_dict.keys():
                    projectName = cf.get_value("projectName")
                    # picPath = os.path.dirname(os.path.dirname(os.path.abspath(_ _file__))) \
                    #           + "\\pictures\\%s" %projectName
                    picPath = "%s\\pictures\\%s" \
                              %(frozen_dir.app_path(), projectName)

                    dirName = createCurrentDateDir(picPath)
                    capture_screen(dirName)

                    # err = "\n[错误行] %s\n[报错文件] %s\n[错误信息] %s\n" \
                    #       % (e.__traceback__.tb_lineno,
                    #          e.__traceback__.tb_frame.f_globals["__file__"], e)
                    # auto.Logger.WriteLine(err, auto.ConsoleColor.Cyan, writeToFile=True)

                funcName = func.__name__
                err = cf.get_value("err")
                if projectName:
                    errInfo = "\n[工程名称] %s\n%s\n[关键字] %s\n[异常信息] %s\n" \
                              %(projectName, err, funcName, repr(e))
                else:
                    errInfo = "\n%s\n[关键字] %s\n[异常信息] %s" \
                              %(err, funcName, repr(e))
                auto.Logger.WriteLine(errInfo)
                raise CNBMError(errInfo)
        except CNBMError as err:
            raise err
def clean_workspace():
    """ Supprime les fichier de compilation et les fichiers __init__.py du domaine utilisateur.
    """
     # Suppression de tous les pyc à la fin, pour ne pas pertuber l'utilisateur.
    for root, subFolders, files in os.walk(Globals.user_abs_simulation()):
        for f in files:
            infos = os.path.splitext(f)
            if infos[1] != ".pyc":
                continue
            os.remove(os.path.join(root, f))

    # Supression des fichier __init__
    for root, subFolders, files in os.walk(os.path.join(Globals.user_abs_simulation())):
        for f in files:
            infos = os.path.splitext(f)
            if infos[0] != "__init__":
                continue
            os.remove(os.path.join(root, f))
Esempio n. 6
0
    def __init__(self):
        self.chrome_driver = path
        self.chrome_options = Options()
        self.chrome_options.add_experimental_option("debuggerAddress",
                                                    "127.0.0.1:9222")

        self.driver = webdriver.Chrome(self.chrome_driver,
                                       chrome_options=self.chrome_options)

        try:
            cf._global_dict
        except:
            # checkFunc中调用时,此前未定义 cf._global_dict
            cf._init()
        cf.set_value("driver", self.driver)
        print("[title] ", self.driver.title)

        self.page_source = self.driver.page_source
        self.url = self.driver.current_url
    def test_get_entity_names(self):
        """ TestBuilder Récupérer les noms des entités"""

        b = Builder()
        for entityName in b._get_entity_names():
            path = os.path.join(Globals.user_abs_entity_path(entityName),
                                "attributes.json")
            assert os.path.exists(path)
        assert Builder._get_entity_names()[0] == "Moustique", \
                "Builder._get_entity_names()[0] = {}".format(Builder._get_entity_names()[0])
        assert Builder._get_entity_names()[1] == "Humain", \
                "Builder._get_entity_names()[1] = {}".format(Builder._get_entity_names()[1])
Esempio n. 8
0
    def startHook(self):
        ''' 开始录制流程 '''
        import hooker.Hook as H
        self.initProcess()
        autoType = cf.get_value("autoType")
        print("本次录制类型:", autoType)
        cf.set_value("autoType", autoType)

        if autoType == "Windows":
            HK = H.Hooker()
            HK.hooks()
        elif autoType == "IE":
            IEXPath = parentDirPath + r"\tools\IEXPath.exe"
            win32api.ShellExecute(0, 'open', IEXPath, '', '', 1)

            HK = H.Hooker()
            HK.hooks()
        elif autoType == "Chrome" or autoType == "Firefox":
            Init().hooks()
            from hooker.Extension import run
            run()
        else:
            pass
Esempio n. 9
0
def handler():
    global request_counter
    # print("recv data = {}".format(str(request.json)))
    # print(request.form.get('expression'))
    expression = request.json.get('expression')
    print("xpath:", expression)

    isRecord = recordIntoProject(expression)
    if isRecord:
        fp = open(hookLogPath, "a", encoding='utf-8')
        fp.write('\n-----')
        fp.write('\n' + '[捕获时间] %s' % getCurrentTime(date=True))
        fp.write('\n' + '[捕获对象类型] %s' % cf.get_value("autoType"))
        fp.write('\n' + '[层级结构]' + '\n')
        fp.write(expression)

    response = make_response(
        jsonify({'error': 0, 'msg': 'success', 'data': {'counter': request_counter, 'request': request.json}}))
    # print(response._status_code)
    return response
Esempio n. 10
0
 def _get_entity_filename(self, filename):
     """ Donne le chemin pour un fichier situé dans le dossier de l'entité
     actuellement parsée.
     """
     return os.path.abspath(Globals.user_abs_entity_path(self.entity_name) + os.sep +  filename)
Esempio n. 11
0
 def __init__(self):
     self.pause = False
     self.flag = False
     self.autoType = cf.get_value("autoType")
Esempio n. 12
0
 def clickMe(self):
     # button被点击之后会被执行
     global autoType
     win.destroy()
     autoType = browser.get()
     cf.set_value("autoType", autoType)
Esempio n. 13
0
def recordIntoProject(eleProperties):
    ''' 点击目标控件(IE)后,判断是否保存到本地库,并定义控件名称(不做唯一性校验)
    :param eleProperties: 目标控件所有信息
    :return: True:成功获取并保存/False:不保存
    '''
    import tkinter.messagebox as msg
    import win32api, win32con
    import easygui

    try:
        autoType = cf.get_value("autoType")
        if autoType == "IE":
            # IE类型控件
            keyObj = eleProperties.get("Depth")
            info = keyObj[str(len(keyObj) - 1)]
            # print(info)
            copyInfo = info["Name"]
        elif autoType == "Windows":
            keyObj = eleProperties.get("Depth")
            info = keyObj[str(len(keyObj) - 1)]
            # print(info)
            copyInfo = {
                "AutomationId": info["AutomationId"],
                "ClassName": info["ClassName"],
                "ControlType": info["ControlType"],
                "Depth": info["Depth"],
                "Name": info["Name"],
            }
        else:
            # chrome或firefox类型控件
            copyInfo = eleProperties

        message = "是否添加控件:\n" + str(copyInfo)
        # result = easygui.boolbox(msg=message, title='提示', choices=('是', '否'), image=None)                # rasygui,可用
        result = win32api.MessageBox(0, message, "提示",
                                     win32con.MB_OKCANCEL)  # pywin32,可用
        # result = message_askyesno("提示", message)                                                        # tk下总会有空白/多余弹框,且易卡顿,不可用
        # print(result)

        path = cf.get_value("path")
        if result == 1:
            if autoType == "Windows":
                # windows控件保存前脚本进行唯一性校验
                # (True:可直接保存;False:人工进行index判断)
                AC = AppControl()
                flag = AC.checkBottom(keyObj,
                                      True)  # TODO:根据判断识别出结果但应用程序实际不可识别处理方法
                if not flag:
                    # win32api.MessageBox(0, "依据获取信息无法识别控件,请检查控件状态!", "提示", win32con.MB_OK)
                    # rasygui,可用
                    confirmMsg = "请检查控件当前状态,并确认是否继续保存?"
                    confirm = win32api.MessageBox(0, confirmMsg, "请确认",
                                                  win32con.MB_OKCANCEL)
                    if confirm != 1:
                        return False

            # 点击后保存
            filePath = path + r"\log.txt"
            # print(filePath)
            with open(filePath, "a+"):
                pass
            with open(filePath, "r+") as f:
                rawData = f.read()
                if not rawData:
                    rawData = "{'%s': {}}" % autoType
                rawDict = eval(rawData)

                # objName = input("定义控件名称为:")
                objName = getInput("请确认", "请定义控件名称:")
                if objName is None:
                    # 点击后不保存,默认继续识别
                    return False

                if autoType not in rawDict:
                    rawDict[autoType] = dict()
                rawDict[autoType][objName] = dict()
                if autoType == "IE":
                    rawDict[autoType][objName]["xpath"] = copyInfo
                    rawDict[autoType][objName]["Starts"] = eleProperties[
                        "Starts"]
                    rawDict[autoType][objName]["Ends"] = eleProperties["Ends"]
                elif autoType == "Windows":
                    rawDict[autoType][objName] = eleProperties
                else:
                    # chrome/firefox
                    rawDict[autoType][objName]["xpath"] = copyInfo
                    rawDict[autoType][objName]["time"] = "%s %s" % (
                        getCurrentDate(), getCurrentTime())
                # print(rawDict)
            with open(filePath, "w") as f:
                f.write(str(rawDict))
                # f.close()
            return True
        else:
            # 点击后不保存,默认继续识别
            return False
    except Exception as e:
        raise e
Esempio n. 14
0
# _*_ coding:utf-8 _*_
from hooker import *
from config.GUIdesign import *
from localSDK.BasicFunc import *
import subprocess
import config.Globals as cf

autoType = cf.get_value("autoType")


def myPopen(cmd):
    ''' 执行命令cmd '''
    try:
        # popen = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        popen.wait()
        lines = popen.stdout.readlines()
        # print(["lines"], type(lines), "\n", lines)

        dt = compileData(lines)
        return dt

        # return [line.decode('UTF-8') for line in lines]
        # for line in lines:
        #     print(line.decode("UTF-8"))
    except BaseException as e:
        # return -1
        return e
    except Exception as e:
        raise e
Esempio n. 15
0
from config.DirAndTime import *
import config.Globals as cf
import uiautomation as auto
import frozen_dir

auto.uiautomation.DEBUG_EXIST_DISAPPEAR = True
auto.uiautomation.DEBUG_SEARCH_TIME = True
auto.uiautomation.TIME_OUT_SECOND = 10

# dateDir = createCurrentDateDir("%s\log" %parentDirPath)
dateDir = createCurrentDateDir("%s\log" % frozen_dir.app_path())
auto.Logger.SetLogFile("%s\ExecuteLog.txt" % dateDir)
# print(dateDir)

# 保存全局变量”工程名“,并写入日志
cf._init()
projectName = os.getcwd().split("\\")[-1]
cf.set_value("projectName", projectName)
auto.Logger.WriteLine("-----\n[%s %s] 开始执行工程 '%s'" %
                      (getCurrentDate(), getCurrentTime(), projectName))
# 读取工程下日志文件
PF = PublicFunc()
logDict = PF.readFromLog()

browser = PageAction()
win = AppControl()
key = KeyboardKeys()
win.dict = logDict
excel = ParseExcel()

# ---------- 以上为公共流程 ----------
def build_workspace():
    """ Crée un fichier __init__.py dans tous les dossiers d'entités
    afin de rendre les scripts locaux importable"""
    for root, dirs, filenames in os.walk(Globals.user_abs_simulation()):
        with open(os.path.join(root, "__init__.py"), "w"):
            pass