python+appium自动化测试-获取toast信息


toast是基于uiautomator2,如果没有uiautomator2的话,需要安装,cmd输入:

cnpm install appium-uiautomator2-driver

需要在APP启动设置的capability中额外配置下面内容:

"automationName": "UiAutomator2"

capability的设置可以查看之前的博客:python+appium自动化测试如何控制App的启动和退出

博客园链接:

封装toast,具体代码:

# 获取toast函数封装
from selenium.webdriver.support.wait import WebDriverWait
from page.base_page import BasePage

class Toast(BasePage):
    def get_toast(self, message):
        try:
	    # 需要获取到的toast
            toast_message = '//*[@text=\'{}\']'.format(message)
	    # 使用xpath定位,是否能定位到需要的toast信息。
            toast_element = WebDriverWait(self.driver, 5, 0.5).until(lambda driver: self.driver.find_element_by_xpath(toast_message))
            print(toast_element.text)
            return toast_element.text
        except:
            print("没有找到这个toast!")

WebDriverWait(self.driver, 5, 0.5):5表示查找的时间,单位:秒;0.5表示查找的频率,单位:秒

其它函数中调用:

from common.toast import Toast
from page.base_page import BasePage

class ToastInvoke(BasePage):
    def __init__(self, driver):
        super().__init__(driver)
        self.toast = Toast(driver)

注意:由于我使用的是PO模式,所以将元素定位封装在BasePage类中,该页面使用到了元素定位,需要继承BasePage,PO模式具体内容请查看之前的博客:python+appium自动化测试Page Object模式——微博登录代码封装

博客园链接:

测试用例执行:

class TestToast:
    def setup_class(self):
        self.content_page = AppStart.start().enter_content()

    # 获取toast测试
    def test_toast(self):
        self.content_page.toast_test()
        self.content_page.toast.get_toast("已取消收藏")

以上所有代码均以微博作为示例,toast获取的代码使用的是微博内容收藏和取消收藏

以上内容有错误的地方,大家多多指正,谢谢!