def select(self, tablename, cond_dict='', order='', fields='*'): """查询数据 args: tablename :表名字 cond_dict :查询条件 order :排序条件 example: logger.info mydb.select(table) logger.info mydb.select(table, fields=["name"]) logger.info mydb.select(table, fields=["name", "age"]) logger.info mydb.select(table, fields=["age", "name"]) """ consql = ' ' if cond_dict != '': for k, v in cond_dict.items(): consql = consql + '`' + k + '`' + '=' + '"' + v + '"' + ' and' consql = consql + ' 1=1 ' if fields == "*": sql = 'select * from %s where ' % tablename else: if isinstance(fields, list): fields = ",".join(fields) sql = 'select %s from %s where ' % (fields, tablename) else: logger.info("fields input error, please input list fields.") sql = sql + consql + order logger.info('select:' + sql) return self.executeSql(sql)
def click_grade(self, grade="初一"): self.wait_for_exist() try: logger.info("选择年级,点击初一") self.click_control(grade) except: logger.info("不需要选择年级")
def release(self): '''终止APP ''' logger.info( '[%s] APP - Release - %s' % (datetime.datetime.fromtimestamp(time.time()), self._bundle_id)) self._app_started = False
def update(self, tablename, attrs_dict, cond_dict): """更新数据 args: tablename :表名字 attrs_dict :更新属性键值对字典 cond_dict :更新条件字典 example: params = {"name" : "caixinglong", "age" : "38"} cond_dict = {"name" : "liuqiao", "age" : "18"} mydb.update(table, params, cond_dict) """ attrs_list = [] consql = ' ' for tmpkey, tmpvalue in attrs_dict.items(): attrs_list.append("`" + tmpkey + "`" + "=" + "\'" + tmpvalue + "\'") attrs_sql = ",".join(attrs_list) logger.info("attrs_sql:", attrs_sql) if cond_dict != '': for k, v in cond_dict.items(): if isinstance(v, str): v = "\'" + v + "\'" consql = consql + "`" + tablename + "`." + "`" + k + "`" + '=' + v + ' and ' consql = consql + ' 1=1 ' sql = "UPDATE %s SET %s where%s" % (tablename, attrs_sql, consql) logger.info(sql) return self.executeCommit(sql)
def cmdloop(self): logger.info("""QTAF %(qtaf_version)s (test project: %(proj_root)s [%(proj_mode)s mode])\n""" % { 'qtaf_version': version, 'proj_root': settings.PROJECT_ROOT, 'proj_mode': settings.PROJECT_MODE, }) if six.PY3: raw_input_func = input else: raw_input_func = raw_input while 1: line = raw_input_func(self.prompt) args = shlex.split(line, posix="win" not in sys.platform) if not args: continue subcmd = args[0] if not self._argparser.get_subcommand(subcmd): sys.stderr.write("invalid command: \"%s\"\n" % subcmd) continue try: subcmd, ns = self._argparser.parse_args(args) subcmd.execute(ns) except SystemExit: logger.info("command exit") except: traceback.print_exc()
def execute(self, args): if not args.tests: logger.info("no test set specified") exit(1) shows = args.shows or ["filtered", "error", "normal"] priorities = args.priorities or [TestCase.EnumPriority.Normal, TestCase.EnumPriority.High] status = args.status or [TestCase.EnumStatus.Ready] test_conf = TestCaseSettings(names=args.tests, excluded_names=args.excluded_names, priorities=priorities, status=status, owners=args.owners, tags=args.tags, excluded_tags=args.excluded_tags) loader = TestLoader(test_conf.filter) tests = loader.load(test_conf.names) test_list_output = test_list_types[args.output_type](args.output_file) if "filtered" in shows: filtered_tests = loader.get_filtered_tests_with_reason().items() sorted_filtered_tests = sorted(filtered_tests, key=lambda x: x[0].test_name) test_list_output.output_filtered_tests(sorted_filtered_tests) if "normal" in shows: sorted_tests = sorted(tests, key=lambda x: x.test_name) test_list_output.output_normal_tests(sorted_tests) if "error" in shows: error_tests = loader.get_last_errors().items() sorted_error_tests = sorted(error_tests, key=lambda x: x[0]) test_list_output.output_error_tests(sorted_error_tests) test_list_output.end_output()
def cleanup_log(self): '''清理交互日志 ''' self._driver.device.cleanup_log() logger.info('[%s] Device - Clean Up Logger - %s - %s (%s)' % (datetime.datetime.fromtimestamp( time.time()), self.name, self.udid, self.ios_version))
def release(self): '''终止APP ''' self._stop_app() self._device_manager.release_driver(self._driver_wrapper) logger.info('[%s] Device - Release - %s - %s (%s)' % (datetime.datetime.fromtimestamp( time.time()), self.name, self.udid, self.ios_version))
def findUser(id): load = {"id": id} logger.info(f"request-->id:{id}") response = requests.post("http://localhost:8080/user", json=load) logger.info(f"response-->{response.json()}") return response.json()
def release(self): '''终止APP ''' logger.info( '[%s] APP - Release - %s' % (datetime.datetime.fromtimestamp(time.time()), self._app_name)) self._device.release() self._app_started = False
def deleteTable(self, tablename): """清空数据库表 args: tablename :表名字 """ sql = "DELETE FROM %s" % tablename logger.info("sql=", sql) self.executeCommit(sql)
def print_help(self): """打印帮助文档 """ logger.info( self.USAGE % { "ProgramName": self.prog, "SubcmdList": "\n".join(['\t%s' % it.name for it in self.subcmd_classes]) })
def install(self, app_path): '''安装应用程序 :param app_path: ipa或app安装包的路径(注意:真机和模拟器的安装包互不兼容) :type app_path: str :rtype: boolean ''' begin_time = time.time() result = self._driver.device.install(app_path) logger.info("安装被测应用耗时:%s" % round(time.time() - begin_time, 3)) return result
def start(self): '''启动APP ''' begin_time = time.time() env = { 'rules_of_alert_auto_handle' : self._rules_of_alert_auto_handle, 'flag_alert_auto_handled' : not self._flag_alert_auto_handled } self._driver.web.release_app_session(self._bundle_id) #重启app后app_id会发生变化,需要重新获取app_id self._app_started = self._device.start_app(self._bundle_id, self._app_params, env, self._trace_template, self._trace_output) if not self._app_started: raise Exception('APP-StartError') logger.info('[%s] APP - Start - %s - 启动耗时%s秒' % (datetime.datetime.fromtimestamp(time.time()), self._bundle_id, round(time.time() - begin_time, 3)))
def executeCommit(self, sql=''): """执行数据库sql语句,针对更新,删除,事务等操作失败时回滚 """ try: self.cur.execute(sql) self.con.commit() except pymysql.Error as e: self.con.rollback() error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1]) logger.info("error:", error) return error
def set_host_proxy(self, server, port, wifi_name): '''设置host代理 :param server: 服务器名 :type server: str :param port: 端口号 :type port: int :param wifi: wifi名 :type wifi: str ''' #ios版本 version = int(self._device.ios_version[0]) if version == 1 : version = int(self._device.ios_version[:2]) time.sleep(1) #添加保护 #进入无线局域网 if self._win.Controls['无线局域网'].wait_for_exist(2,0.05): self._win.Controls['无线局域网'].click() time.sleep(1) #添加保护 from qt4i.icontrols import Element from qt4i.qpath import QPath self._win.updateLocator({ 'wifi_name':{'type':Element, 'root':self, 'locator':wifi_name}, 'wifi_title':{'type':Element, 'root':self, 'locator':QPath("/classname='NavigationBar' & maxdepth=4 & name='%s'" % wifi_name)}, }) self._win.Controls['wifi_name'].click() time.sleep(1) #添加保护 if self._win.Controls['wifi_title'].exist(): logger.info('已经是%s, 无需切换WiFi' % wifi_name) else: #再点击一次进入代理设置 self._win.Controls['wifi_name'].click() if version == 11 : self._win.Controls['配置代理'].click() self._win.Controls['手动'].click() #服务器框 server_text_field = self._win.Controls['服务器'] server_text_field.click() server_text_field.value = server + '\n' #端口框 port_text_field = self._win.Controls['端口'] port_text_field.value = port if version == 11 : self._win.Controls['存储'].click() if self._win.Controls['wifi_name'].wait_for_exist(2,0.05): self._win.Controls['wifi_name'].click() self._win.Controls['返回.无线局域网'].click() self._win.Controls['设置'].click()
def acquire_device(self, device_id=None, **kwargs): '''申请设备接口 :param device_id: 设备ID,用于本地调试 :type device_id: string ''' if device_id: kwargs['id'] = device_id resource = self.test_resources.acquire_resource('android', condition=kwargs) device = DeviceProviderManager().connect_device(resource) if not device: raise RuntimeError('Connect device %s failed' % resource) try: self.test_result.log_record( EnumLogLevel.Environment, '申请 %s 设备成功:%s(%s)' % ('Android', device.model, device.device_id), {"device": device.imei}) except Exception as e: qta_logger.warn('GetDeviceImei error:%s' % e) if hasattr(settings, 'QT4A_DEVICE_HOSTS'): device_hosts = settings.QT4A_DEVICE_HOSTS if device_hosts: self.logInfo('设置设备hosts为:\n%s' % device_hosts) host_list = [] pattern = re.compile(r'\s*(\S+)\s+(\S+)\s*') for line in device_hosts.split('\n'): line = line.strip() if not line: continue ret = pattern.match(line) if not ret: raise RuntimeError('hosts格式错误: %r' % line) host_list.append((ret.group(1), ret.group(2))) device.modify_hosts(host_list) self.add_logcat_callback(device) if hasattr( settings, 'QT4A_RECORD_SCREEN') and settings.QT4A_RECORD_SCREEN == True: if not hasattr(self, '_record_thread_status_dict'): self._record_thread_status_dict = {} self._record_thread_status_dict[device.device_id] = False qta_logger.info('%s start record screen thread' % device.device_id) t = util.ThreadEx(target=self._record_screen_thread, args=(device, ), name='Device Record Screen Thread') t.setDaemon(True) t.start() device.adb.start_logcat() return device
def start(self): '''启动APP ''' self.__set_environment__() begin_time = time.time() self._app_started = self._device.start_app(self._app_name, self._app_params, self._trace_template, self._trace_output) if not self._app_started: raise Exception('APP-StartError') logger.info('[%s] APP - Start - %s - 启动耗时%s秒' % (datetime.datetime.fromtimestamp(time.time()), self._app_name, round(time.time() - begin_time, 3)))
def execute(self, args): """执行过程 """ if args.dest is None: dest = os.getcwd() else: dest = args.dest if os.path.isfile(__file__): mode = project.EnumProjectMode.Standard else: mode = project.EnumProjectMode.Standalone proj_path = os.path.join(dest, args.name.lower() + 'testproj') logger.info('create %s mode test project: %s' % (mode, proj_path)) project.create_project(proj_path, args.name, mode)
def __init__(self, device_id=None): '''Device构造函数 :param device_id: 本地设备的UDID 不指定UDID则获取已连接的真机,无真机连接则使用默认的模拟器 指定Simulator则使用默认的模拟器 指定UDID则使用指定的设备,如果是真机的UDID,真机不存在则异常,如果是模拟器的UDID,对不上号则异常(要注意每一台Mac的模拟器的UDID都不相同)。 :type device_id: str|None ''' self._device_manager = DeviceManager() self._driver_wrapper = self._device_manager.acquire_driver() self._driver = self._driver_wrapper.driver self._device = None # -*- -*- -*- -*- -*- -*- # 第一默认: 第一台连接的真机 if device_id is None: _real_devices = self._driver.dt.get_real_devices() if len(_real_devices) > 0: self._device = _real_devices[0] # 第二默认: 默认模拟器 if self._device is None and (device_id is None or str(device_id).lower() == 'simulator'): self._driver.dt.start_simulator() _simulators = self._driver.dt.get_simulators() for _simulator in _simulators: if _simulator['state'] == "Booted": self._device = _simulator break # 第三指定: 指定设备 if self._device is None and device_id is not None and str( device_id).lower() != 'simulator': _device = self._driver.dt.get_device_by_udid(device_id) if _device is not None: self._device = _device # -*- -*- -*- -*- -*- -*- if self._device is None: raise Exception('无可用的真机和模拟器: device_udid=%s' % device_id) # -*- -*- -*- -*- -*- -*- self._device_udid = self._device['udid'] self._device_name = self._device['name'] self._device_ios = self._device['ios'] self._device_type = self.EnumDeviceType.Unknown self._device_simulator = self._device['simulator'] self._app_started = False self._keyboard = Keyboard(self) Device.Devices.append(self) logger.info('[%s] Device - Connect - %s - %s (%s)' % (datetime.datetime.fromtimestamp( time.time()), self.name, self.udid, self.ios_version))
def __init__(self, config): self.host = config['host'] self.username = config['user'] self.password = config['passwd'] self.port = config['port'] self.con = None self.cur = None try: self.con = pymysql.connect(**config) self.con.autocommit(1) # 所有的查询,都在连接 con 的一个模块 cursor 上面运行的 self.cur = self.con.cursor() except: logger.info("DataBase connect error,please check the db config.")
def executeSql(self, sql=''): """执行sql语句,针对读操作返回结果集 args: sql :sql语句 """ try: self.cur.execute(sql) records = self.cur.fetchall() if records == (): return [None] return records except pymysql.Error as e: error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1]) logger.info(error)
def find_UIAElm(Condition, timeout=10): start = time.time() try_count = 0 while time.time() - start < timeout: try: desk_elm = UIAutomationClient.GetRootElement() elm = desk_elm.FindFirst(IUIAutomation.TreeScope_Descendants, Condition) elm.CurrentName #验证获取到是不是空elm return elm except ValueError: logger.info("未查找到有效uia元素,尝试重新查找") time.sleep(0.5) try_count += 1 raise TimeoutError("在%d秒里尝试了%d次" % (timeout, try_count))
def creatTable(self, tablename, attrdict, constraint): """创建数据库表 args: tablename :表名字 attrdict :属性键值对,{'book_name':'varchar(200) NOT NULL'...} constraint :主外键约束,PRIMARY KEY(`id`) """ # 判断表是否存在 if self.isExistTable(tablename): logger.info("%s is exit" % tablename) return sql = '' sql_mid = '`id` bigint(11) NOT NULL AUTO_INCREMENT,' for attr, value in attrdict.items(): sql_mid = sql_mid + '`' + attr + '`' + ' ' + value + ',' sql = sql + 'CREATE TABLE IF NOT EXISTS %s (' % tablename sql = sql + sql_mid sql = sql + constraint sql = sql + ') ENGINE=InnoDB DEFAULT CHARSET=utf8' logger.info('creatTable:' + sql) self.executeCommit(sql)
def insertMany(self, table, attrs, values): """插入多条数据 args: tablename :表名字 attrs :属性键 values :属性值 example: table='test_mysqldb' key = ["id" ,"name", "age"] value = [[101, "liuqiao", "25"], [102,"liuqiao1", "26"], [103 ,"liuqiao2", "27"], [104 ,"liuqiao3", "28"]] mydb.insertMany(table, key, value) """ values_sql = ['%s' for v in attrs] attrs_sql = '(' + ','.join(attrs) + ')' values_sql = ' values(' + ','.join(values_sql) + ')' sql = 'insert into %s' % table sql = sql + attrs_sql + values_sql logger.info('insertMany:' + sql) try: logger.info(sql) for i in range(0, len(values), 20000): self.cur.executemany(sql, values[i:i + 20000]) self.con.commit() except pymysql.Error as e: self.con.rollback() error = 'insertMany executemany failed! ERROR (%s): %s' % (e.args[0], e.args[1]) logger.info(error)
def insert(self, tablename, params): """创建数据库表 args: tablename :表名字 key :属性键 value :属性值 """ key = [] value = [] for tmpkey, tmpvalue in params.items(): key.append(tmpkey) if isinstance(tmpvalue, str): value.append("\'" + tmpvalue + "\'") else: value.append(tmpvalue) attrs_sql = '(' + ','.join(key) + ')' values_sql = ' values(' + ','.join(value) + ')' sql = 'insert into %s' % tablename sql = sql + attrs_sql + values_sql logger.info('_insert:' + sql) self.executeCommit(sql)
def delete(self, tablename, cond_dict): """删除数据 args: tablename :表名字 cond_dict :删除条件字典 example: params = {"name" : "caixinglong", "age" : "38"} mydb.delete(table, params) """ consql = ' ' if cond_dict != '': for k, v in cond_dict.items(): if isinstance(v, str): v = "\'" + v + "\'" consql = consql + tablename + "." + k + '=' + v + ' and ' consql = consql + ' 1=1 ' sql = "DELETE FROM %s where%s" % (tablename, consql) logger.info(sql) return self.executeCommit(sql)
def release(self): '''释放设备 ''' try: self.stop_app() self._driver.web.release() if hasattr(self, 'nlc_flag') and self.nlc_flag: #恢复网络设置 from qt4i.app import NLCType self.switch_network(5, NLCType.NONE) if hasattr(self, 'wifi') and self.wifi: #关闭host代理 self.reset_host_proxy() except Exception: traceback.print_exc() finally: try: self._test_resources.release_resource( "ios", self._device_resource.resource_id) except: pass Device.Devices.remove(self) logger.info('[%s] Device - Release - %s - %s (%s)' % (datetime.datetime.fromtimestamp(time.time()), self.name, self.udid, self.ios_version))
def task_api(id, taskName, startTime, endTime, executeCycles, executeTime, executeUserId=None, executeUserName=None, taskDetailStr=None): # 请求参数 load = { 'id': id, 'taskName': taskName, 'startTime': startTime, 'endTime': endTime, 'executeCycles': executeCycles, 'executeTime': executeTime, 'executeUserId': executeUserId, 'executeUserName': executeUserName, 'taskDetailStr': taskDetailStr, 'token': "123", 'uid': '606159115988594688', 'client_id': 'client_id', 'timestamp': int(round((time.time()) * 1000)), 'sig': "123123123" } u = url.email_url request_url = u.split("@")[0] h = host.stg_host logger.info(f"request-->{load}") # 发送请求 requests_post = requests.post(h + request_url, data=load) # 查看请求结果 return requests_post.json()
def release_all_device(): '''释放所有设备 ''' qta_logger.info('释放设备资源') Device.device_list = [] DeviceProviderManager().release_all()