def __init__(self, remote_address: str, desired_capabilities: dict = None, execution_id: str = None): if RemoteDriver.__instance is not None: raise Exception("A driver session already exists") LoggingHelper.configure_logging() self._desired_capabilities = desired_capabilities self._mate_client: MateClient = MateClient(execution_id) AppiumWebDriver.__init__( self, command_executor=remote_address, desired_capabilities=self._desired_capabilities, ) self._mate_client.update_session_id(self.session_id) self.command_executor = CustomAppiumCommandExecutor( mate_client=self._mate_client, remote_server_addr=remote_address, ) # this ensures that mobile-specific commands are also available for our command executor self._addCommands() RemoteDriver.__instance = self
def test_accept_leave_examine(): #跑时修改 desired_caps = { 'deviceName': '9cd2876d', 'platformName': 'Android', 'platformVersion': '5.0.2', 'appPackage': 'com.hecom.sales', 'appActivity': 'com.hecom.splash.SplashActivity' } http = 'http://localhost:4723/wd/hub' employerdriver = WebDriver(http, desired_caps) desired_caps = { 'deviceName': '9cd2876d', 'platformName': 'Android', 'platformVersion': '4.4.2', 'appPackage': 'com.hecom.sales', 'appActivity': 'com.hecom.splash.SplashActivity' } http = 'http://localhost:4723/wd/hub' employeedriver = WebDriver(http, desired_caps) add_leave_examine(employeedriver) workpage = homeMainTab(employerdriver).toWorkPages() workpage.getWorkItem(name='审批').click() examinepage = examinePage(employerdriver) examinedetailpage = examinepage.toLatestWaitAprroveExamineDetailPage() examinepage = examinedetailpage.agree('agree')
def try_find_element(web_driver: WebDriver, by: FindElementBy, unique_val, retry_count, ignore_if_not_found=False) \ -> WebElement: """ attempts to find element within defined retry count. raises NoSuchElementException if ignore_if_not_found=false """ element = None retried = 0 while True: try: if by == FindElementBy.CLASS: element = web_driver.find_element_by_class_name(unique_val) elif by == FindElementBy.NAME: element = web_driver.find_element_by_name(unique_val) elif by == FindElementBy.AUTOMATION_ID: element = web_driver.find_element_by_accessibility_id( unique_val) except NoSuchElementException: retried = retried + 1 if retried > retry_count: if ignore_if_not_found: return None raise NoSuchElementException else: sleep(1) continue break return element
def driver(request) -> WebDriver: config = parse_rd_config(conf_file=request.config.getoption('--config')) appium_server_url = config.get('appium_server_url') caps = config.get('caps') driver = WebDriver(command_executor=f"http://{appium_server_url}/wd/hub", desired_capabilities=caps) yield driver driver.quit()
def show_desktop(dsk_session: WebDriver): """ Minimize all windows before opening window you need to work on. use to overcome command not working issue due to working window being overlapped by other unwanted window """ dsk_session.find_element_by_class_name( "TrayShowDesktopButtonWClass").click()
def get_clildelement(self,eles:WebDriver,key): '''封装从父元素获取子元素''' data = self.read_ini.get_value(key) by = data.split('>')[0] value = data.split('>')[1] try: if by == 'id': ele = eles.find_element_by_id(value) return ele elif by == 'xpath': ele = eles.find_element_by_xpath(value) return ele except Exception as e: self.logger.info('查找元素出现异常,异常信息为:' + {e})
class IosTestApp(TestCase): def setUp(self): server_url = 'http://127.0.0.1:4723/wd/hub' capabilities = DesiredCapabilities.IPHONE capabilities['automationName'] = 'Appium' capabilities['platformName'] = 'iOS' capabilities['deviceName'] = 'iPhone 6' capabilities['platformVersion'] = '8.3' capabilities['browserName'] = '' capabilities[ 'app'] = 'https://github.com/appium/javascript-workshop/blob/master/apps/TestApp7.1.app.zip?raw=true' # Create a new appium driver before each test self.driver = WebDriver(command_executor=server_url, desired_capabilities=capabilities) self.driver.implicitly_wait(5) def tearDown(self): # Close driver self.driver.quit() def test_sum(self): first_number = 2 second_number = 3 # Input numbers and click button first_element = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.XPATH, "//UIATextField[1]"))) first_element.send_keys(first_number) self.driver.find_element_by_xpath("//UIATextField[2]").send_keys(second_number) self.driver.find_element_by_accessibility_id("ComputeSumButton").click() # Check expected result result = int(self.driver.find_element_by_xpath("//UIAStaticText[1]").text) assert_equal(first_number + second_number, result, "Wrong sum")
def method(self, driver: WebDriver, method, value): ele = None if method == 'id': ele = driver.find_element_by_id(value) elif method == 'xpath': ele = driver.find_element_by_xpath(value) elif method == 'accessibility': ele = driver.find_element_by_accessibility_id(value) else: return 'No element' return ele
def attach(driver: WebDriver, name): ''' 截图并保存到allure报告上 ''' temp_name = "xx.png" name = "步骤--" + repr(name) # 强制转换为字符串 driver.get_screenshot_as_file(temp_name) allure.attach.file(temp_name, attachment_type=allure.attachment_type.PNG, name=name) os.remove(temp_name)
def __init__( self, desired_capabilities: dict = None, token: str = None, project_name: str = None, job_name: str = None, disable_reports: bool = False, ): if Remote.__instance is not None: raise SdkException("A driver session already exists") LoggingHelper.configure_logging() self._desired_capabilities = desired_capabilities self._token = token if token is not None else ConfigHelper.get_developer_token( ) if disable_reports: # Setting the project and job name to empty strings will cause the Agent to not initialize a report self._project_name = "" self._job_name = "" else: self._project_name = (project_name if project_name is not None else ReportHelper.infer_project_name()) self._job_name = (job_name if job_name is not None else ReportHelper.infer_job_name()) report_settings = ReportSettings(self._project_name, self._job_name) self._agent_client: AgentClient = AgentClient( token=self._token, capabilities=self._desired_capabilities, report_settings=report_settings, ) self._agent_session: AgentSession = self._agent_client.agent_session self.w3c = True if self._agent_session.dialect == "W3C" else False AppiumWebDriver.__init__( self, command_executor=self._agent_session.remote_address, desired_capabilities=self._desired_capabilities, ) self.command_executor = CustomAppiumCommandExecutor( agent_client=self._agent_client, remote_server_addr=self._agent_session.remote_address, ) # this ensures that mobile-specific commands are also available for our command executor self._addCommands() Remote.__instance = self
def swipe_down(driver: WebDriver, peroid): """ 向下滑动 :param driver: :param peroid: :return: """ l = getSize(driver) x1 = int(l[0] * 0.5) y1 = int(l[1] * 0.25) y2 = int(l[1] * 0.75) driver.swipe(x1, y1, x1, y2, peroid)
def swipe_up_with_distance(driver: WebDriver, distance, peroid): """ 向上滑动固定的距离 :param driver: :param peroid: :return: """ l = getSize(driver) x1 = int(l[0] * 0.5) y1 = int(l[1] * 0.9) y2 = int(l[1] * 0.9 - distance) driver.swipe(x1, y1, x1, y2, peroid)
def swipe_up_small(driver: WebDriver, peroid): """ 向上滑动(小距离) :param driver: :param peroid: :return: """ l = getSize(driver) x1 = int(l[0] * 0.5) y1 = int(l[1] * 0.7) y2 = int(l[1] * 0.6) driver.swipe(x1, y1, x1, y2, peroid)
def driver(mock, desired_capabilities: dict) -> WebDriver: hostname = socket.gethostname() ip = socket.gethostbyname(hostname) driver = WebDriver(command_executor=f"http://{ip}:4723/wd/hub", desired_capabilities=desired_capabilities, direct_connection=True, keep_alive=True) driver.implicitly_wait(3) logging.debug( f"created driver with desired_capabilities: {desired_capabilities}") return driver
def get_size(self, driver: WebDriver = None): """ 获取屏幕大小 :param driver: :return: """ driver = driver or self.driver if not driver: return driver x = driver.get_window_size()['width'] y = driver.get_window_size()['height'] return [x, y]
def run(self, driver: WebDriver): for step in self.steps: print(step) # {'id': 'tv_agree'} element = None if isinstance(step, dict): if "id" in step.keys(): element = driver.find_element_by_id(step["id"]) if step.keys() != "tv_top_list": element.click() elif "xpath" in step.keys(): element = driver.find_element_by_xpath(step["xpath"]) if "input" in step.keys(): element.send_keys(step["input"])
def find_by_swip2(driver: WebDriver, by, locator) -> WebElement: driver.implicitly_wait(1) elements = driver.find_elements(by, locator) while len(elements) == 0: driver.swipe(0, 600, 0, 400) elements = driver.find_elements(by, locator) driver.implicitly_wait(5) return elements[0]
def setUp(self): server_url = 'http://127.0.0.1:4723/wd/hub' app = 'https://github.com/appium/javascript-workshop/blob/master/apps/TestApp7.1.app.zip?raw=true&fake=.zip' capabilities = DesiredCapabilities.IPHONE capabilities['automationName'] = 'Appium' capabilities['platformName'] = 'iOS' capabilities['deviceName'] = 'iPhone 6' capabilities['platformVersion'] = '8.3' capabilities['browserName'] = '' capabilities['app'] = app # Create a new appium driver before each test self.driver = WebDriver(command_executor=server_url, desired_capabilities=capabilities) self.driver.implicitly_wait(5)
def quit(self): """Quits the driver and stops the session with the Mate Server, cleaning up after itself.""" # Report any left over driver command reports self.command_executor.clear_stash() # Make instance available again RemoteDriver.__instance = None try: AppiumWebDriver.quit(self) except Exception: pass # Stop the Mate client self.command_executor.mate_client.stop()
def setUp(self): server_url = 'http://127.0.0.1:4723/wd/hub' capabilities = DesiredCapabilities.ANDROID capabilities['automationName'] = 'Appium' capabilities['platformName'] = 'Android' capabilities['deviceName'] = 'Android Emulator' capabilities['browserName'] = '' capabilities[ 'app'] = 'https://github.com/appium/javascript-workshop/blob/master/apps/ApiDemos.apk?raw=true' capabilities['appWaitActivity'] = '' # Create a new appium driver before each test self.driver = WebDriver(command_executor=server_url, desired_capabilities=capabilities) self.driver.implicitly_wait(5)
def test_add_business_examine(driver): desired_caps = { 'deviceName': '9cd2876d', 'platformName': 'Android', 'platformVersion': '4.4.2', 'appPackage': 'com.hecom.sales', 'appActivity': 'com.hecom.splash.SplashActivity' } http = 'http://localhost:4723/wd/hub' driver = WebDriver(http, desired_caps) workpage = homeMainTab(driver).toWorkPages() workpage.getWorkItem(name='审批').click() examinepage = examinePage(driver) leaveexaminepage = examinepage.addBussinessOutExamine() leaveexaminepage.setReason('businessreason1') approverlistpage = leaveexaminepage.toSetApproverPage() approverlistpage.selectPersons([ ['小潘', 'xiaopan'], ]) #审批人 leaveexaminepage = approverlistpage.confirm() examinepage = leaveexaminepage.submit() examinedetailpage = examinepage.toLatestCreatedExamineDetailPage('请假申请') details = examinedetailpage.getDetails()['approve_desc'] assert 'businessreason1' in details
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False): capabilities = { 'automationName' : 'Android', 'platformName' : 'Android', 'deviceName' : '', 'appPackage' : 'com.opera.browser', 'androidDeviceSocket' : 'com.opera.browser.devtools', } if desired_capabilities: capabilities.update(desired_capabilities) AppiumDriver.__init__(self, command_executor, capabilities, browser_profile, proxy, keep_alive) self._desired_caps = capabilities
def add_image(driver: WebDriver): """截图到报告 :param driver: :return: """ if "NATIVE_APP" in driver.context: AddImage(driver.get_screenshot_as_base64()) else: context = driver.context driver.switch_to.context(None) try: AddImage(driver.get_screenshot_as_base64()) except WebDriverException as e: logger().info(f"截图失败:\n{e}") finally: driver.switch_to.context(context)
def video(driver: WebDriver, request, pytestconfig): # if pytestconfig.option.video is False: # return logging.debug(f"started recording video") driver.start_recording_screen(videoType="mpeg4", bugReport=True) yield None now = datetime.now() date_string = now.strftime("%Y-%m-%d_%H:%M:%S") video_name: str = f"{request.node.name}_{date_string}" file_name: str = f"videos/{video_name}.mp4" with open(file_name, "wb") as f: video: str = driver.stop_recording_screen() f.write(base64.b64decode(video)) logging.debug(f"saved video to file: {file_name}")
def run(self, driver: WebDriver): for step in self.steps: element = None if isinstance(step, dict): if "id" in step.keys(): element = driver.find_element_by_id(step.get("id")) elif "xpath" in step.keys(): element = driver.find_element_by_xpath(step.get("xpath")) else: print(step.keys()) if "input" in step.keys(): element.send_keys(step.get("input")) elif "get" in step.keys(): text = element.get_attribute(step.get("get")) elif "eq" in step.keys(): assert float(text) > float(step.get("eq")) else: element.click()
def swipe_up(self, driver: WebDriver = None, _time: int = 500): """ 向上滑动 :param driver: :param _time: :return: """ driver = driver or self.driver if not driver: return driver try: size = self.get_size(driver) x1 = int(size[0] * 0.5) # 起始x坐标 y1 = int(size[1] * 0.9) # 起始y坐标 y2 = int(size[1] * 0.2) # 终点y坐标 driver.swipe(x1, y1, x1, y2, _time) return True except: return False
def test_create_project(driver: WebDriver): driver.find_element_by_xpath( '//XCUIElementTypeButton[@name="+ Create new"]').click() test_project_name = 'test-project-' + random_characters() driver.find_element_by_xpath('//XCUIElementTypeTextField').send_keys( test_project_name) driver.find_element_by_xpath( '//XCUIElementTypeButton[@name="Save"]').click() time.sleep(2) driver.find_element_by_xpath( '//XCUIElementTypeStaticText[@name="{}"]'.format( test_project_name)).click() time.sleep(2)
def quit(self): """Quits the driver and stops the session with the Agent, cleaning up after itself.""" # Report any left over driver command reports self.command_executor.clear_stash() try: AppiumWebDriver.quit(self) except Exception: pass # Stop the Agent client self.command_executor.agent_client.stop() # Clean up any environment variables set in the decorator for env_var in [ EnvironmentVariable.TP_TEST_NAME, EnvironmentVariable.TP_PROJECT_NAME, EnvironmentVariable.TP_JOB_NAME, ]: EnvironmentVariable.remove(env_var)
def run(self, driver: WebDriver): for step in self.steps: element = None if isinstance(step, dict): if "id" in step.keys(): element = driver.find_element_by_id(step["id"]) elif "xpath" in step.keys(): element = driver.find_element_by_xpath(step["xpath"]) else: print(step.keys()) if "input" in step.keys(): element.send_keys(step["input"]) else: element.click() if "get" in step.keys(): text = element.get_attribute(step["get"]) return text
def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False): capabilities = { 'automationName': 'Android', 'platformName': 'Android', 'deviceName': '', 'appPackage': 'com.opera.browser', 'androidDeviceSocket': 'com.opera.browser.devtools', } if desired_capabilities: capabilities.update(desired_capabilities) AppiumDriver.__init__(self, command_executor, capabilities, browser_profile, proxy, keep_alive) self._desired_caps = capabilities
def create_driver(request, language): platform = request.config.option.platform assert platform in POSSIBLE_PLATFORM cap = open(f'configuration_data/{platform}_config.json').read() capabilities = json.loads(cap) if platform == ANDROID_TYPE and language: change_language_android(language) elif platform == IOS_TYPE: capabilities["language"] = language driver = WebDriver("http://0.0.0.0:4723/wd/hub", desired_capabilities=capabilities) driver._platform = platform driver.implicitly_wait(5) request.addfinalizer(driver.quit) return Driver(driver)
def setUp(self): server_url = 'http://127.0.0.1:4723/wd/hub' capabilities = DesiredCapabilities.ANDROID capabilities['automationName'] = 'Appium' capabilities['platformName'] = 'Android' capabilities['deviceName'] = 'Android Emulator' capabilities['browserName'] = '' capabilities['app'] = 'https://github.com/appium/javascript-workshop/blob/master/apps/ApiDemos.apk?raw=true' capabilities['appWaitActivity'] = '' # Create a new appium driver before each test self.driver = WebDriver(command_executor=server_url, desired_capabilities=capabilities) self.driver.implicitly_wait(5)
def setUp(self): server_url = 'http://127.0.0.1:4723/wd/hub' capabilities = DesiredCapabilities.IPHONE capabilities['automationName'] = 'Appium' capabilities['platformName'] = 'iOS' capabilities['deviceName'] = 'iPhone 6' capabilities['platformVersion'] = '8.3' capabilities['browserName'] = '' capabilities[ 'app'] = 'https://github.com/appium/javascript-workshop/blob/master/apps/TestApp7.1.app.zip?raw=true' # Create a new appium driver before each test self.driver = WebDriver(command_executor=server_url, desired_capabilities=capabilities) self.driver.implicitly_wait(5)
def wait_find_elements(self, by_type: str, value: str, driver: WebDriver = None): """ 获取多个元素, 显式等待 :param driver: :param by_type: :param value: :return: """ driver = driver or self.driver if not driver: return driver try: WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located(locator=(by_type, value))) return driver.find_elements(by_type, value) except: return False
def find_element_by_id(self, el_id): el_id = self.get_element_id(el_id) return AppiumDriver.find_element_by_id(self, el_id)
class Tabs(TestCase): """This is the same test as test_android.py but without using Toolium""" def setUp(self): server_url = 'http://127.0.0.1:4723/wd/hub' capabilities = DesiredCapabilities.ANDROID capabilities['automationName'] = 'Appium' capabilities['platformName'] = 'Android' capabilities['deviceName'] = 'Android Emulator' capabilities['browserName'] = '' capabilities['app'] = 'https://github.com/appium/javascript-workshop/blob/master/apps/ApiDemos.apk?raw=true' capabilities['appWaitActivity'] = '' # Create a new appium driver before each test self.driver = WebDriver(command_executor=server_url, desired_capabilities=capabilities) self.driver.implicitly_wait(5) def tearDown(self): # Close driver self.driver.quit() def test_change_tab(self): # Open tabs activity option_locator = 'new UiScrollable(new UiSelector().scrollable(true).instance(0))' \ '.scrollIntoView(new UiSelector().text("{}").instance(0));' self.driver.find_element_by_android_uiautomator(option_locator.format('Views')).click() self.driver.find_element_by_android_uiautomator(option_locator.format('Tabs')).click() self.driver.find_element_by_android_uiautomator(option_locator.format('1. Content By Id')).click() # Check that the first tab is open content1 = self.driver.find_element_by_id('io.appium.android.apis:id/view1') assert_equal('tab1', content1.text) # Open second tab and check content self.driver.find_element_by_xpath('(//android.widget.TabWidget//android.widget.TextView)[2]').click() content2 = self.driver.find_element_by_id('io.appium.android.apis:id/view2') assert_equal('tab2', content2.text)