当前位置:   article > 正文

Appium+Python+pytest自动化测试框架的实战_python3、pytest+appium进行微信小程序ui自动化测试架构设计

python3、pytest+appium进行微信小程序ui自动化测试架构设计

本文主要介绍了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自动化测试框架的实战的文章就介绍到这了

最后: 为了回馈铁杆粉丝们,我给大家整理了完整的软件测试视频学习教程,朋友们 如果需要可以自行免费领取 【保证100%免费】
在这里插 入图片描述

软件测试面试文档

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

在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/844856
推荐阅读
相关标签
  

闽ICP备14008679号