Appium+Python+pytest自动化测试框架的实战

本文主要介绍了Appium+Python+pytest自动化测试框架的实战,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

先简单介绍一下目录,再贴一些代码,代码里有注释

Basic目录下写的是一些公共的方法,Data目录下写的是测试数据,image存的是测试失败截图,Log日志文件,Page测试的定位元素,report测试报告,Test测试用例,pytest.ini是pytest启动配置文件,requirements.txt需要安装的py模块,run.py运行文件

在这里插入图片描述
Basic/base.py

里面封装了 一些方法,元素的点击,输入,查找,还有一些自己需要的公共方法也封装在里面,如果你们有别的需要可以自己封装调用

  1. # coding=utf-8

  2. import random

  3. import allure

  4. import pymysql

  5. import time

  6. from selenium.webdriver.common.by import By

  7. from selenium.webdriver.support.ui import WebDriverWait

  8. from Basic import Log

  9. import os

  10. log = Log.MyLog()

  11. class Base(object):

  12. def __init__(self, driver):

  13. self.driver = driver

  14. # 自定义一个元素查找方法

  15. def find_element(self, feature,timeout=5, poll=1.0):

  16. # feature = By.XPATH,"//*[@text='显示']"

  17. """

  18. 依据用户传入的元素信息特征,然后返回当前用户想要查找元素

  19. :param feature: 元组类型,包含用户希望的查找方式,及该方式对应的值

  20. :return: 返回当前用户查找的元素

  21. """

  22. by = feature[0]

  23. value = feature[1]

  24. wait = WebDriverWait(self.driver, timeout, poll)

  25. if by == By.XPATH:

  26. # print( "说明了用户想要使用 xpath 路径的方式来获取元素" )

  27. value = self.make_xpath(value)

  28. return wait.until(lambda x: x.find_element(by,value))

  29. def find_elements(self, feature):

  30. wait = WebDriverWait(self.driver, 5, 1)

  31. return wait.until(lambda x: x.find_elements(feature[0], feature[1]))

  32. def click_element(self, loc):

  33. '''

  34. 封装点击操作函数

  35. '''

  36. self.find_element(loc).click()

  37. def input_text(self, loc, text):

  38. '''

  39. 封装输入操作函数

  40. '''

  41. self.fm = self.find_element(loc)

  42. self.fm.clear() # 需要先清空输入框,防止有默认内容

  43. self.fm.send_keys(text)

  44. # 自定义了一个可以自动帮我们拼接 xpath 路径的工具函数

  45. def make_xpath(self, feature):

  46. start_path = "//*["

  47. end_path = "]"

  48. res_path = ""

  49. if isinstance(feature, str):

  50. # 如果是字符串 我们不能直接上来就拆我们可以判断一下它是否是默认正确的 xpath 写法

  51. if feature.startswith("//*["):

  52. return feature

  53. # 如果用户输入的是字符串,那么我们就拆成列表再次进行判断

  54. split_list = feature.split(",")

  55. if len(split_list) == 2:

  56. # //*[contains(@text,'设')]

  57. res_path = "%scontains(@%s,'%s')%s" % (start_path, split_list[0], split_list[1], end_path)

  58. elif len(split_list) == 3:

  59. # //[@text='设置']

  60. res_path = "%s@%s='%s'%s" % (start_path, split_list[0], split_list[1], end_path)

  61. else:

  62. print("请按规则使用")

  63. elif isinstance(feature, tuple):

  64. for item in feature:

  65. # 默认用户在元组当中定义的数据都是字符串

  66. split_list2 = item.split(',')

  67. if len(split_list2) == 2:

  68. res_path += "contains(@%s,'%s') and " % (split_list2[0], split_list2[1])

  69. elif len(split_list2) == 3:

  70. res_path += "@%s='%s' and " % (split_list2[0], split_list2[1])

  71. else:

  72. print("请按规则使用")

  73. andIndex = res_path.rfind(" and")

  74. res_path = res_path[0:andIndex]

  75. res_path = start_path + res_path + end_path

  76. else:

  77. print("请按规则使用")

  78. return res_path

  79. def assert_ele_in(self, text, element):

  80. '''

  81. 封装断言操作函数

  82. '''

  83. try:

  84. assert text in self.find_element(element).text

  85. assert 0

  86. except Exception:

  87. assert 1

  88. def get_assert_text(self, element):

  89. ele = self.find_element(element, timeout=5, poll=0.1)

  90. return ele.text

  91. # 自定义一个获取 toast内容的方法

  92. def get_toast_content(self, message):

  93. tmp_feature = By.XPATH, "//*[contains(@text,'%s')]" % message

  94. ele = self.find_element(tmp_feature)

  95. return ele.text

  96. # 自定义一个工具函数,可以接收用户传递的部分 toast 信息,然后返回一个布尔值,来告诉

  97. # 用户,目标 toast 到底是否存在

  98. def is_toast_exist(self, mes):

  99. # 拿着用户传过来的 message 去判断一下包含该内容的 toast 到底是否存在。

  100. try:

  101. self.get_toast_content(mes)

  102. return True

  103. except Exception:

  104. # 如果目标 toast 不存在那么就说明我们的实际结果和预期结果不一样

  105. # 因此我们想要的是断言失败

  106. return False

  107. def get_mysql(self, table, value):

  108. '''连接数据库'''

  109. # 打开数据库连接

  110. db = pymysql.connect(host='', port=, db=, user='', passwd='', charset='utf8')

  111. # 使用 cursor() 方法创建一个游标对象 cursor

  112. cursor = db.cursor()

  113. try:

  114. # 使用 execute() 方法执行 SQL 查询

  115. cursor.execute(value)

  116. db.commit()

  117. except Exception as e:

  118. print(e)

  119. db.rollback()

  120. # 使用 fetchone() 方法获取单条数据.

  121. data = cursor.fetchone()

  122. # 关闭数据库连接

  123. db.close()

  124. return data

  125. def get_xpath(self, value):

  126. '''封装获取xpath方法'''

  127. text = By.XPATH, '//*[@text="%s"]' % value

  128. return text

  129. # 自定义一个获取当前设备尺寸的功能

  130. def get_device_size(self):

  131. x = self.driver.get_window_size()["width"]

  132. y = self.driver.get_window_size()["height"]

  133. return x, y

  134. # 自定义一个功能,可以实现向左滑屏操作。

  135. def swipe_left(self):

  136. start_x = self.get_device_size()[0] * 0.9

  137. start_y = self.get_device_size()[1] * 0.5

  138. end_x = self.get_device_size()[0] * 0.4

  139. end_y = self.get_device_size()[1] * 0.5

  140. self.driver.swipe(start_x, start_y, end_x, end_y)

  141. # 自定义一个功能,可以实现向上滑屏操作。

  142. def swipe_up(self):

  143. start_x = self.get_device_size()[0] * 1/2

  144. start_y = self.get_device_size()[1] * 1/2

  145. end_x = self.get_device_size()[0] * 1/2

  146. end_y = self.get_device_size()[1] * 1/7

  147. self.driver.swipe(start_x, start_y, end_x, end_y, 500)

  148. # 切换到微信

  149. def switch_weixxin(self):

  150. self.driver.start_activity("com.tencent.mm", ".ui.LauncherUI")

  151. # 切换到医生端

  152. def switch_doctor(self):

  153. self.driver.start_activity("com.rjjk_doctor", ".MainActivity")

  154. # 切换到销售端

  155. def switch_sale(self):

  156. self.driver.start_activity("com.rjjk_sales", ".MainActivity")

  157. def switch_webview(self):

  158. # 切换到webview

  159. print(self.driver.contexts)

  160. time.sleep(5)

  161. self.driver.switch_to.context("WEBVIEW_com.tencent.mm:tools")

  162. print("切换成功")

  163. time.sleep(3)

  164. # 自定义根据坐标定位

  165. def taptest(self, a, b):

  166. # 设定系数,控件在当前手机的坐标位置除以当前手机的最大坐标就是相对的系数了

  167. # 获取当前手机屏幕大小X,Y

  168. X = self.driver.get_window_size()['width']

  169. Y = self.driver.get_window_size()['height']

  170. # 屏幕坐标乘以系数即为用户要点击位置的具体坐标

  171. self.driver.tap([(a * X, b * Y)])

  172. # 自定义截图函数

  173. def take_screenShot(self):

  174. '''

  175. 测试失败截图,并把截图展示到allure报告中

  176. '''

  177. tm = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))

  178. self.driver.get_screenshot_as_file(

  179. os.getcwd() + os.sep + "image/%s.png" % tm)

  180. allure.attach.file(os.getcwd() + os.sep + "image/%s.png" %

  181. tm, attachment_type=allure.attachment_type.PNG)

  182. # 自定义随机生成11位手机号

  183. def create_phone(self):

  184. # 第二位数字

  185. second = [3, 4, 5, 7, 8][random.randint(0, 4)]

  186. # 第三位数字

  187. third = {

  188. 3: random.randint(0, 9),

  189. 4: [5, 7, 9][random.randint(0, 2)],

  190. 5: [i for i in range(10) if i != 4][random.randint(0, 8)],

  191. 7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],

  192. 8: random.randint(0, 9),

  193. }[second]

  194. # 最后八位数字

  195. suffix = random.randint(9999999, 100000000)

  196. # 拼接手机号

  197. return "1{}{}{}".format(second, third, suffix)

Basic/deiver.py
APP启动的前置条件,一个是普通的app,一个是微信公众号,配置微信公众号自动化测试和一般的APP是有点区别的,微信需要切换webview才能定位到公众号

  1. from appium import webdriver

  2. def init_driver():

  3. desired_caps = {}

  4. # 手机 系统信息

  5. desired_caps['platformName'] = 'Android'

  6. desired_caps['platformVersion'] = '9'

  7. # 设备号

  8. desired_caps['deviceName'] = 'emulator-5554'

  9. # 包名

  10. desired_caps['appPackage'] = ''

  11. # 启动名

  12. desired_caps['appActivity'] = ''

  13. desired_caps['automationName'] = 'Uiautomator2'

  14. # 允许输入中文

  15. desired_caps['unicodeKeyboard'] = True

  16. desired_caps['resetKeyboard'] = True

  17. desired_caps['autoGrantPermissions'] = True

  18. desired_caps['noReset'] = False

  19. # 手机驱动对象

  20. driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)

  21. return driver

  22. def driver_weixin():

  23. desired_caps = {}

  24. # 手机 系统信息

  25. desired_caps['platformName'] = 'Android'

  26. desired_caps['platformVersion'] = '9'

  27. # 设备号

  28. desired_caps['deviceName'] = ''

  29. # 包名

  30. desired_caps['appPackage'] = 'com.tencent.mm'

  31. # 启动名

  32. desired_caps['appActivity'] = '.ui.LauncherUI'

  33. # desired_caps['automationName'] = 'Uiautomator2'

  34. # 允许输入中文

  35. desired_caps['unicodeKeyboard'] = True

  36. desired_caps['resetKeyboard'] = True

  37. desired_caps['noReset'] = True

  38. # desired_caps["newCommandTimeout"] = 30

  39. # desired_caps['fullReset'] = 'false'

  40. # desired_caps['newCommandTimeout'] = 10

  41. # desired_caps['recreateChromeDriverSessions'] = True

  42. desired_caps['chromeOptions'] = {'androidProcess': 'com.tencent.mm:tools'}

  43. # 手机驱动对象

  44. driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)

  45. return driver

Basic/get_data.py

这是获取测试数据的方法

  1. import os

  2. import yaml

  3. def getData(funcname, file):

  4. PATH = os.getcwd() + os.sep

  5. with open(PATH + 'Data/' + file + '.yaml', 'r', encoding="utf8") as f:

  6. data = yaml.load(f, Loader=yaml.FullLoader)

  7. # 1 先将我们获取到的所有数据都存放在一个变量当中

  8. tmpdata = data[funcname]

  9. # 2 所以此时我们需要使用循环走进它的内心。

  10. res_arr = list()

  11. for value in tmpdata.values():

  12. tmp_arr = list()

  13. for j in value.values():

  14. tmp_arr.append(j)

  15. res_arr.append(tmp_arr)

  16. return res_arr

Basic/Log.py

日志文件,不多介绍

  1. # -*- coding: utf-8 -*-

  2. """

  3. 封装log方法

  4. """

  5. import logging

  6. import os

  7. import time

  8. LEVELS = {

  9. 'debug': logging.DEBUG,

  10. 'info': logging.INFO,

  11. 'warning': logging.WARNING,

  12. 'error': logging.ERROR,

  13. 'critical': logging.CRITICAL

  14. }

  15. logger = logging.getLogger()

  16. level = 'default'

  17. def create_file(filename):

  18. path = filename[0:filename.rfind('/')]

  19. if not os.path.isdir(path):

  20. os.makedirs(path)

  21. if not os.path.isfile(filename):

  22. fd = open(filename, mode='w', encoding='utf-8')

  23. fd.close()

  24. else:

  25. pass

  26. def set_handler(levels):

  27. if levels == 'error':

  28. logger.addHandler(MyLog.err_handler)

  29. logger.addHandler(MyLog.handler)

  30. def remove_handler(levels):

  31. if levels == 'error':

  32. logger.removeHandler(MyLog.err_handler)

  33. logger.removeHandler(MyLog.handler)

  34. def get_current_time():

  35. return time.strftime(MyLog.date, time.localtime(time.time()))

  36. class MyLog:

  37. path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

  38. log_file = path+'/Log/log.log'

  39. err_file = path+'/Log/err.log'

  40. logger.setLevel(LEVELS.get(level, logging.NOTSET))

  41. create_file(log_file)

  42. create_file(err_file)

  43. date = '%Y-%m-%d %H:%M:%S'

  44. handler = logging.FileHandler(log_file, encoding='utf-8')

  45. err_handler = logging.FileHandler(err_file, encoding='utf-8')

  46. @staticmethod

  47. def debug(log_meg):

  48. set_handler('debug')

  49. logger.debug("[DEBUG " + get_current_time() + "]" + log_meg)

  50. remove_handler('debug')

  51. @staticmethod

  52. def info(log_meg):

  53. set_handler('info')

  54. logger.info("[INFO " + get_current_time() + "]" + log_meg)

  55. remove_handler('info')

  56. @staticmethod

  57. def warning(log_meg):

  58. set_handler('warning')

  59. logger.warning("[WARNING " + get_current_time() + "]" + log_meg)

  60. remove_handler('warning')

  61. @staticmethod

  62. def error(log_meg):

  63. set_handler('error')

  64. logger.error("[ERROR " + get_current_time() + "]" + log_meg)

  65. remove_handler('error')

  66. @staticmethod

  67. def critical(log_meg):

  68. set_handler('critical')

  69. logger.error("[CRITICAL " + get_current_time() + "]" + log_meg)

  70. remove_handler('critical')

  71. if __name__ == "__main__":

  72. MyLog.debug("This is debug message")

  73. MyLog.info("This is info message")

  74. MyLog.warning("This is warning message")

  75. MyLog.error("This is error")

  76. MyLog.critical("This is critical message"

Basic/Shell.py

执行shell语句方法

  1. # -*- coding: utf-8 -*-

  2. # @Time : 2018/8/1 下午2:54

  3. # @Author : WangJuan

  4. # @File : Shell.py

  5. """

  6. 封装执行shell语句方法

  7. """

  8. import subprocess

  9. class Shell:

  10. @staticmethod

  11. def invoke(cmd):

  12. output, errors = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

  13. o = output.decode("utf-8")

  14. return o

Page/page.py

  1. class Page:

  2. def __init__(self, driver):

  3. self.driver = driver

  4. @property

  5. def initloginpage(self):

  6. return Login_Page(self.driver)

Test/test_login.py

登陆的测试用,我贴一条使用数据文件的用例

  1. class Test_login:

  2. @pytest.mark.parametrize("args", getData("test_login_error", 'data_error_login'))

  3. def test_error_login(self, args):

  4. """错误登陆"""

  5. self.page.initloginpage.input_user(args[0])

  6. self.page.initloginpage.input_pwd(args[1])

  7. self.page.initloginpage.click_login()

  8. toast_status = self.page.initloginpage.is_toast_exist(args[2])

  9. if toast_status == False:

  10. self.page.initpatientpage.take_screenShot()

  11. assert False

pytest.ini

pytest配置文件,注释的是启动失败重试3次,因为appium会因为一些不可控的原因失败,所有正式运行脚本的时候需要加上这个

  1. [pytest]

  2. ;addopts = -s --html=report/report.html --reruns 3

  3. addopts = -s --html=report/report.html

  4. testpaths = ./Test

  5. python_files = test_*.py

  6. python_classes = Test*

  7. python_functions = test_add_prescription_list

  8. requirements.txt

  9. 框架中需要的患教,直接pip install -r requirements.txt 安装就可以了,可能会失败,多试几次

  10. ```python

  11. adbutils==0.3.4

  12. allure-pytest==2.7.0

  13. allure-python-commons==2.7.0

  14. Appium-Python-Client==0.46

  15. atomicwrites==1.3.0

  16. attrs==19.1.0

  17. certifi==2019.6.16

  18. chardet==3.0.4

  19. colorama==0.4.1

  20. coverage==4.5.3

  21. decorator==4.4.0

  22. deprecation==2.0.6

  23. docopt==0.6.2

  24. enum34==1.1.6

  25. facebook-wda==0.3.4

  26. fire==0.1.3

  27. humanize==0.5.1

  28. idna==2.8

  29. importlib-metadata==0.18

  30. logzero==1.5.0

  31. lxml==4.3.4

  32. more-itertools==7.1.0

  33. namedlist==1.7

  34. packaging==19.0

  35. Pillow==6.1.0

  36. pluggy==0.12.0

  37. progress==1.5

  38. py==1.8.0

  39. PyMySQL==0.9.3

  40. pyparsing==2.4.0

  41. pytest==5.0.0

  42. pytest-cov==2.7.1

  43. pytest-html==1.21.1

  44. pytest-metadata==1.8.0

  45. pytest-repeat==0.8.0

  46. pytest-rerunfailures==7.0

  47. PyYAML==5.1.1

  48. requests==2.22.0

  49. retry==0.9.2

  50. selenium==3.141.0

  51. six==1.12.0

  52. tornado==6.0.3

  53. uiautomator2==0.3.3

  54. urllib3==1.25.3

  55. wcwidth==0.1.7

  56. weditor==0.2.3

  57. whichcraft==0.6.0

  58. zipp==0.5.1

到此这篇关于Appium+Python+pytest自动化测试框架的实战的文章就介绍到这了

 

总结:

感谢每一个认真阅读我文章的人!!!

作为一位过来人也是希望大家少走一些弯路,如果你不想再体验一次学习时找不到资料,没人解答问题,坚持几天便放弃的感受的话,在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

 

          视频文档获取方式:
这份文档和视频资料,对于想从事【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!以上均可以分享,点下方小卡片即可自行领取。

  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Appium是一个用于移动应用自动化测试的开源工具,而Pytest是一个Python的测试框架。结合使用AppiumPytest,可以搭建一个强大的移动应用自动化测试框架。 使用AppiumPytest进行自动化测试时,首先需要安装AppiumAppium Python客户端。然后,编写测试脚本,可以使用Pytest提供的各种断言和测试装置。 下面是一个简单的例子,演示了如何使用AppiumPytest进行自动化测试: ```python import pytest from appium import webdriver @pytest.fixture def driver(): desired_caps = { 'platformName': 'Android', 'deviceName': 'your_device_name', 'appPackage': 'your_app_package', 'appActivity': 'your_app_activity' } driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) yield driver driver.quit() def test_login(driver): # 执行登录操作 # ... # 使用Pytest进行断言 assert driver.find_element_by_id('login_success_element').is_displayed() def test_logout(driver): # 执行退出操作 # ... # 使用Pytest进行断言 assert driver.find_element_by_id('logout_success_element').is_displayed() ``` 在上面的例子中,我们使用了`@pytest.fixture`装饰器来创建一个测试驱动程序实例。通过将`driver`作为参数传递给测试函数,我们可以在每个测试用例中共享同一个驱动程序实例。 然后,我们编写了两个测试函数`test_login`和`test_logout`,分别测试登录和退出功能。在每个测试函数中,我们使用Appium提供的API执行相应的操作,并使用Pytest提供的断言来验证测试结果。 最后,使用Pytest运行测试脚本即可进行自动化测试。 需要注意的是,上述示例代码只是一个简单的示例,实际项目中可能需要更复杂的操作和断言。同时,还可以结合其他的测试工具和框架,例如Allure报告、数据驱动等,来提升测试效果和维护性。 希望以上信息对你有帮助!如有更多问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值