Exemplo n.º 1
0
def Login_Fixture():
    # 获取我的页面
    driver = Remote(Config.get("xf_remote", "command_executor"),
                    eval(Config.get("xf_remote", "desired_capabilities")))
    my_page = MyPage(driver, RESULT_XF_LOGS_DIR,
                     RESULT_XF_ERROR_SCREENSHOT_DIR)
    yield my_page
    driver.quit()
Exemplo n.º 2
0
def init_pwd():
    driver = Remote(desired_capabilities=devices_info.caps)
    driver.implicitly_wait(30)
    # 初始化登录页面
    login = Login(driver)
    home = Home(driver)
    pwd = Pwd(driver)
    yield driver, login, home, pwd
    driver.quit()
Exemplo n.º 3
0
class APP(object):
    """
    APP页面基类
    """
    __metaclass__ = _APPMetaclass
    driver_share = {}
    driver = None
    command_executor = None
    desired_capabilities = None

    def __init__(self):
        self.LOGGER = logging.getLogger(self.__class__.__name__)
        if not self.driver_share.get('driver'):
            self.driver = Remote(
                self.command_executor,
                desired_capabilities=self.desired_capabilities)
            self.driver_share['driver'] = self.driver
        else:
            self.driver = self.driver_share['driver']  # type: Remote

    @classmethod
    def init(cls, command_executor=None, desired_capabilities=None):
        if command_executor:
            cls.command_executor = command_executor
        if desired_capabilities:
            cls.desired_capabilities = desired_capabilities

    def __getattr__(self, item):
        try:
            element = self.__elements__[item]
        except IndexError:
            raise ValueError(u'没找到要查找的变量')

        time.sleep(0.4)
        total_time, element_object = self.__find_element(element)
        self.LOGGER.info(u'查找%s元素共用时: %s秒' % (item, total_time))
        return element_object

    @fn_timer
    def __find_element(self, element):
        if len(element) == 2:
            return self.driver.find_element(*element)
        elif len(element) == 3 and element[-1] == 'elements':
            return self.driver.find_elements(*element[:2])
        else:
            raise TypeError(u'Element(s)不正确')

    def quit(self):
        try:
            self.driver.quit()
            self.driver_share['driver'] = None
        except:
            pass
Exemplo n.º 4
0
def init_app():
    caps = {
        "platformName": "Android",
        "platformVersion": "5.1",
        "deviceName": "Android Emulator",
        "automationName": "uiautomator2",
        "appActivity": "com.lemon.lemonban.activity.WelcomeActivity",
        "appPackage": "com.lemon.lemonban",
        "noReset": True
    }

    app_driver = Remote(desired_capabilities=caps)
    yield app_driver
    app_driver.quit()
Exemplo n.º 5
0
def driver():
    """启动和结束appium 对象"""
    caps = {"platformName": "Android",
            "automationName":"Uiautomator2", # 使用toast弹框必须要使用uiautomator2 才能定位
            "deviceName": "emulator-5554",
            "appPackage": "com.lemon.lemonban",
            "appActivity": "com.lemon.lemonban.activity.WelcomeActivity",
            "noReset":False
            }
    # 创建一个会话
    session = Remote(command_executor='http://127.0.0.1:4723/wd/hub',
                    desired_capabilities=caps)
    # 等待
    session.implicitly_wait(10)
    yield session
    session.quit()
Exemplo n.º 6
0
def init_app():
    """启动app fixture"""
    # caps = {
    #     "platformName": "Android",
    #     "deviceName": "Android Emulator",
    #     "automationName": "UiAutomator2",
    #     "appActivity": ".activity.MainActivity",
    #     "appPackage": "com.lemon.lemonban",
    #     "chromedriverExecutableDir" : r"C:\chrome_driver",
    #     "noReset": False,
    # }
    driver = Remote(desired_capabilities=caps,
                    command_executor='http://127.0.0.1:4723/wd/hub')
    driver.implicitly_wait(20)
    yield driver

    print("退出浏览器")
    driver.quit()
Exemplo n.º 7
0
class InstallApk:
    def open_app(self, Version, name, Activity, Package, Reset):
        caps = {
            'platformName': 'Android',
            'platformVersion': Version,
            'deviceName': name,
            'appActivity': Activity,
            'appPackage': Package,
            # 'app':self.app,
            'moReset': Reset
        }

        self.driver = Remote(desired_capabilities=caps)
        sleep(10)
        self.driver.quit()
        return self.driver

    def wait_ele(self, locator):
        Wait = WebDriverWait(self.driver, 30)
        ele = Wait.until(ec.presence_of_element_located((locator)))
        return ele
Exemplo n.º 8
0
def init_bid():
    ' ' '不重置APP' ' '
    caps['noReset'] = False
    driver = Remote(desired_capabilities=caps)
    # 初始化登录页面
    login = Login(driver)
    home = Home(driver)
    bid = Bid(driver)
    sleep(3)
    # 进入首页
    home.homepage()
    # 点击注册/登录
    login.click_login()
    # 输入用户名
    login.login()
    # 输入密码
    login.get_password_input().send_keys('python')
    # 点击下一步
    login.click_next()
    login.click_talk_later()
    yield driver, login, bid
    driver.quit()
Exemplo n.º 9
0
def init_app(request):
    ' ' '初始化APP' ' '
    if request.param == 'Reset':
        # 重置APP
        caps['noReset'] = False
        driver = Remote(desired_capabilities=caps)
        login = Login(driver)
        home = Home(driver)
        sleep(3)
        # 进入首页
        home.homepage()
        sleep(1)
    else:
        # 不重置APP
        caps['noReset'] = True
        driver = Remote(desired_capabilities=caps)
        # 初始化登录页面
        login = Login(driver)
        sleep(3)
    # 点击注册/登录
    login.click_login()
    yield driver, login, caps
    driver.quit()
Exemplo n.º 10
0
# 得到元素的起点坐标和高宽  {"x": 3, "y": 3, "width": 599, "height": 900}
# e.rect
# driver.get_window_size()
# e.locatoin, 元素的坐标, e.size 获取宽度和高度
size = jiugongge.rect
print(size)

x = size['x']
y = size['y']
width = size['width']
height = size['height']

point1 = {'x': x + width / 6 * 1, 'y': y + height / 6}
point2 = {'x': x + width / 6 * 3, 'y': y + height / 6}
point3 = {'x': x + width / 6 * 5, 'y': y + height / 6}
point5 = {'x': x + width / 6 * 3, 'y': y + height / 6 * 3}
point7 = {'x': x + width / 6 * 1, 'y': y + height / 6 * 5}

# 绘制手势:TouchAction
action = TouchAction(driver)
# press(x=point1['x'], y= point1['y])
action.press(**point1).wait(200).\
    move_to(**point2).wait(200).\
    move_to(**point3).wait(200).\
    move_to(**point5).wait(200).\
    move_to(**point7).wait(200).\
    release().perform()

time.sleep(2)
driver.quit()
Exemplo n.º 11
0
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()
Exemplo n.º 12
0
def RecommenderRegistration_Fixture():

    driver = Remote(Config.get("xf_remote", "command_executor"),
                    eval(Config.get("xf_remote", "desired_capabilities")))
    # 获取首页
    home_page = HomePage(driver, RESULT_XF_LOGS_DIR,
                         RESULT_XF_ERROR_SCREENSHOT_DIR)
    # 首页关闭公告
    home_page.Home_Click_Notice_Close_Button()
    #获取我的页面
    my_page = MyPage(driver, RESULT_XF_LOGS_DIR,
                     RESULT_XF_ERROR_SCREENSHOT_DIR)
    # 点击我的
    my_page.MyPage_Click_My()
    # 点击手机号登陆
    my_page.MyPage_Click_Moblie_Login()
    # 获取手机号激活页面
    useractivation_page = UserActivationPage(driver, RESULT_XF_LOGS_DIR,
                                             RESULT_XF_ERROR_SCREENSHOT_DIR)
    # 输入激活手机号
    useractivation_page.UserActivation_Input_Mobile(
        Config.get("xf_login_data", "moblie_phone"))
    # 点击获取验证码
    useractivation_page.UserActivation_Click_Get_Verification_Code()
    # 输入验证码
    useractivation_page.UserActivation_Input_Verification_Code(
        Config.get("xf_login_data", "verification_code"))
    # 点击验证手机
    useractivation_page.UserActivation_Click_Verify_Mobile()
    # 点击我的页面普通用户登录
    my_page.MyPage_Click_Mine_Login()
    # 获取普通用户登录页面
    generaltransactionlogin_page = GeneralTransactionloginPage(
        driver, RESULT_XF_LOGS_DIR, RESULT_XF_ERROR_SCREENSHOT_DIR)
    # 普通用户页面输入账号
    generaltransactionlogin_page.GeneralTransactionlogin_Input_Account(
        Config.get("xf_login_data", "account"))
    # 普通用户页面输入密码
    generaltransactionlogin_page.GeneralTransactionlogin_Input_PassWord(
        Config.get("xf_login_data", "password"))
    # 点击登录
    generaltransactionlogin_page.GeneralTransactionlogin_Click_Login()
    # 关闭我的页面广告弹窗
    my_page.MyPage_Click_Advertisement_Window_Close()
    # 滑动到联系客服可见
    my_page.MyPage_Swipe_To_Contact_Customer_Service_Visibility()
    # 点击联系客服
    my_page.MyPage_Click_Contact_Customer_Service()
    # 获取客户页面
    contactcustomerservice_page = ContactCustomerServicePage(
        driver, RESULT_XF_LOGS_DIR, RESULT_XF_ERROR_SCREENSHOT_DIR)
    # 点击推荐人登记
    contactcustomerservice_page.ContactCustomerService_Click_Recommender_Registration(
    )
    # 获取推荐人登记页面
    recommenderregistration_page = RecommenderRegistrationPage(
        driver, RESULT_XF_LOGS_DIR, RESULT_XF_ERROR_SCREENSHOT_DIR)

    yield recommenderregistration_page
    # 返回上一页面
    driver.press_keycode(4)
    time.sleep(1)
    driver.press_keycode(4)
    # 滑动到已登录手机号
    my_page.MyPage_Swipe_To_Signed_In_Mobile_Visibility()
    # 点击已登录手机号
    my_page.MyPage_Click_Signed_In_Mobile()
    # 获取我的资料页面
    myinformation_page = MyInformationPage(driver, RESULT_XF_LOGS_DIR,
                                           RESULT_XF_ERROR_SCREENSHOT_DIR)
    # 我的资料页面,点击手机号码
    myinformation_page.MyInformation_Click_Mobile_Phone()
    # 获取退出登录页面
    logout_page = LogOutPage(driver, RESULT_XF_LOGS_DIR,
                             RESULT_XF_ERROR_SCREENSHOT_DIR)
    # 退出登录页面,点击退出登录
    logout_page.LogOut_Click_Log_Out()

    driver.quit()
Exemplo n.º 13
0
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)