appium 属性获取与断言

一、属性获取

1. 与selenium不同,有大量移动端元素的属性值

2. 官方文档地址:http://appium.io/docs/en/commands/element/attributes/attribute/

3. 用法:先获取元素,然后用get_attribute(str) 方法,根据元素拥有属性的名称获取该属性的值,参考官方文档的Example usage,如下:

tagName = self.driver.find_element_by_accessibility_id('SomeAccessibilityID').get_attribute('content-desc')

4. 实际操作实例如下:

 

 1 #!/usr/bin/python3.8.9
 2 # -*- coding: utf-8 -*-
 3 
 4 # @Author  : Tina Yu
 5 # @Time    : 2021-12-10 18:00
 6 from appium import webdriver
 7 from appium.webdriver.common.mobileby import MobileBy
 8 
 9 
10 class TestGetAttr:
11     """获取元素属性"""
12 
13     def setup(self):
14         desire_cap = {
15             "platformName": "android",
16             "deviceName": "127.0.0.1:7555",
17             "appPackage": "com.xueqiu.android",
18             "appActivity": ".view.WelcomeActivityAlias",
19             "unicodeKeyBoard": "True"
20         }
21         self.driver = webdriver.Remote("http://localhost:4723/wd/hub", desire_cap)
22         self.driver.implicitly_wait(10)
23 
24     def teardown(self):
25         self.driver.quit()
26 
27     def test_get_attr(self):
28         """
29         1、打开雪球app
30         2、点击搜索框
31         3、输入”阿里巴巴“
32         4、在搜索结果中点击”阿里巴巴“
33         5、获取这只上香港阿里巴巴的股价,并判断这只股价的价格>200
34         """
35         ele_search = self.driver.find_element(MobileBy.ID, "com.xueqiu.android:id/tv_search")
36         # 属性名称存在的,则返回属性值
37         print(ele_search.get_attribute("resource-id"))
38         # 属性名称不存在的,则返回None
39         print(ele_search.get_attribute("content-desc"))
40         ele_search.click()
View Code

 

 

运行结果如下:

 

 

二、断言

1. 普通断言:assert

2. Hamcrest断言

  • 官方文档:https://github.com/hamcrest/PyHamcrest
  • 是一种编辑断言的框架,可基于它进行开发可提高代码的可读性。
  • 需要导入包;pip install PyHamcrest
  • 然后用assert_that()方法。
  • 几个简单实例如下:
 1 #!/usr/bin/python3.8.9
 2 # -*- coding: utf-8 -*-
 3 
 4 # @Author  : Tina Yu
 5 # @Time    : 2021-12-11 14:06
 6 
 7 from hamcrest import *
 8 
 9 
10 class TestAssert:
11 
12     def test_assert(self):
13         a = 10
14         b = 20
15         assert a < b
16         # 当表达式结果为False时,会抛出错误AssertionError
17         assert a == b
18 
19     def test_hamcrest(self):
20         """
21         官方文档:https://github.com/hamcrest/PyHamcrest
22         :return:
23         """
24         actual0 = "yuhuifei"
25         actual0_1 = "yukexina"
26         expected0 = "yuhuifei"
27         print(len(actual0_1))
28         print(len(expected0))
29 
30         assert_that(actual0, equal_to(expected0), "演示断言结果为False的场景,这个字段是可选项")  # 匹配相等
31         assert_that(actual0_1, has_length(len(expected0)), "长度匹配")  # 长度匹配
32 
33         assert_that(actual0, has_string(starts_with("yu")))  # has_string - 匹配字符串 str()
34 
35         actual1 = 20.1
36         expect1 = 20
37         assert_that(actual1, close_to(expect1, expect1 * 0.1))
38         assert_that(actual1, greater_than(expect1), "断言实际比预期大")
View Code

 

posted @ 2021-12-11 14:47  于慧妃  阅读(384)  评论(0编辑  收藏  举报