def test_join_meeting(self, driver: webdriver.Remote): time.sleep(3) driver.find_element_by_id('enter_meeting_code_button').click() driver.find_element_by_id('join_meeting_edittext').send_keys(self.ROOM) driver.find_element_by_id('join_meeting_positive_button').click() driver.find_element_by_id('greenroom_join_button').click() assert driver.find_element_by_id( 'greenroom_sub_header' ).text == "You'll join the meeting when someone lets you in" time.sleep(5)
# "platformVersion": "5.1", # "app": r"D:\data\柠檬班环境\app测试环境\环境\应用apk包\Future-release-2018.apk", "deviceName": "Android Emulator", "appActivity": "com.xxzb.fenwoo.activity.addition.WelcomeActivity", "appPackage": "com.xxzb.fenwoo", # "noReset": "false", } # 增量开发(编程) driver = Remote(desired_capabilities=caps, command_executor='http://127.0.0.1:4444/wd/hub') driver.implicitly_wait(10) # 快速切换页面 driver.start_activity( 'com.xxzb.fenwoo', 'com.xxzb.fenwoo.activity.user.CreateGesturePwdActivity') driver.find_element_by_android_uiautomator( 'new UiSelector().text("确定")').click() # 定位绘制手势的元素 jiugongge_elem = driver.find_element_by_id( 'com.xxzb.fenwoo:id/gesturepwd_create_lockview') # 手势绘制, 1,2,3,5,7 # 得到元素的起点坐标和高宽 {"x": 3, "y": 3, "width": 599, "height": 900} # e.rect # driver.get_window_size() # e.locatoin, 元素的坐标, e.size 获取宽度和高度 BasePage(driver).jiugongge(jiugongge_elem, location=[1, 2, 3, 5, 8])
"automationName": "UiAutomator2", "deviceName": "HUAWEIP30", "appPackage": "com.lemon.lemonban", "appActivity": "com.lemon.lemonban.activity.WelcomeActivity", 'noReset': True } driver = Remote(command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_cap, ) driver.implicitly_wait(15) # 获取屏幕大小 size = driver.get_window_size() # 点击题库 driver.find_element_by_id('com.lemon.lemonban:id/navigation_tiku').click() time.sleep(2) t1 = TouchAction(driver) t1.press(x=size["width"] * 0.5, y=size["height"] * 0.8) t1.wait(200) t1.move_to(x=size["width"] * 0.5, y=size["height"] * 0.7) t1.wait(200) t1.move_to(x=size["width"] * 0.5, y=size["height"] * 0.6) t1.wait(200) t1.move_to(x=size["width"] * 0.5, y=size["height"] * 0.5) t1.wait(200) t1.release() t1.perform()
caps = { "platformName": "Android", "platformVersion": "6.0", "deviceName": "192.168.56.101:5555", "appPackage": "com.xueqiu.android", # aapt dump badging apk "appActivity": ".view.WelcomeActivityAlias", "noReset": False } from appium.webdriver import Remote driver = Remote(desired_capabilities=caps, command_executor='http://127.0.0.1:4723/wd/hub') # 初始化Remote e = driver.find_element_by_id('') rect = e.rect # 可以打印坐标的x,y,width,height strat_x = rect['x'] # 元素的起始坐标 start_y = rect['y'] # 元素的起始坐标 width = rect['width'] height = rect['height'] # 第一个点 point1 = {'x': strat_x + width / 6, 'y': start_y + height / 6} # 第二个点 point2 = {'x': strat_x + width / 6 * 3, 'y': start_y + height / 6} # 第三个点 point3 = {'x': strat_x + width / 6 * 5, 'y': start_y + height / 6} # 初始化TouchAction touch = TouchAction(driver) # press 点击 move_to 移动 release:释放
from time import sleep from yaml import load from appium.webdriver import Remote from Common import Project_path from Common.Keys import keys caps = load(open(Project_path.device_path, encoding='utf-8')) driver = Remote(desired_capabilities=caps) sleep(8) # sleep(3) ele = driver.find_element_by_id('com.android.browser:id/url') ele.clear() ele.send_keys('http://www.baidu.com') # 点击回车 driver.press_keycode(keys.KEYCODE_ENTER) sleep(2) context = driver.contexts print(context) driver.switch_to.context(context[1]) sleep(10) ele = driver.find_element_by_id('index-kw') ele.clear() ele.send_keys('无上皇座') driver.press_keycode(keys.KEYCODE_ENTER) sleep(3) driver.find_element_by_xpath("//span[text()='最新章节免费阅读_百度小说']").click()
caps = { "platformName": "Android", "platformVersion": "5.1", "deviceName": "Android Emulator", "appActivity": ".BrowserActivity", "appPackage": "com.android.browser", "noReset": "False" } android_driver = Remote(desired_capabilities=caps) android_driver.implicitly_wait(10) # 浏览器中输入网址并点击回车 address_input_e = android_driver.find_element_by_id( 'com.android.browser:id/url') address_input_e.send_keys('www.baidu.com') android_driver.press_keycode(KeyCode.ENTER) # 获取上下文环境,并进行切换app和H5环境 contexts = android_driver.contexts for ctx in contexts: if "WEBVIEW" in ctx: android_driver.switch_to.context(ctx) time.sleep(0.5) input_e = android_driver.find_element_by_id('index-kw') input_e.send_keys('柠檬班') android_driver.find_element_by_id('index-bn').click() time.sleep(1) android_driver.quit()
class AppiumCommon(unittest.TestCase): def __init__(self, filepath): self.desired_caps = {} self._driver = None file_object = open(filepath, 'rb') try: for line in file_object: # 忽略注释行 if line.startswith('#'): continue line.strip() worlds = line.split('==') # 忽略如下数据 如 app = 2 =linux if len(worlds[0]) != 2: continue if worlds[0] == 'app': self.desired_caps[worlds[0]] = PATH(worlds[1]) elif worlds[0] == 'remoteHost': remoteHost = worlds[1] else: self.desired_caps[worlds[0]] = worlds[1] except IOError as e: print e.message finally: file_object.close() # 初始化驱动 def initDriver(self): self._driver = Remote(self.remoteHost, self.desired_caps) # 用例执行后环境清理 关闭session def quitDriver(self): self._driver.quit() """ 给定控件的Xpath、id、name 来定位控件 :args: -controlInfo 控件的信息 如:xpath / id /name 等 :return: 如果找到控件返回第一个 :usrage: self.findElemen(controlInfo) """ def findElement(self, controlinfo): element = "" if controlinfo.startwith('//'): # xpath element = self._driver.find_element_by_xpath(controlinfo) # id elif ':id' in controlinfo or ':string' in controlinfo: element = self._driver.find_element_by_id(controlinfo) else: # 剩下的字符串没有特点,无法区分,因此先尝试通过name查找 try: element = self._driver.find_element_by_name(controlinfo) except: element = self._driver.find_element_by_class_name(controlinfo) return element """ 给定控件的xpatch, id 或者name来查找控件 :Args: - controlInfo: 控件的信息,可以是xpath,id或者其他属性 :Return: 返回所有满足条件的控件,返回的类型是一个列表 :Usage: self.findElements(controlInfo) """ def findElements(self, controlinfo): elements = "" if controlinfo.startwith('//'): # xpath elements = self._driver.find_element_by_xpath(controlinfo) # id elif ':id' in controlinfo: elements = self._driver.find_element_by_id(controlinfo) else: # 剩下的字符串没有特点,无法区分,因此先尝试通过name查找 elements = self._driver.find_element_by_name(controlinfo) if len(elements == 0): elements = self._driver.find_element_by_class_name(controlinfo) return elements """ 在一个已知的控件中通过给定控件的xpatch, id 或者name来查找子控件 :Args: - parentElement: 父控件,是一个已知的WebElement - childElementInfo: 子控件的信息,可以是xpath,id或者其他属性 :Return: 如果找到控件,返回第一个 :Usage: self.findElement(controlInfo) """ def findElementInParentElement(self, parentElement, childElementInfo): element = "" if (childElementInfo.startswith("//")): element = parentElement.find_element_by_xpath(childElementInfo) elif (":id/" in childElementInfo): element = parentElement.find_element_by_id(childElementInfo) else: # 剩下的字符串没有特点,无法区分,因此先尝试通过名称查找 try: element = parentElement.find_element_by_name(childElementInfo) except: # 如果通过名称不能找到则通过class name查找 element = parentElement.find_element_by_class_name(childElementInfo) return element """ 在一个已知的控件中通过给定控件的xpatch, id 或者name来查找子控件 :Args: - parentElement: 父控件,是一个已知的WebElement - childElementInfo: 子控件的信息,可以是xpath,id或者其他属性 :Return: 如果找到控件,返回所有符合条件的控件 :Usage: self.findElementsInParentElement(parentElement, controlInfo) """ def findElementsInParentElement(self, parentElement, chrildElementInfo): elements = "" if chrildElementInfo.startwith("//"): elements = self._driver.find_element_by_xpath(chrildElementInfo) elif ":id/" in chrildElementInfo: elements = self._driver.find_element_by_id(chrildElementInfo) else: # 剩下的字符串没有特点,无法区分,因此先尝试通过名称查找 elements = parentElement.find_elements_by_name(chrildElementInfo) if (len(elements) == 0): # 如果通过名称不能找到则通过class name查找 elements = parentElement.find_elements_by_class_name(chrildElementInfo) return elements """ 通过UIAutomator的uio_string 来查找控件 :Args: -uia_string: UiSelector相关的代码,参考http://developer.android.com/ tools/help/uiautomator/UiSelector.html#fromParent%28com.android.uiautomator.core.UiSelector%29 Return: -找到的控件 Useage: self.findElementByUIAutomator(new UiSelector().(android.widget.LinearLayout)) """ def findElementByUIAutomator(self, uia_string): return self._driver.find_element_by_android_uiautomator(uia_string) """ 滑动操作 Args: -X1,Y1,X2,Y2 活动起点、结束的左表 Useage: self.swipe(x1,y1,x2,y2,duration=None) duration位滑动操作的时间单位为毫秒 self.flick(x1,y1,x2,y2) :快速滑动 """ def flick(self, x1, y1, x2, y2): self._driver.flick(x1, y1, x2, y2) """ 点击屏幕上的位置,最多五个位置 Args: tap(position,duration) -position为一个列表 每一个列表是一个2元祖表示元素的坐标 -duration=None Useage: self.driver.tap([(100,100),(200,200),(300,300),(400,400),(500,500)],500) """ """ 长按点击操作 :Args: - x,y: 长按点的坐标 - peroid: 多长时间内完成该操作,单位是毫秒 :Usage: self.longPress(50, 50, 500) """ def longPress(self, x, y, peroid): self._driver.tap([(x, y)], peroid) """ 点击某一个控件,如果改控件不存在则会抛出异常 :Args: - elementInfo: 控件的信息,可以是xpath,id或者其他属性 :Usage: self.clickElement(elementInfo) """ def clickElement(self, elementInfo): element = self.findElement(elementInfo) element.click() """ 获取某个控件显示的文本,如果该控件不能找到则会抛出异常 :Args: - elementInfo: 控件的信息,可以是xpath,id或者其他属性 :Return: 返回该控件显示的文本 :Usage: self.getTextOfElement(elementInfo) """ def getTextOfElement(self, elementInfo): element = self.findElement(elementInfo) return element.text """ 清除文本框里面的文本 :Usage: self.clearTextEdit(elementInfo) """ def clearTextEdit(self, elementInfo): element = self.findElement(elementInfo) element.clear() """ 按返回键 press_keycode(self,keycode,metastate=None) 模拟发送一个硬件码到手机 Useage: self.pressBackKEY() """ def pressBackKey(self): self._driver.press_keycode(4) """ 等待某个控件显示 Args: elementInfo 控件信息 可以是XPATH ID NAME CLASS_NAME等 priod等待的秒数 Useage: self.waitForElement(elementInfo,priod) """ def waitForElement(self, elementInfo, priod): for i in range(0, priod): try: element = self.findElement(elementInfo) if element.is_displayed(): break except: continue time.sleep(1) else: raise Exception("Cannot find %s in %d seconds" % (elementInfo, priod)) """ 等待某个控件不再显示 :Args: - elementInfo: 控件的信息,可以是xpath,id或者其他属性 - period:等待的秒数 :Usage: self.waitForElementNotPresent(elementInfo, 3) """ def waitForElementNotPresent(self, elementInfo, priod): for i in range(priod): try: if not self.checkElementIsShown(elementInfo): break except: continue time.sleep(1) else: raise Exception("Cannot find %s in %d seconds" % (elementInfo, period)) """ 判断某个控件是否显示 :Args: - elementInfo: 控件的信息,可以是xpath,id或者其他属性 :Return: True: 如果当前画面中期望的控件能被找到 :Usage: self.checkElementIsShown(elementInfo) """ def checkElementIsShown(self, elementInfo): try: self.findElement(elementInfo) return True except: return False """ 判断某个控件是否显示在另外一个控件中 :Args: - parentElement: 父控件,是一个已知的WebElement - childElementInfo: 子控件的信息,可以是xpath,id或者其他属性 :Return: True: 如果当前画面中期望的控件能被找到 :Usage: self.checkElementShownInParentElement(parentElement,elementInfo) """ def checkElementShownParentElement(self, parentElement, childElementInfo): try: self.findElementInParentElement(parentElement, childElementInfo) return True except: return False """ 判断某个控件是否被选中 :Args: - elementInfo: 控件的信息,可以是xpath,id或者其他属性 :Return: True: 如果当前画面中期望的控件能被选中 :Usage: self.checkElementIsSelected(elementInfo) """ def checkElementIsSelected(self, elementInfo): element = self.findElement(elementInfo) return element.is_selected() """ 判断摸个控件是否enabled :Args: - elementInfo: 控件的信息,可以是xpath,id或者其他属性 :Return: True: 如果当前画面中期望的控件enabled :Usage: self.checkElementIsEnabled(elementInfo) """ def checkElementIsEnabled(self, elementInfo): element = self.findElement(elementInfo) return element.get_attribute("enabled") """ 获取当前的Activity :Return: 当前Activity的名称 """ def getCurrentActivety(self): return self._driver.current_activity """ 等待某一个Activity显示 备注:不确定是否适用于ios :Args: -activityName: 某acitivity的名称 -period: 等待的时间,秒数 """ def waitForActivity(self, activetyName, priod): for i in range(priod) try: if activetyName in self.getCurrentActivety(): break except: continue time.sleep(1) else: raise Exception("Cannot find the activity %s in %d seconds" % (activityName, period)) """ 保存当前手机的屏幕截图到电脑上指定位置 :Args: - pathOnPC: 电脑上保存图片的位置 :Usage: self.saveScreenshot("c:\test_POI1.jpg") """ def saveScreenshort(self, filename): self._driver.get_screenshot_as_file() def setNetwork(self, netType): pass """ 启动测试程序 """ def launchApp(self): self._driver.launch_app() """ 关闭测试程序 """ def closeApp(self): self._driver.close_app() """ 获取测试设备的OS :Return: Android或者ios """ def getDeviceOs(self): return self.desired_caps['platformName'] """ 只打开wifi连接 """ def enableWifiOnly(self): if ((self._driver.network_connection & 0x2) == 2): return else: self._driver.set_network_connection(ConnectionType.WIFI_ONLY) """ 只打开数据连接 """ def enableDataOnly(self): # if self._driver.network_connection ==4 if (int(self._driver.network_connection & 4) == 4): return else: self._driver.set_network_connection(ConnectionType.DATA_ONLY) """ 关闭所有网络连接 """ def disableAllConnection(self): self._driver.set_network_connection(ConnectionType.NO_CONNECTION) """ 获取context """ def getContext(self): self._driver.contexts def switchContext(self, contextName): self._driver.switch_to.context(contextName) """ 打开所有的网络连接 """ def enableAllConnection(self): self._driver.set_network_connection(ConnectionType.ALL_NETWORK_ON)
"appPackage": "com.xxzb.fenwoo", # 应用程序的启动页面 "appActivity": "com.xxzb.fenwoo.activity.addition.WelcomeActivity", "noReset": True } # 启动driver对象 driver = Remote(command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=capabilities ) # 设置隐式等待 driver.implicitly_wait(10) # 定位九宫格元素 ele = driver.find_element_by_id("com.xxzb.fenwoo:id/lpv_password") """ 封装一个处理九宫格滑动的方法, 入参: ele:九宫格元素, locust:轨迹[1,2,3,5,7] [1,2,3,5,7,8,9] """ def func_sli(ele, locust): """ 九宫格滑动 :param ele: 定位到的九宫格元素 :param locust: 滑动的轨迹
class Client: def __init__(self): super(Client, self).__init__() self.config = Config() self.desired_caps = { 'platformName': self.config.get_config('DESIRED_CAPS', 'platformName'), 'platformVersion': self.config.get_config('DESIRED_CAPS', 'platformVersion'), 'deviceName': self.config.get_config('DESIRED_CAPS', 'deviceName'), 'appPackage': self.config.get_config('DESIRED_CAPS', 'appPackage'), 'appActivity': self.config.get_config('DESIRED_CAPS', 'appActivity'), # 'udid': '127.0.0.1:4723', 'unicodeKeyboard': True, 'resetKeyboard': True, 'autoGrantPermissions': True, 'automationName': 'uiautomator2', 'app': PATH("packages/apps-release.apk") } self.driver_url = self.config.get_config('APP_DATABASE', 'driver_url') # self.driver = Remote("http://127.0.0.1:4723/wd/hub", self.desired_caps) self.driver = Remote('{}'.format(self.driver_url), self.desired_caps) self.driver.implicitly_wait(15) self.wait = WebDriverWait def find(self, xpath): result = self.driver.find_element_by_xpath(xpath).text return result def click(self, res): try: self.driver.find_element_by_id(res).click() except: self.driver.find_element_by_xpath(res).click() def xpath(self, xpath): self.driver.find_element_by_xpath(xpath).click() def send_keys(self, res, keywords): try: self.driver.find_element_by_id(res).send_keys(keywords) except: self.driver.find_element_by_xpath(res).send_keys(keywords) def swipe(self, res): width = self.driver.get_window_rect()['width'] height = self.driver.get_window_rect()['height'] i = 0 while i < 10: try: self.driver.find_element_by_id(res).is_enabled() break except Exception as e: self.driver.swipe(width / 2, height * 0.8, width / 2, height * 0.2) i = i + 1
# print(driver.desired_capabilities) # # # 查看当前的包名 # print(driver.current_package) # # # 查看当前的页面入口,利用这个去切换页面 # print(driver.current_activity) # 查看当前的上下文(环境) native web # print(driver.current_context) # # # 查看源码(在web环境下面,打印html源代码 在native中,打印xml) # print(driver.page_source) # # # 设备时间 # print(driver.device_time) time.sleep(4) driver.find_element_by_id("com.xueqiu.android:id/tv_agree").click() # 跳转到其他页面上 启动app # driver.start_activity("com.xueqiu.android","com.xueqiu.gear.common.js.SnowballWebViewActivity") # time.sleep(10)