Web 自动化测试 1

霍格沃兹测试学院 ceshiren.com

目录

  • UI 自动化测试简介
  • 使用 remote 复用已有的浏览器
  • 使用 cookie 登陆

UI 自动化测试

功能测试场景


autonumber

actor 测试工程师 as tester
participant 系统 as sys

tester -> sys: 测试工程师在系统页面做点击输入等操作
sys -> sys: 系统运行产生响应
sys -> tester: 测试工程师拿到实际结果与预期结果对比

UI 自动化测试场景


autonumber

actor 测试工程师 as tester
participant Python as python
participant Selenium as web
participant 被测系统 as sys

tester -> python: 使用Python编写自动化测试脚本
python -> web: 调用selenium执行自动化测试脚本
web -> sys: 模拟点击、输入等操作,并获取自动化运行的响应结果
sys -> python: Python拿到系统的响应结果,并与提前设定好的预期结果进行对比

什么时候需要做 UI 自动化测试

UI 自动化测试需要哪些技术

  • Web 自动化测试: Selenium、Cypress、Airtest
  • App 自动化测试: Appium、ATX、Airtest

Selenium

Selenium is a suite of tools to automate web browsers across many platforms. runs in many browsers and operating systems can be controlled by many programming languages and testing frameworks

官网

https://seleniumhq.github.io/selenium/docs/api/py/

安装 selenium

  • pip install selenium
  • 直接通过 pycharm 安装

环境安装-配置环境变量

把 chromedriver 所在路径添加至 path 内

环境变量注意事项!!!!

配置完成之后一定要重启Pycharm 或者 Cmd(命令行)

验证环境变量是否生效

where chromedriver

复用浏览器使用场景

  • 自动化测试过程中,一定要人为介入的场景
  • 编写脚本过程中,进行 Debug

复用已有浏览器-配置步骤

  1. 需要退出当前所有的谷歌浏览器(特别注意)
  2. 找到 chrome 的启动路径(下一页 ppt)
  3. 配置环境变量(下一页 ppt)
  4. 启动命令
  • windows:chrome --remote-debugging-port=9222
  • mac:Google\ Chrome --remote-debugging-port=9222

windows 环境变量配置:1. 获取启动路径

windows 环境变量配置:2. 配置环境变量

Mac 环境变量配置

  1. 获取启动路径(注意:使用 tab 键,不要手动输入)
  2. 将启动路径配置到环境变量中
# 举例,不要生搬硬套
export PATH=$PATH:/Applications/Google\ Chrome.app/Contents/MacOS

复用已有浏览器-代码设置

from selenium.webdriver.chrome.options import Options
option = Options()
option.debugger_address = "localhost:9222"
self._driver = webdriver.Chrome(options=option)
self._driver.get("https://work.weixin.qq.com/wework_admin/frame")

cookie 是什么

  • Cookie 是一些数据, 存储于你电脑上的文本文件中
  • 当 web 服务器向浏览器发送 web 页面时,在连接关闭后,服务端不会记录用户的信息

cookie 的使用场景

扫码登录等无法自动化登录的场景

使用 cookie 登录

  • 获取 cookie driver.get_cookies()
  • 设置 cookie driver.add_cookie(cookie)

思路

@startmindmap

* 思路
** 1. 打开浏览器,扫码登录
** 2. 登录之后(重点!!!),通过get_cookies获取cookie
** 3. 检查本地文件是否已经获取成功
** 4. 再次打开浏览器,直接进入主页
** 5. 可以跳过扫码步骤

@endmindmap

代码

def test_cookie():
  driver = webdriver.Chrome()
  driver.implicitly_wait(5)
  driver.get("https://work.weixin.qq.com/wework_admin/loginpage_wx?")
  cookies = [{'domain': '.work.weixin.qq.com', 'httpOnly': False,}]
  for cookie in cookies:
    driver.add_cookie(cookie)
  driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
  driver.find_element_by_id("menu_contacts").click()
  time.sleep(5)
  driver.quit()

常见问题

  • chromedriver 的配置问题
    • 下载浏览器对应的 driver 版本(如无浏览器对应版本,取相近版本即可)
  • chromedriver 配置环境变量
    • 注意:
      • 重启命令行以及 pycharm
      • Mac 需要重新加载环境变量source .zshrcsource .bash_profile
  • 学会找报错信息,以及理解报错信息的含义
  • 浏览器不要设置缩放!!!

课后作业

  • 通过 Cookie 或者 Remote 浏览器复用完成添加联系人测试用例