def __init__(self): self.driver = None self.command = Command() self.flag = None # self.report = Report() self.result = None self.exception = None
def port_is_used(self, port): self.cmd = Command() result = self.cmd.excute_command_result("netstat -nat | grep " + str(port)) if len(result) > 0: # 被占用 return True else: return False
def port_is_used(cls, port_num): """ 判断端口是否被占用 :param port_num: :return: """ _cmd = Command() command = f'{Command.CHECK_PORT}{str(port_num)}' result = _cmd.get_cmd_result(command) if len(result) > 0: flag = True else: flag = False return flag
def __init__(self): self.command = Command() self.appium_command = None # self.adb = Adb() # self.adb.handle_devices() # port = Port() # port_dic = {} # port.create_list(device_list=self.adb.device_list, start_port=4723) # port_dic['appium_list'] = port.port_list # port.create_list(device_list=self.adb.device_list, start_port=4900) # port_dic['bootstrap_list'] = port.port_list # print(port_dic) self.yaml_operation = YamlOperation() self.yaml_operation.read('../config/device_info.yaml')
class Port: def port_is_used(self, port): self.cmd = Command() result = self.cmd.excute_command_result("netstat -nat | grep " + str(port)) if len(result) > 0: # 被占用 return True else: return False def create_port_list(self, start_port, device_list): ''' 生成可用端口 :return: ''' port_list = [] if device_list: while not len(port_list) == len(device_list): if not self.port_is_used(start_port): port_list.append(start_port) start_port += 1 return port_list else: print("生成可用端口失败") return None
class RunTest: def __init__(self): self.cmd = Command() self.time_stamp = str(int(time.time())) pass def run_test(self): test_dir = os.path.join(BASE_DIR, 'test_cases/test_db_case.py') html_report = os.path.join(BASE_DIR, 'report/html_report/') html_report += self.time_stamp + '.html' allure_report = os.path.join(BASE_DIR, 'report/allure_report') allure_reports = os.path.join(BASE_DIR, 'report/allure_reports/') pytest.main([ test_dir, '-v', '-s', '--html=' + html_report, '--alluredir=' + allure_reports, ]) cmd = "allure generate " + allure_reports + " -o " + allure_report + " -c" self.cmd.execute_cmd(cmd)
def get_commands(self): if not self.valid: return _commands = self.config.get("commands") for _command in _commands: _key = _command.get("key") _controller = _command.get("controller") _restriction = _command.get("restriction") _description = _command.get("descritpion") _args = _command.get("argRequired") self.commands[_key] = Command(_key, _controller, _args, description=_description, restriction=_restriction) return self.commands
class Server: def __init__(self): self.command = Command() self.appium_command = None # self.adb = Adb() # self.adb.handle_devices() # port = Port() # port_dic = {} # port.create_list(device_list=self.adb.device_list, start_port=4723) # port_dic['appium_list'] = port.port_list # port.create_list(device_list=self.adb.device_list, start_port=4900) # port_dic['bootstrap_list'] = port.port_list # print(port_dic) self.yaml_operation = YamlOperation() self.yaml_operation.read('../config/device_info.yaml') def create_command(self, device, appium_port, bootstrap_port): # self.yaml_operation.read('../config/device_info.yaml') # for i in self.yaml_operation.content: # cmd = 'appium -p %(appium)s -bp %(bootstrap)s -U %(device)s --no-reset --session-over' \ # % {'appium': i['appium_port'], # 'bootstrap': i['bootstrap_port'], # 'device': i['device'] # } # self.command_list.append(cmd) self.appium_command = 'appium -p %(appium)s -bp %(bootstrap)s -U %(device)s --no-reset --session-over' \ % {'device': device, 'appium': appium_port, 'bootstrap': bootstrap_port } # self.command_list.append(cmd) def start_appium(self, device, appium_port, bootstrap_port): # self.create_command() # for i in self.command_list: # self.command.execute_cmd(i) self.kill_server() self.create_command(device, appium_port, bootstrap_port) self.command.execute_cmd(self.appium_command) # def start_server(self): # self.kill_server() # self.create_command() # for i in self.command_list: # appium_start = threading.Thread(target=self.start_appium, args=(i,)) # appium_start.start() def kill_server(self): self.command.execute_cmd_result('tasklist | findstr node') server_list = self.command.result if server_list is not None: self.command.execute_cmd('taskkill -F -PID node.exe')
class KeyWords: def __init__(self): self.driver = None self.command = Command() self.flag = None # self.report = Report() self.result = None self.exception = None def _success(self): # 这些函数废弃,使用result装饰器 self.result = 'success' self.exception = None def _failed(self, ex=None): # 这些函数废弃,使用result装饰器 self.result = 'failed' self.exception = ex def _ignore_ex(self, ex): # 这些函数废弃,使用result装饰器 self.result = 'success' self.exception = ex def start_appium(self, device, appium_port, bootstrap_port): server = Server() server.start_appium(device, appium_port, bootstrap_port) logging.debug("start_appium" + str(device) + str(appium_port) + str(bootstrap_port)) self._success() def start_driver(self, device, appium_port, app, package, activity): driver = Driver() self.driver = driver.android_driver(device, appium_port, app, package, activity) logging.debug("start_driver" + str(device) + str(appium_port) + str(app + package) + str(activity)) self._success() def find_element(self, method, locator): if method == 'id': self.driver.find_element_by_id(locator) elif method == 'xpath': self.driver.find_element_by_xpath(locator) elif method == 'class': self.driver.find_element_by_class_name(locator) # def start_appium(self): # # self.server.start_appium() # self.server.start_server() @result def click(self, method, locator): """ 点击 :param method: 定位方式 :param locator: 定位信息 :return: """ # self.exist(method, locator) # if self.result: # try: self.driver.find_element(method, locator).click() time.sleep(1) logging.debug("click" + str(method) + str(locator)) # self._success() # except Exception as ex: # self._failed(ex) # log.info(ex) def exist_click(self, method, locator): """ 点击 :param method: 定位方式 :param locator: 定位信息 :return: """ try: self.driver.find_element(method, locator).click() time.sleep(1) logging.debug("click" + str(method) + str(locator)) self._success() except Exception as ex: self._ignore_ex(ex) def input(self, method, locator, value): """ 输入 :param method:定位方式 :param locator: 定位信息 :param value: 输入的值 :return: """ try: real_value = self.get_var(value) self.driver.find_element(method, locator).send_keys(real_value) log.info("input" + str(method) + str(locator + value)) self._success() except Exception as ex: self._failed(ex) def exist_input(self, method, locator, value): """ 输入 :param method:定位方式 :param locator: 定位信息 :param value: 输入的值 :return: """ try: real_value = self.get_var(value) self.driver.find_element(method, locator).send_keys(real_value) self._success() except Exception as ex: self._ignore_ex(ex) def clear_text(self, method, locator): """ 清空文本框文本 :param method: :param locator: :return: """ try: self.driver.find_element(method, locator).clear() except Exception as ex: self._failed(ex) def long_press(self, method, locator, press_time=2000): """ 长按操作 :param method: :param locator: :param press_time: :return: """ try: ele = self.driver.find_element(method, locator) TouchAction(self.driver).long_press(ele).wait( press_time).release().perform() self._success() except Exception as ex: self._failed(ex) def wait(self, wait_time): """ 等待时间 :param wait_time:等待时间,单位秒 :return: """ self.driver.implicitly_wait(wait_time) def get_text(self, method, locator, var): # 要解决如何把输入的当成变量来使用 """ 获取控件文本 还可以获取控件属性 [精]把获取的变量,存到var中 :param method:定位方式 :param locator: 定位信息 :param var: :return: """ try: ele = self.driver.find_element(method, locator) # return ele.text globals()[var] = ele.text except Exception as ex: self._failed(ex) # @staticmethod def compare(self, value, target, expect=True): """ 比较两个值是否相等 :param value: :param target: :return: """ try: real_value = self.get_var(value) real_target = self.get_var(target) if real_value == real_target: self.flag = True else: self.flag = False if self.flag == expect: self._success() else: self._failed() except Exception as ex: self._failed(ex) def exist(self, method, locator, var, exist=True): """ 判断控件是否存在 还需要对结果可设置 :return: """ try: ele = self.driver.find_element(method, locator) # 判断元素是否存在 if ele.size is not None: result = True else: result = False # 判断与预期结果是否一致 if result == exist: self.flag = True globals()[var] = True else: self.flag = False globals()[var] = False except Exception as ex: self.flag = False log.info(ex) def swipe(self, direction, times=1, size=1.0, duration=1000): """ 划动屏幕 :return: """ try: x = self.driver.get_window_size()['width'] y = self.driver.get_window_size()['height'] while times > 0: if direction == 'up': self.driver.swipe(x * 0.5, y * 0.9 * float(size), x * 0.5, y * 0.1 * float(size), duration) elif direction == 'down': self.driver.swipe(x * 0.5, y * 0.1 * float(size), x * 0.5, y * 0.9 * float(size), duration) elif direction == 'left': self.driver.swipe(x * 0.9 * float(size), y * 0.5, x * 0.1 * float(size), y * 0.5, duration) elif direction == 'right': self.driver.swipe(x * 0.1 * float(size), y * 0.5, x * 0.9 * float(size), y * 0.5, duration) times -= 1 self._success() except Exception as ex: self._failed(ex) def swipe_to(self, direction, method, locator, max_times=10, size=0.5): """ 划动屏幕至某一控件 :param size: :param direction: :param method: :param locator: :param max_times: 最大划动次数 :return: """ try: while (self.exist(method, locator) is False) and (max_times > 0): self.swipe(direction=direction, size=size) max_times -= 1 self._success() except Exception as ex: self._failed(ex) def screenshot(self, path): """ 截图 :param path:截图存放路径 :return: """ try: self.driver.get_screenshot_as_file(path) self._success() except Exception as ex: self._failed(ex) def home_button(self): try: self.driver.keyevent(3) except Exception as ex: self._failed(ex) def volume_up(self): self.driver.keyevent(24) def volume_down(self): self.driver.keyevent(25) def set_network(self): """ 设置网络状态 设置网络开关状态,暂时不添加 :return: """ pass def install_app(self, path): """ 安装应用 不可用,有bug :return: """ self.driver.install_app(path) def uninstall_app(self, package): """ 卸载应用 未调试 :return: """ self.driver.remove_app(package) def reset_app(self, package): """ 重置应用(清空应用数据) 不可用,有bug :return: """ self.driver.reset(package) def adb_cmd(self, cmd): """ 执行adb命令 :return: """ self.command.execute_cmd(cmd) @staticmethod def get_var(value): """ 这个方法是用来取用户传入的值 如果用户传入的是实际值,直接返回 如果用户传入的是用户自己定义的变量,{{xxx}}格式,会判断下取出实际值 强烈建议,对用户传入值的每一个地方,都是用此方法获取实际值 :param value: :return: """ if re.match('{{.*}}', value): var = value.strip('{}') real_value = globals()[var] return real_value else: return value
def __init__(self): self.cmd = Command() self.handle_driver = HandleDriverConf() self.device_list = self._get_devices() self._platform = platform.system().lower()
class Server: def __init__(self): self.cmd = Command() self.handle_driver = HandleDriverConf() self.device_list = self._get_devices() self._platform = platform.system().lower() def _get_devices(self): """ 获取设备信息 """ devices_list = [] result_list = self.cmd.get_cmd_result(Command.LIST_ADB_DEVICES) if len(result_list) >= 2: for i in result_list: if 'List' in i: continue devices_info = i.split('\t') if devices_info[1].lower() == 'device': devices_list.append(devices_info[0]) return devices_list else: raise Exception('设备未连接') def create_port_list(self, start_port): """ 创建可用端口 """ # port_list = [] port_list = Port().create_port_list(start_port, self.device_list) return port_list def create_command_ordinal(self, index): """ 按次序生成 Appium 服务启动命令 """ appium_port_list = self.create_port_list(4700) bootstrap_port_list = self.create_port_list(4900) device_list = self.device_list port = str(appium_port_list[index]) bp = str(bootstrap_port_list[index]) device = device_list[index] command = f'{Command.START_APPIUM} -p {port} -bp {bp} -U {device} --no-reset --session-override' self.handle_driver.write_data(index, port, bp, device) return command def start_server_ordinal(self, index): command = self.create_command_ordinal(index) self.cmd.exec_cmd(command) while True: port = self.handle_driver.get_value(f'user_info_{str(index)}', 'port') if Port().port_is_used(port): break def stop_server(self): server_list = self.cmd.get_cmd_result(Command.LIST_RUNNING_SERVER) if len(server_list) > 0: if self._platform == 'windows': self.cmd.exec_cmd(Command.KILL_PROCESS) else: for pid in server_list: self.cmd.exec_cmd(f'{Command.KILL_PROCESS} {pid}') def start_appium(self): """ 功能:根据线程启动 Appium 服务 """ self.stop_server() self.handle_driver.clear_data() for i in range(len(self.device_list)): appium_start = Process(target=self.start_server_ordinal, args=(i, )) appium_start.start()
import pytest import sys, time, openpyxl from util.command import Command from util.Base import Base from config.setting import Setting as set #文件路径类 from selenium import webdriver cmd = Command() base = Base() class TestIndexWeb(): """ pageobject 首个页面 """ flag = 3 base_url = "http://www.ctrip.com/" def setup_class(self): try: self.driver = cmd.start_brower(self.base_url) except Exception as err: print(format(err)) def teardown_class(self): if set.debug: print("END" * 3) self.driver.quit() def test_step_start(self, msg=base.read_dict_data(1, 6)):
def __init__(self): self.cmd = Command() self.port = Port() self.write_user_command = WriteUserCommand() self.device_list = self.get_devices()
class Server: def __init__(self): self.cmd = Command() self.port = Port() self.write_user_command = WriteUserCommand() self.device_list = self.get_devices() def get_devices(self): """ 获取设备信息 :return: """ result_list = self.cmd.excute_command_result("adb devices") device_list = [] if len(result_list) > 1: for d in result_list: if d == 'List of devices attached': continue elif '\tdevice' in d: device_list.append(d.replace('\tdevice', '')) return device_list else: return None def create_port_list(self, start_port): port_list = self.port.create_port_list(start_port, self.device_list) return port_list def create_command_list(self, i): command_list = [] appium_port_list = self.create_port_list(4700) bootstrap_list = self.create_port_list(4900) command = "appium -p " + str(appium_port_list[i]) + " -bp " + str(bootstrap_list[i]) + " -U " + self.device_list[i] + \ " --no-reset --session-override --log appium.log" command_list.append(command) self.write_user_command.write_data(i, self.device_list[i], bootstrap_list[i], appium_port_list[i]) # port device 配对关系写入配置文件,base文件读取 return command_list def start_server(self, i): """ 启动服务 :return: """ appium_command = self.create_command_list(i) self.cmd.excute_command(appium_command) def kill_server(self): """ 杀掉之前的进程 :return: """ server_list = self.cmd.excute_command_result("ps -ef | grep node") if server_list: self.cmd.excute_command("killall node") def main(self): """ 多线程启动appium :return: """ self.kill_server() self.write_user_command.clear_data() appium_list = [] for i in range(len(self.device_list)): appium_t = threading.Thread(target=self.start_server, args=(i, )) print("id: ", i) appium_list.append(appium_t) [i.start() for i in appium_list]
def __init__(self): self.cmd = Command() self.time_stamp = str(int(time.time())) pass
__author__ = "Nightwish" __title__ = "测试主方法" from util.command import Command import pytest import os comd = Command(5, 2) class Test_main(): def test_a(self): # try: A = comd.jia() assert 7 == A # except Exception as error: # print(format(error)) def test_b(self): # try: B = comd.jian() assert 4 == B # except Exception as error: # # print(format(error)) if __name__ == '__main__': pytest.main("pytest") pytest.main(["-durations=2", comd.stuite_path + os.sep + "test_main.py"])