软件测试所有内容笔记正在陆续更新中,笔记已经在本地记录,全部为自己手动记录的笔记及总结,正在开始更新中,后续会逐步更新并完善到 软件测试学习内容总结 专栏。
本节内容:Web自动化测试

文章目录

  • 1 page object设计模式
  • 2 page object原则
  • 3 企业微信的自动化登录
    • driver下载地址
    • selenium简介
    • selenium IDE
    • 使用remote复用已有的浏览器
    • 使用cookie登陆
  • 4 page object演练
  • 5 企业微信web端自动化测试实战
    • selenium PO设计模式核心思想
    • selenium PO设计模式六大原则
    • selenium PO设计模式实战练习

1 page object设计模式

案例

案例抽象化

操作细节

历史

  • 2013 Martin Flower https://martinfowler/bliki/PageObject.html
  • 2015 Selenium https://github.con/SeleniumHQ/selenium/wiki/PageObjects
  • 2020 https://www.selenium.dev/documentation/en/guidelines_and_recommendations/page_object_models/

2 page object原则

PageObject六大原则

设计原则1

  • 只为页面中重要的元素创建page类

举例

设计原则2

  • 如果页面A导航到页面B,Page A 应当return Page B

举例

3 企业微信的自动化登录

重点

  • 了解 selenium IDE
  • 掌握使用remote复用已有的浏览器
  • 掌握使用cookie登陆

PPT:


driver下载地址

chromedriver下载地址与webview自动化关键代码

海外版地址

  • https://chromedriver.storage.googleapis/index.html

淘宝CDN

  • https://npm.taobao/mirrors/chromedriver

appium的配置

# 简单的方案
caps.setCapability("chromedriverExecutable","/Users/seveniruby/projects/chromedriver/72/chromedriver");

# 完善的方案
caps.setCapability("chromedriverExecutableDir", "/Users/seveniruby/projects/chromedriver/2.20");
caps.setCapability("chromedriverChromeMappingFile","/Users/seveniruby/projects/Java3/src/test/java/test_app/wechat/mapping.json");
caps.setCapability("showChromedriverLog", true);

mapping.json

{
  "83.0.4103.39": "83.0.4103.39",
  "81.0.4044.138": "81.0.4044.138",
  "81.0.4044.69": "81.0.4044.69",
  "81.0.4044.20": "81.0.4044.20",
}

常见错误

  • Chrome version must be >=

appium中的chromedriver说明

https://github/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md


ceshiren笔记

指定driver路径的方式
webdriver.Chrome(executable_path="/Users/jaxon/work/driver/chromedriver/chromedriver")

配置环境变量的方式
self.driver = webdriver.Chrome()

  1. chromedriver的配置问题。
    • 下载浏览器对应的driver版本
    • chromedriver配置环境变量
    • 重启命令行以及Pycharm
  2. 学会找报错信息,以及理解报错信息的含义
  3. 浏览器不要设置缩放!!!(很重要)

selenium简介

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
  • Selenium是一套跨许多平台自动化web浏览器的工具。
  • 可在多种浏览器和操作系统中运行
  • 可以被多种编程语言和测试框架控制

官网

  • https://www.selenium.dev/selenium/docs/api/py/

selenium IDE

Selenium IDE

  • 浏览器插件
  • 录制自动化脚本

配置环境变量-Windows

查看环境变量是否生效

  • Windows:where chromedriver
  • Mac:echo $chromedriver

使用remote复用已有的浏览器

复用已有的浏览器

  • 浏览器
  • chrome --remote-debugging-port=9222
  • python
  • hrome_arg=webdriver.ChromeOptions()
  • chrome_arg.debugger_address=‘127.0.0.1:9222’
  • self.driver = webdriver.Chrome(options=chrome_arg)

复用已有的浏览器(调式)

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

chrome启动路径-Windows

chrome启动路径-Mac

  • /Applications/Google\ Chrome.app/Contents/MacOS/Google\Chrome --remote-debugging-port=9222
  • 注意:使用tab键,不要手动输入

复用已有浏览器

  • 在Python中编写
  • 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/wework_admin/frame’)

代码 --PPT

# Generated by Selenium IDE
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdrivermon.by import By
class TestDemo:
    def setup_method(self, method):
        options = Options()
        options.debugger_address = '127.0.0.1:9222'
        self.driver = webdriver.Chrome(options=options)
        self.vars = {}
    def teardown_method(self,method):
        self.driver.quit()

    def test_demo(self):
        # self.driver.get('https://ceshiren')
        self.driver.find_element(By.ID, 'menu_contacts').click()
        sleep(5)

实战代码

复用浏览器核心代码

def test_wework():
  # 调用chromeoptions方法
  opt = webdriver.ChromeOptions()
  # 设置复用浏览器的地址
  opt.debugger_address = "127.0.0.1:9222"
  driver = webdriver.Chrome(options=opt)
  # 设置隐式等待
  driver.implicitly_wait(10)
  # 打开企业微信主页
  driver.get("https://work.weixin.qq/wework_admin/frame#index")
  # 点击通讯录
  driver.find_element_by_id("menu_contacts").click()

复用浏览器注意事项:

seleniummon.exceptions.InvalidCookieDomainException: Message: invalid cookie domain

原因:selenium默认域名是data:,,cookie中自带的域名,如果发现当前域名不在cookie中时,则cookie设置失败,使用cookie登录前,必须先访问下目标地址


使用cookie登陆

使用Cookie

driver.get(url)
driver.delete_all_cookies()
for cookie in cookies:
    driver.add_cookie(ciikie)
driver.refresh()

Cookie是什么

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

获取Cookie

  • driver.get_cookies()

代码 --PPT

class TestDemo:
    def setup_method(self, method):
        options = Options()
        options.debugger_address = '127.0.0.1:9222'
        self.driver = webdriver.Chrome()
        self.vars = {}
    def teardown_method(self,method):
        self.driver.quit()

    def test_demo(self):
        # print(self.driver.get_cookies())
        self.driver.get('https:work.weixin.qq/wework_admin/frame')
        db = shelve.open('cookies')
        # db['cookie'] = self.driver.get_cookies()
        cookies = db['cookie']
        for cookie in cookies:
            if 'expiry' in cookie.keys():
                cookie.pop('expiry')
            self.driver.add_cookie(cookie)
        self.driver.get('https:work.weixin.qq/wework_admin/frame')
        sleep(3)
        db.close()

实战代码

# 简易版使用cookie登录
def test_login():
  driver = webdriver.Chrome()
  # 设置cookie前访问企业微信扫码登录页面
  driver.get("https://work.weixin.qq/wework_admin/loginpage_wx")
  cookies = [{'domain': '.work.weixin.qq', 'httpOnly': False, 'name': 'wwrtx.vid', 'path': '/', 'secure': False, 'value': '1688853776947167'}]  # cookies为获得的cookie完整内容
  for cookie in cookies:
    # 把cookie传给driver
    driver.add_cookie(cookie)
  # 设置cookie后,再次访问企业微信
  driver.get("https://work.weixin.qq/wework_admin/frame#index")
  time.sleep(3)

使用序列化的方法用cookie登录

# 获取cookie序列化后存入yaml
def test_get_cookie():
  # 调用chromeoptions方法
  opt = webdriver.ChromeOptions()
  # 设置复用浏览器的地址
  opt.debugger_address = "127.0.0.1:9222"
  driver = webdriver.Chrome(options=opt)
  # 设置隐式等待
  driver.implicitly_wait(10)
  cookies = driver.get_cookies()
  with open("data.yaml", "w",encoding="utf-8") as f:
    # 快捷键导包:mac option+enter,win: alt + enter
    # 序列化cookie,存入yaml文件
    yaml.dump(cookies,f)

# 从yaml里读取cookie登录
def test_login():
  driver = webdriver.Chrome()
  # 设置cookie前访问企业微信扫码登录页面
  driver.get("https://work.weixin.qq/wework_admin/loginpage_wx")
  # 打开yaml文件,读取cookie信息,赋值给yaml_date
  with open("data.yaml",encoding="utf-8") as f:
    yaml_date = yaml.safe_load(f)
  for cookie in yaml_date:
    # 把cookie传给driver
    driver.add_cookie(cookie)
  # 设置cookie后,再次访问企业微信
  driver.get("https://work.weixin.qq/wework_admin/frame#index")
  time.sleep(3)

课后作业 --PPT

  • 使用序列化cookie的方式登录企业微信,完成导入联系人,加上断言验证

课后作业 --ceshiren
使用序列化的方法用cookie登录企业微信,并添加成员

4 page object演练


5 企业微信web端自动化测试实战

重点

  • 掌握po设计模式
  • 实现企业微信部分功能自动化测试

https://github/ceshiren/HogwartsFIS03
.member_colRight_memberTable_td:nth-child(2)

selenium PO设计模式核心思想

selenium PO设计模式六大原则

selenium PO设计模式实战练习


ceshiren
官网链接
selenium官方网站:–PO设计模式:https://www.selenium.dev/documentation/zh-cn/guidelines_and_recommendations/page_object_models/
马丁福勒个人博客:–PageObject:https://martinfowler/bliki/PageObject.html

PO设计思想

实战练习
上节课作业答案

def test_login():
    opt = webdriver.ChromeOptions()
    opt.debugger_address = "127.0.0.1:9222"
    driver = webdriver.Chrome(options=opt)
    driver.implicitly_wait(10)
    driver.get("https://work.weixin.qq/wework_admin/frame")
    driver.find_element_by_id("menu_contacts").click()
    ele = (By.CSS_SELECTOR, ".ww_operationBar .js_add_member")
    # 显示等待,等待元素是可点击状态
    WebDriverWait(driver,10).until(expected_conditions.element_to_be_clickable(ele))
    # 解决点击无效问题;设置死循环多次点击,直到目标元素出现后,跳出死循环
    while True:
        driver.find_element(*ele).click()
        element = driver.find_elements_by_id("username")
        if len(element) > 0:
            break
    driver.find_element_by_id("username").send_keys("5151155")
    driver.find_element_by_id("memberAdd_acctid").send_keys("xx151utuds")
    driver.find_element_by_id("memberAdd_mail").send_keys("s1sa51t1d@qq")
    driver.find_element_by_css_selector(".js_btn_save").click()
    time.sleep(1)
    eles = driver.find_elements_by_css_selector(".member_colRight_memberTable_td:nth-child(2)")
    name_list = []
    for value in eles:
        # 获取元素属性title的值,存入list内
        print(value.get_attribute("title"))
        name_list.append(value.get_attribute("title"))
    # 断言目标名字是否在列表内
    assert "5151155" in name_list
    print(name_list)

PO六大原则

Summary

  • The public methods represent the services that the page offers
  • Try not to expose the internals of the page
  • Generally don’t make assertions
  • Methods return other PageObjects
  • Need not represent an entire page
  • Different results for the same action are modelled as different methods

作业
使用PO设计模式编写添加成员自动化测试用例(首页-通讯录-添加成员-断言;首页-添加成员-断言)


更多推荐

13z Web自动化测试 - 软件测试