def __uploadproject(self, file): temp_file = os.path.join(self.app.config['AUTO_TEMP'], file.filename) os.remove(temp_file) if os.path.exists(temp_file) else None file.save(temp_file) (_, f_ext) = os.path.splitext(temp_file) if f_ext == '.zip': path = os.path.join(self.app.config['AUTO_TEMP'], 'unzipfile') (status, info) = do_unzip_project(temp_file, path) if status == 'success': projectname = get_projectnamefromkey(info) msg = self.app.config['DB'].load_project_from_path(info) result = { "status": "success", "msg": "Result: {} project:{}".format(msg, projectname) } self.app.config['DB'].insert_loginfo(session['username'], 'project', 'upload_project', info, result['status']) else: result = {"status": "fail", "msg": info} self.app.config['DB'].insert_loginfo(session['username'], 'project', 'upload_project', info, result['status']) return result
def generate_high_light(doc_dir): ''' This is new fun, Invoked by project.get ,then loaded in editor.html. ''' log.info("生成高亮显示 js ...") project = get_projectnamefromkey(doc_dir) kwd = os.getcwd() + "/keyword/" + project jsd = os.getcwd() + "/auto/www/static/js/" + project if not os.path.exists(jsd): mk_dirs(jsd) if not os.path.exists(kwd): mk_dirs(kwd) ff = codecs.open(jsd + "/highlight.js", "w", "utf-8") keyword_list = [] keys = os.listdir(kwd) for k in keys: if not k.endswith('.xml'): continue path = kwd + "/" + k tree = ET.parse(path) root = tree.getroot() name = root.attrib["name"] for kw in root.iter("kw"): # 关键字 keyword_list.append("'" + kw.attrib["name"] + "'") keyword_list = list(set(keyword_list)) keyword_list.sort(key=len, reverse=True) keywords = "var high_light=" + "[" + ",".join(keyword_list) + "];" ff.write(keywords) ff.close()
def __downruninfo(self, args): # charis added : user_path = args["key"] project = get_projectnamefromkey(user_path) self.log.info("下载请求 runinfo:" + user_path) jobpath = self.app.config["AUTO_HOME"] + "/jobs" job_path = self.app.config["AUTO_HOME"] + "/jobs/%s/%s" % ( session['username'], project) for user in os.listdir(job_path): if os.path.isdir(user): for prj in os.listdir(user): if os.path.isdir(prj) and prj == project: for tasks in prj: if os.path.isdir(tasks): for f in tasks: if f.endswith('.xml'): suite = ExecutionResult(f).suite user_path = "/Users/tester/PycharmProjects/uniRobotDev/.beats/workspace/Admin/Demo_Project/RobotTestDemo/TestCase/01Template.robot" self.app.config['DB'].insert_loginfo(session['username'], 'runinfo', 'download', project) return self.__sendfile(user_path)
def get_robotcase_res(casefile): project = get_projectnamefromkey(casefile) projectdir = get_projectdirfromkey(casefile) os.environ["ROBOT_DIR"] = projectdir os.environ["PROJECT_DIR"] = projectdir cwd = os.getcwd() + "/keyword/" + project if not os.path.exists(cwd): mk_dirs(cwd) try: suite = TestSuiteBuilder().build(casefile) except SyntaxError as e: log.error("Exception:TestSuiteBuilder().build:{} {}".format( casefile, e)) return [] except Exception as e: log.error("Exception:TestSuiteBuilder().build:{} {}".format( casefile, e)) return [] resources = [] for i in suite.resource.imports: rsfile = i.name # Full path of file if rsfile.find("%{ROBOT_DIR}") != -1: rsfile = rsfile.replace("%{ROBOT_DIR}", projectdir) if rsfile.find("%{PROJECT_DIR}") != -1: rsfile = rsfile.replace("%{PROJECT_DIR}", projectdir) if rsfile.startswith('.'): dir = os.path.dirname(casefile) rsfile = os.path.join(dir, rsfile) basename = os.path.basename(rsfile) # Lib name without path fpre = basename.split('.')[ 0] # BuildIn or UserRes without '.resource' or '.robot' xmlfile = cwd + "/%s.xml" % fpre if not os.path.exists(rsfile) and (rsfile.find('/') != -1 or rsfile.find('.robot') != -1 or rsfile.find('.resource') != -1): log.error("找不到资源文件:{} !".format(rsfile)) continue if os.path.exists(rsfile): res = generate_resource_xml( rsfile, xmlfile) if not os.path.exists(xmlfile) else None resources.append(fpre) if os.path.exists(xmlfile) else log.error( "生成资源文件失败 XML:{},INFO:{}".format(xmlfile, res)) else: res = generate_resource_xml( fpre, xmlfile) if not os.path.exists(xmlfile) else None resources.append(fpre) if os.path.exists(xmlfile) else log.error( "生成资源文件失败 XML:{},INFO:{}".format(xmlfile, res)) if rsfile.endswith('.robot') or rsfile.endswith('.resource'): resources += get_robotress_res(rsfile) return resources
def robot_run(app, case_key, args='', user='', driver='USER'): username = user if user != '' else session['username'] project = get_projectnamefromkey(case_key) output = app.config["AUTO_HOME"] + "/jobs/%s/%s" % (username, project) if not exists_path(output): mk_dirs(output) (out, index) = reset_next_build_numb(output) mk_dirs(out) if not exists_path(out) else None cmd = 'robot ' + args + ' --outputdir=' + out + ' ' + case_key log.info("Robot_run CMD:{}".format(cmd)) with open(out + "/cmd.txt", 'w') as f: f.write("{}|robot|{}|--outputdir={}|{}\n".format( driver, args, out, case_key)) cp = subRun(cmd, shell=True, stdout=PIPE, stderr=STDOUT, text=True, timeout=7200) # timeout: sec 2hrs with open(out + "/debug.txt", 'w') as f: f.write(cp.stdout) app.config['DB'].insert_loginfo(username, 'task', 'run', case_key, 'OK') # Report and xUnit files can be generated based on the result object. # ResultWriter(result).write_results(report=out + '/report.html', log=out + '/log.html') try: detail_result = ExecutionResult(out + "/output.xml") except Exception as e: log.error( "Open output.xml Exception:{},\n May robot run fail, console:{}". format(e, cp.stdout)) return # detail_result.save(out + "/output_new.xml") reset_last_status(detail_result, output, index) # Report and xUnit files can be generated based on the result object. ResultWriter(detail_result).write_results(report=out + '/report.html', log=out + '/log.html') s = detail_result.suite dealwith_source(app, username, s)
def save_settings(self, project_path): project = get_projectnamefromkey(project_path) owner = self.app.config['DB'].get_projectowner(project) settingsfile = os.path.join(project_path, 'platforminterface/settings.conf') self.log.info("保存 settings 文件:{}".format(settingsfile)) with open(settingsfile, 'w') as f: f.write("#description#item#value#demo#category\n") res = self.app.config['DB'].runsql("select * from settings;") for i in res: f.write('#'.join(i) + '\n')
def prepare_editorjs(key): project = get_projectnamefromkey(key) jsd = os.getcwd() + "/auto/www/static/js/" + project desd = os.getcwd() + "/auto/www/static/js" copy_file(jsd + '/highlight.js', desd + '/highlight.js') if os.path.exists(jsd + '/highlight.js') else None copy_file( jsd + '/autocomplete.js', desd + '/autocomplete.js') if os.path.exists(jsd + '/autocomplete.js') else None
def save_project(self, project_path): project = get_projectnamefromkey(project_path) projectfile = os.path.join(project_path, 'platforminterface/project.conf') self.log.info("保存项目信息到文件:{}".format(projectfile)) with open(projectfile, 'w') as f: f.write("# projectname|owner|users|cron\n") res = self.app.config['DB'].runsql( "select * from project where projectname='{}';".format( project)) for i in res: (projectname, owner, users, cron) = i line = "{}|{}|{}|{}\n".format(projectname, owner, users, cron) self.log.info("保存项目信息:{}".format(line)) f.write(line)
def update_resource(path): '''when update,rename,delete resource file, xml file should be updated.''' if not path.endswith('.resource'): log.error("更新资源文件应该已resource为后缀: " + path) return project = get_projectnamefromkey(path) fname = os.path.basename(path).split('.')[0] kwd = os.getcwd() + "/keyword/" + project kwdfile = kwd + '/' + fname + '.xml' os.remove(kwdfile) if os.path.isfile(kwdfile) else None generate_resource_xml(path, kwdfile) generate_high_light(path) generate_auto_complete(path)
def save_user(self, project_path): project = get_projectnamefromkey(project_path) owner = self.app.config['DB'].get_projectowner(project) userfile = os.path.join(project_path, 'platforminterface/user.conf') self.log.info("保存用户信息到文件:{}".format(userfile)) with open(userfile, 'w') as f: f.write( "# username|fullname|passworkdHash|email|category|main_project\n" ) res = self.app.config['DB'].runsql( "select * from user where main_project='{}';".format(project)) for i in res: (username, fullname, passworkdHash, email, category, main_project) = i f.write("{}|{}|{}|{}|{}|{}\n".format(username, fullname, passworkdHash, email, category, main_project))
def clear_projectres(project, key=''): prj = project if not key == '': prj = get_projectnamefromkey(key) log.info("清除项目关键字:" + prj) cwd = os.getcwd() + "/keyword/" + prj try: remove_dir(cwd) except FileNotFoundError: log.warning("删除项目目录失败:" + cwd) jsd = os.getcwd() + "/auto/www/static/js/" + prj log.info("清除项目的js文件:" + prj) try: remove_dir(jsd) except FileNotFoundError: log.warning("删除项目目录失败:" + jsd)
def generate_auto_complete( doc_dir ): # This is new fun, Invoked by project.get ,then loaded in editor.html. log.info("生成自动完成 js ...") project = get_projectnamefromkey(doc_dir) kwd = os.getcwd() + "/keyword/" + project jsd = os.getcwd() + "/auto/www/static/js/" + project if not os.path.exists(jsd): mk_dirs(jsd) if not os.path.exists(kwd): mk_dirs(kwd) ff = codecs.open(jsd + "/autocomplete.js", "w", "utf-8") keyword_list = [] keys = os.listdir(kwd) for k in keys: if not k.endswith('.xml'): continue path = kwd + "/" + k tree = ET.parse(path) root = tree.getroot() name = root.attrib["name"] for kw in root.iter("kw"): # 关键字 word = "'" + kw.attrib["name"] # 关键字参数 for arg in kw.iter("arg"): word += "\t[" + arg.text.replace("'", "") + "]" word += "'" keyword_list.append(word) keyword_list = list(set(keyword_list)) keyword_list.sort(key=len, reverse=False) keyword_list = ROBOT_BUILTIN_KEYWORDS + keyword_list kewords = "var auto_complete=" + "[" + ",".join(keyword_list) + "];" ff.write(kewords) ff.close()
def __gitclone(self, args): url = args['name'] (ok, info) = remote_clone(self.app, url) if ok: projectname = get_projectnamefromkey(info) msg = self.app.config['DB'].load_project_from_path(info) result = { "status": "success", "msg": "Result: {} project:{}".format(msg, projectname) } self.app.config['DB'].insert_loginfo(session['username'], 'project', 'gitcreate', info, result['status']) else: result = {"status": "fail", "msg": info} self.app.config['DB'].insert_loginfo(session['username'], 'project', 'gitcreate', url, result['status']) return result
def __set_main(self, args): main_project = self.app.config['DB'].get_user_main_project( session['username']) owner = self.app.config['DB'].get_projectowner(main_project) if session['username'] == owner: return {"status": "Fail", "msg": "失败:项目管理员不能切换主项目."} #user_path = self.app.config["AUTO_HOME"] + "/workspace/%s/%s" % (session["username"], args["name"]) user_path = args['key'] if exists_path(user_path): info = self.app.config['DB'].init_project_settings(user_path) projectname = get_projectnamefromkey(user_path) self.app.config['DB'].set_user_main_project( session['username'], projectname) result = {"status": "success", "msg": info} self.app.config['DB'].insert_loginfo(session['username'], 'project', 'set_main', user_path, info) return result
def __deluser(self, args): result = {"status": "success", "msg": "成功:移除用户."} project = get_projectnamefromkey(args['key']) owner = get_ownerfromkey(args['key']) if not session["username"] == owner: result["status"] = "fail" result["msg"] = "失败:没有权限操作,请联系{}.".format(owner) return result new_name = args["new_name"] try: self.app.config['DB'].del_projectuser(project, new_name) except Exception: result["status"] = "fail" result["msg"] = "DB操作失败!" self.save_project(args['key']) self.save_user(args['key']) self.app.config['DB'].insert_loginfo(session['username'], 'project', 'deluser', args['key'], new_name) return result
def parser_robot_keyword_list(key): project = get_projectnamefromkey(key) cwd = os.getcwd() + "/keyword/" + project resources = ["BuiltIn"] + get_resource_list(key) resources = list(set(resources)) resources.sort() keyword_list = [] for k in resources: path = cwd + "/%s.xml" % k if not os.path.exists(path): generate_resource_xml(k, cwd + "/%s.xml" % k) tree = ET.parse(path) root = tree.getroot() name = root.attrib["name"] children = [] for kw in root.iter("kw"): # 关键字 keyword = kw.attrib["name"] # 关键字参数 params = "" doc_params = [] for arg in kw.iter("arg"): params += "\t[" + arg.text + "]" doc_params.append(arg.text) params += "\n" if len(doc_params) == 0: doc_params = "无" # 使用说明 doc = kw.find("doc").text if doc is not None: doc_help = doc.replace("\n", "<br>").replace("\r\t", "<br>") else: doc_help = doc children.append({ "id": keyword, "text": keyword, "iconCls": "icon-keyword", "attributes": { "keyword": keyword, "category": "keyword", "params": params, "doc": "<p>KeyWord: %s<br><br/>Lib: %s<br><br>Param: <br>%s<br><br>文档:<br>%s</p>" % (keyword, k, " | ".join(doc_params), doc_help) } }) keyword_list.append({ "id": name, "text": name, "state": "closed", "iconCls": "icon-keyword-list", "attributes": { "category": name }, "children": children }) return keyword_list
def get_userexcinfo(key, method): """ Get Users' execution info. :param key: :param method: :return: """ app = current_app._get_current_object() pname = get_projectnamefromkey(key) users = app.config['DB'].get_projectusers(pname) excute_list = {"total": 0, "rows": []} for u in users: sql = '''SELECT count(*) from loginfo WHERE user='******' and target='case' and action='create' and logtime > datetime('now','localtime','-1 day'); '''.format( u) res = app.config['DB'].runsql(sql) (createcase, ) = res.fetchone() sql = '''SELECT count(*) from loginfo WHERE user='******' and target='case' and (action='run' OR action='hand' OR action='debug') and logtime > datetime('now','localtime','-1 day'); '''.format( u) res = app.config['DB'].runsql(sql) (excutecase, ) = res.fetchone() sql = '''SELECT count(*) from loginfo WHERE user='******' and target='suite' and (action='create' OR action='copy') and logtime > datetime('now','localtime','-1 day'); '''.format( u) res = app.config['DB'].runsql(sql) (createsuite, ) = res.fetchone() sql = '''SELECT count(*) from loginfo WHERE user='******' and target='suite' and action='run' and logtime > datetime('now','localtime','-1 day'); '''.format( u) res = app.config['DB'].runsql(sql) (excutesuite, ) = res.fetchone() sql = '''SELECT count(*) from loginfo WHERE user='******' and target='suite' and (action='edit' OR action='rename') and logtime > datetime('now','localtime','-1 day'); '''.format( u) res = app.config['DB'].runsql(sql) (editsuite, ) = res.fetchone() sql = '''SELECT count(*) from loginfo WHERE user='******' and target='suite' and action='delete' and logtime > datetime('now','localtime','-1 day'); '''.format( u) res = app.config['DB'].runsql(sql) (deletesuite, ) = res.fetchone() sql = '''SELECT min(logtime), max(logtime) from loginfo WHERE user='******' and logtime > datetime('now','localtime','-1 day'); '''.format( u) res = app.config['DB'].runsql(sql) (start, end) = res.fetchone() usetime = start + ' - ' + end if (start and end) else "None - None" excute_list["rows"].append({ "createcase": createcase, "excutecase": excutecase, "createsuite": createsuite, "excutesuite": excutesuite, "editsuite": editsuite, "deletesuite": deletesuite, "usetime": usetime, "username": u }) return excute_list