def start_appium_server(self, server_arguments=None): """ used to start appium server before test executions :param server_arguments: Server arguments list """ appium_service = AppiumService() appium_service.start(args=server_arguments or [])
class AppiumSession(object): def __init__(self, capabilities): # Find free port for Appium server port = self.free_port() # Ensure we have driver if we test mobile web or hybrid apps if "chromeDriverVersion" in capabilities: driver_version = capabilities.get('chromeDriverVersion') path = ChromeDriverManager(version=driver_version).install() sys.path.append(path) # Start Appium server and attach client self.appium_service = AppiumService() self.appium_service.start(args=['--address', '127.0.0.1', '-p', str(port)]) self.driver = webdriver.Remote("http://127.0.0.1:{0}/wd/hub".format(port), capabilities) def stop(self): if self.driver is not None: self.driver.quit() if self.appium_service is not None: self.appium_service.stop() @staticmethod def free_port(): """ Determines a free port using sockets. """ free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) free_socket.bind(('0.0.0.0', 0)) free_socket.listen(5) port = free_socket.getsockname()[1] free_socket.close() return port
def start_driver(self): try: sys.stdout.flush() self.logger.info("Starting Appium service.") os.environ.setdefault( key="ANDROID_HOME", value=self.settings['android']['android_home']) self.appiumservice = AppiumService() self.appiumservice.stop() self.appiumservice.start() if self.appiumservice.is_running: self.logger.info("Appium Server is running.") self.driver = webdriver.Remote( command_executor="http://localhost:4723/wd/hub", desired_capabilities=self.settings['desired_caps']) self.logger.info("Connected with Appium Server.") self.driver.switch_to.context("NATIVE_APP") self.driver.implicitly_wait(time_to_wait=10) self.touchaction = TouchAction(self.driver) self.driver.get(url="https://www.instagram.com/{}/".format( self.settings['instagram']['username'])) self.driver.get(url="https://www.instagram.com/") sys.stdout.write('\r' + 'finished \n') except Exception as err: self.logger.critical("Appium not started") self.treat_exception(err)
def start_appium_server(): if not Utils.check_appium_is_already_running(): appium_service = AppiumService() appium_service.start() time.sleep(4) print("Appium is started") else: print("Appium is already running")
def stop_appium_server(): if Utils.check_appium_is_already_running(): appium_service = AppiumService() appium_service.stop() os.system('pkill adb') print("Appium is stop") else: print("Appium is already stop")
class AppiumDriver(object): def __init__(self, capabilities): self.appium_service = AppiumService() self.appium_service.start() self.capabilities = capabilities self.executor = 'http://0.0.0.0:4723/wd/hub' self.driver = webdriver.Remote(self.executor, capabilities) def quit(self): self.appium_service.stop()
def __init__(self, capabilities): # Find free port for Appium server port = self.free_port() # Ensure we have driver if we test mobile web or hybrid apps if "chromeDriverVersion" in capabilities: driver_version = capabilities.get('chromeDriverVersion') path = ChromeDriverManager(version=driver_version).install() sys.path.append(path) # Start Appium server and attach client self.appium_service = AppiumService() self.appium_service.start(args=['--address', '127.0.0.1', '-p', str(port)]) self.driver = webdriver.Remote("http://127.0.0.1:{0}/wd/hub".format(port), capabilities)
def __init__(self, appium_args: List[str] = None, **kwargs: Any): """ Initialize Appium wrapper """ super().__init__() self.port = find_free_port() self.service = AppiumService() self._extra_args = kwargs self._appium_args = appium_args or [] @atexit.register def _exit(): nonlocal self if self.service.is_running: self.logger.warn("exit:stop appium") self.stop()
def start(_serial, _port): # os.system("adb -s {} uninstall io.appium.android.ime".format(_serial)) # os.system("adb -s {} uninstall io.appium.unlock".format(_serial)) # os.system("adb -s {} uninstall io.appium.settings".format(_serial)) # os.system("adb -s {} uninstall io.appium.uiautomator2.server".format(_serial)) # os.system("adb -s {} uninstall io.appium.uiautomator2.server.test".format(_serial)) bp_port = utils.valid_port(int(_port) + 2000) log_file = os.path.join('/tmp/appium_{}.log'.format(_serial)) service = AppiumService() service.start(args=['-p', str(_port), '-bp', str(bp_port), '-U', _serial, '--session-override', '--no-reset', '--log-level', 'error', '--log', log_file], timeout_ms=2000)
def __init__(self, startServer=False, phone="RN8P"): self.start_server = startServer # Flag to start inline server # ============ START SERVER ============ if self.start_server: self.appium_service = AppiumService() self.appium_service.start() # ============ LAUNCH APP ============ self.driver = webdriver.Remote("http://localhost:4723/wd/hub", DESIRED_CAPS) time.sleep(5) # Wait for App self.dev_window_size = WIN_SIZE_RN8P if phone == "RN8P" else self.driver.get_window_size( )
class Appium(Logger): def __init__(self, appium_args: List[str] = None, **kwargs: Any): """ Initialize Appium wrapper """ super().__init__() self.port = find_free_port() self.service = AppiumService() self._extra_args = kwargs self._appium_args = appium_args or [] @atexit.register def _exit(): nonlocal self if self.service.is_running: self.logger.warn("exit:stop appium") self.stop() def get_wd_hub_uri(self) -> str: """ Get local appium uri """ assert self.service.is_running, 'Appium is not running' return f'http://127.0.0.1:{self.port}/wd/hub' def start(self): assert not self.service.is_running, 'Appium already running' # https://appium.io/docs/en/writing-running-appium/server-args/ args = ['-a', '127.0.0.1', '-p', f"{self.port}"] args.extend(self._appium_args) self.logger.info( f'Start Appium with args: {" ".join(args)} {self._extra_args}') self.service.start(args=args, **self._extra_args) assert self.service.is_running, 'Appium did not started :o' uri = self.get_wd_hub_uri() self.logger.info( f'Appium started: {uri} (pid: {self.service._process.pid})') return uri def stop(self): assert self.service.is_running, 'Appium is not running' self.logger.info( f"Close appium server (port: {self.port}, pid: {self.service._process.pid})" ) self.service.stop() def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop()
class AppiumServiceUtils(object): appium_server = AppiumService() @staticmethod def start_appium(): # appium -p 4723 -bp 4724 -U 22238e79 --command-timeout 600 errmsg = "" try: AppiumServiceUtils.appium_server.start() except Exception as msg: errmsg = str(msg) print(errmsg) return errmsg @staticmethod def stop_appium(): errmsg = "" try: AppiumServiceUtils.appium_server.stop() except Exception as msg: errmsg = str(msg) return errmsg
def setUpClass(cls) -> None: cls.appium_server = AppiumService() cls.appium_server.start() cls.todoistapi = ToDoIstAPI() cls.todoistapp = ToDoIstMobileApp() cls.todoistapp.invoke_app()
def prepare_testcase(self, section): """ Testcase Setup section """ log.info("Preparing the test") # Make sure python client is installed "pip install Appium-Python-Client" # Make sure appium is installed 'npm install -g appium' self.appium_service = AppiumService() # By default appium starts server at port 4723. # You can pass port as argument in AppiumService to change it. self.appium_service.start() log.info(self.appium_service.is_running) # Following is desired capabilities for Android app desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '6.0' desired_caps['automationName'] = 'androidautomator' desired_caps['deviceName'] = 'Android Emulator' desired_caps['appPackage'] = 'com.android.calculator2' desired_caps['appActivity'] = 'com.android.calculator2.Calculator' self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
def _start_appium_server_if_needed(self): caps = self._capabilities port = caps['port'] udid = caps['udid'] system_port = caps['systemPort'] server_running = self._check_server_running(port) if server_running: print( f"\n ℹ️ Using appium server at: host=127.0.0.1 port={port}\n") return print("\n------ LAUNCHING APPIUM SERVER ------\n") self._service = AppiumService() self._service.start(args=[ '-U', str(udid), '-p', str(port), '--webdriveragent-port', str(system_port), '--allow-insecure', 'chromedriver_autodownload' ]) print(f"Server started (host=127.0.0.1 port={port})")
def start(**kwargs): port = str(free_port()) devices = Command().devices_and_version()[0] caps = get_caps()["devices"]["samsung-10"] caps.update(getattr(Context, "CAPS")) if kwargs: for key, value in kwargs.items(): caps[key] = value caps["deviceName"] = devices[0] caps["platformVersion"] = devices[1] service = AppiumService() service.start(args=["-a", "127.0.0.1", "-p", port, "--session-override"], timeout_ms=2000) driver = webdriver.Remote( command_executor=f'http://127.0.0.1:{port}/wd/hub', desired_capabilities=caps) yield driver driver.close() driver.quit() service.stop()
def base_args(*port, **kwargs): if not port: # 寻找空闲端口 port = free_port() caps = get_caps() caps.update(getattr(Context, "ENV")["caps"]) devices = Command().devices_and_version() n = 0 if kwargs: for key, value in kwargs.items(): caps[key] = value for res in devices: caps["deviceName"] = res[0] caps["platformVersion"] = res[1] service = AppiumService() service.start( args=["-a", "127.0.0.1", "-p", port[n], "--session-override"], timeout_ms=2000) driver = webdriver.Remote( command_executor='http://127.0.0.1:{}/wd/hub'.format(port[n]), desired_capabilities=caps) yield driver service.stop()
def __start_server(self): Log.info("Starting appium server...") self.service = AppiumService() self.service.start(args=['-p', str(DEFAULT_PORT)]) assert self.service.is_running, "Failed to start appium server." Log.info("Appium server started.")
def start_appium_server(self): service = AppiumService() service.start()
def setup(request): subprocess.call(['adb', 'shell', 'input', 'keyevent', 'KEYCODE_HOME']) appium_service = AppiumService() appium_service.start() desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['deviceName'] = 'raven' desired_caps['automationName'] = 'UiAutomator2' desired_caps['udid'] = '172.19.5.96:5555' desired_caps['platformVersion'] = '7.0' desired_caps['appPackage'] = 'tv.accedo.xdk.dishtv' desired_caps['appActivity'] = 'MainActivity' desired_caps['eventTimings'] = 'True' desired_caps['recordDeviceVitals'] = 'True' driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) request.cls.driver = driver yield time_events = driver.get_events() with open( '/Users/dishbusiness/Desktop/OnStreamTestFiles/Duration/Event_Time_Log.json', 'w', encoding='utf-8') as t: json.dump(time_events, t, ensure_ascii=False, indent=4) gfx = open( '/Users/dishbusiness/Desktop/OnStreamTestFiles/Logs/GFX_Log.txt', "w", encoding='ISO-8859-1') subprocess.run([ 'adb', 'shell', 'dumpsys', 'gfxinfo', 'tv.accedo.xdk.dishtv', 'framestats' ], stdout=gfx) time.sleep(30) with open('/Users/dishbusiness/Desktop/OnStreamTestFiles/Logs/GFX_Log.txt', encoding='ISO-8859-1') as infile, \ open('/Users/dishbusiness/Desktop/OnStreamTestFiles/Logs/OnStream_GFX_Stream.csv', 'w') as outfile: copy = False for line in infile: if line.strip() == "---PROFILEDATA---": copy = True continue elif line.strip() == "View hierarchy:": copy = False continue elif copy: outfile.write(line) df = pd.read_csv( r'/Users/dishbusiness/Desktop/OnStreamTestFiles/Logs/OnStream_GFX_Stream.csv' ) flag = df.loc[df['Flags'] == 0] mill = flag.div(10000000) fld = (mill["FrameCompleted"] - mill["IntendedVsync"]) p = fld.plot() p.axhline(y=16, linewidth=2, color='r') plt.savefig( '/Users/dishbusiness/Desktop/OnStreamTestFiles/Pictures/gfx_OnStream.png' ) plt.clf() cpu = driver.get_performance_data('tv.accedo.xdk.dishtv', 'memoryinfo', 10) with open('/Users/dishbusiness/Desktop/OnStreamTestFiles/Duration/cpu.txt', 'w', encoding='ISO-8859-1') as c: print(cpu, file=c) driver.quit()
def __init__(self): self.appium_server = AppiumService()
def stop_appium_server(): appium_service = AppiumService() appium_service.stop() print("Server Stoped")
def start_appium_server(): appium_service = AppiumService() appium_service.start() print("Server Started")
import subprocess from appium import webdriver from appium.webdriver.appium_service import AppiumService from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.common.by import By subprocess.call(['adb', 'shell', 'input', 'keyevent', 'KEYCODE_HOME']) appium_service = AppiumService() appium_service.start() desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['deviceName'] = 'raven' desired_caps['automationName'] = 'UiAutomator2' desired_caps['udid'] = '172.19.5.96:5555' desired_caps['platformVersion'] = '7.0' desired_caps['appPackage'] = 'tv.accedo.xdk.dishtv' desired_caps['appActivity'] = 'MainActivity' desired_caps['eventTimings'] = 'True' desired_caps['recordDeviceVitals'] = 'True' driver = webdriver.Remote('http://*****:*****@text, 'VIEW FULL TV GUIDE')]"))) driver.find_element_by_xpath( "//android.view.View[contains(@resource-id, 'tv-guide')]").click() WebDriverWait(driver, 30).until( ec.presence_of_element_located(
import os import logging import time from appium.webdriver.appium_service import AppiumService appium_service = AppiumService() def get_Android_Home(): print("checking ANDROID_HOME is defined in the system..") if os.getenv("ANDROID_HOME") is None: print("Android home is not defined..") raise RuntimeError("Define android home for the system to work...") else: print("Android Home is defined..Continuing with connection settings..") def start_appium_session(): print("starting appium server...") logging.info("starting appium server session!") appium_service.start() time.sleep(1) def stop_appium_session(): print("starting appium server...") logging.info("starting appium server session!") appium_service.stop() time.sleep(1)
from appium.webdriver.appium_service import AppiumService appium_server = AppiumService() appium_server.start() appium_server.stop()
class tc_android_calculator(aetest.Testcase): @aetest.setup def prepare_testcase(self, section): """ Testcase Setup section """ log.info("Preparing the test") # Make sure python client is installed "pip install Appium-Python-Client" # Make sure appium is installed 'npm install -g appium' self.appium_service = AppiumService() # By default appium starts server at port 4723. # You can pass port as argument in AppiumService to change it. self.appium_service.start() log.info(self.appium_service.is_running) # Following is desired capabilities for Android app desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '6.0' desired_caps['automationName'] = 'androidautomator' desired_caps['deviceName'] = 'Android Emulator' desired_caps['appPackage'] = 'com.android.calculator2' desired_caps['appActivity'] = 'com.android.calculator2.Calculator' self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) # Following is example of testing iOS app # desired_caps['platformName'] = 'iOS' # desired_caps['platformVersion'] = '11.0' # desired_caps['automationName'] = 'iosautomator' # desired_caps['deviceName'] = 'iPhone 7' # desired_caps['app'] = '/path/to/my.app' # First test section @aetest.test def pass_check(self): no_7 = self.driver.find_element(value="digit_7", by=By.ID) no_7.click() plus = self.driver.find_element(value="op_add", by=By.ID) plus.click() no_4 = self.driver.find_element(value="digit_4", by=By.ID) no_4.click() equalTo = self.driver.find_element(value="eq", by=By.ID) equalTo.click() results = self.driver.find_element(value="formula", by=By.ID) result_value = results.get_attribute('text') if result_value == '11': self.passed('Value is 11') else: self.failed('Value is not 11') # Second test section @aetest.test def failure_check(self): no_7 = self.driver.find_element(value="digit_7", by=By.ID) no_7.click() plus = self.driver.find_element(value="op_add", by=By.ID) plus.click() no_4 = self.driver.find_element(value="digit_4", by=By.ID) no_4.click() equalTo = self.driver.find_element(value="eq", by=By.ID) equalTo.click() results = self.driver.find_element(value="formula", by=By.ID) result_value = results.get_attribute('text') if result_value == '12': self.passed('Value is 12') else: self.failed('Value is not 12') @aetest.cleanup def clean_testcase(self): log.info("Pass testcase cleanup") # Close app self.driver.quit() # Stop Appium Service self.appium_service.stop()
def test_get_instance(self): assert AppiumService()
class AppiumDriver(object): service = None driver = None def __init__(self, platform, device, bundle_id, activity='com.tns.NativeScriptActivity', wait_timeout=30): """ Init appium session. :param platform: Platform enum value. :param device: device instance. :param bundle_id: bundle id of application under test (must be already deployed on device). :param activity: default app activity (needed in Android only). :param wait_timeout: timeout for finding elements (in seconds). """ capabilities = self.__get_capabilities(platform=platform, device=device, bundle_id=bundle_id, activity=activity) self.__start_server() self.__start_client(capabilities, wait_timeout) def stop(self): """ Stop appium session. """ self.__stop_client() self.__stop_server() @staticmethod def kill(): """ Kill all instance of appium server. """ Process.kill(proc_name='node', proc_cmdline='appium') def __start_server(self): Log.info("Starting appium server...") self.service = AppiumService() self.service.start(args=['-p', str(DEFAULT_PORT)]) assert self.service.is_running, "Failed to start appium server." Log.info("Appium server started.") def __stop_server(self): if self.service is not None and self.service.is_running: self.service.stop() Log.info("Stop appium server.") @staticmethod def __get_capabilities(platform, device, bundle_id, activity='com.tns.NativeScriptActivity'): capabilities = {} capabilities['platformName'] = str(platform) capabilities['platformVersion'] = device.version capabilities['deviceName'] = device.name capabilities['udid'] = device.id capabilities['noReset'] = 'true' capabilities['fullReset'] = 'false' if platform == Platform.ANDROID: capabilities['automationName'] = 'uiautomator2' capabilities['appPackage'] = bundle_id capabilities['appActivity'] = activity if platform == Platform.IOS: capabilities['automationName'] = 'XCUITest' capabilities['bundleId'] = bundle_id # In case debug session is found increase 'newCommandTimeout' to allow debugging longer period of time. capabilities['newCommandTimeout'] = 3600 if Settings.IS_DEBUG else 60 return capabilities def __start_client(self, capabilities, wait_timeout): Log.info("Starting appium client...") self.driver = webdriver.Remote('http://0.0.0.0:4723/wd/hub', capabilities) self.driver.implicitly_wait(wait_timeout) Log.info("Appium client started.") def __stop_client(self): if self.driver is not None: self.driver.quit() Log.info("Stop appium client.")
class MobileRunnerBase(RunnerBase): def __init__(self, device_info, app_info, system_capabilities): super().__init__(device_info, app_info, system_capabilities) self._service = None @property def device_info(self): return self._device_info @property def app_info(self): return self._app_info @property def capabilities(self): return self._capabilities @property def app_id(self): raise Exception("Runner must implement 'app_id' property") def supports_scenario(self, scenario: Scenario): return True def prepare(self): self._start_appium_server_if_needed() def start(self): if not self._driver: port = str(self._capabilities["port"]) self._driver = webdriver.Remote(f'http://localhost:{port}/wd/hub', self._capabilities) def reset(self): if self._driver: self._driver.reset() def stop(self): if self._driver: self._driver.terminate_app(self.app_id) def quit(self): if self._driver: self._driver.quit() if self._service: print("------ STOPPING APPIUM SERVER ------") self._service.stop() def _start_appium_server_if_needed(self): caps = self._capabilities port = caps['port'] udid = caps['udid'] system_port = caps['systemPort'] server_running = self._check_server_running(port) if server_running: print( f"\n ℹ️ Using appium server at: host=127.0.0.1 port={port}\n") return print("\n------ LAUNCHING APPIUM SERVER ------\n") self._service = AppiumService() self._service.start(args=[ '-U', str(udid), '-p', str(port), '--webdriveragent-port', str(system_port), '--allow-insecure', 'chromedriver_autodownload' ]) print(f"Server started (host=127.0.0.1 port={port})") @staticmethod def _check_server_running(port, host='127.0.0.1'): import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((host, port)) sock.close() server_running = result == 0 return server_running