Selenium 学习笔记 (一)

不过多的介绍Selenium的历史以及应该使用哪个版本进行测试了。这只是我的学习笔记,方便以后回顾新的知识。

Selenium的命令—Selenese

Selenese---Selenium提供的可以进行全面的Web应用测试的命令的总称。可以通过http://release.seleniumhq.org/selenium-core/1.0.1/reference.html 查询。

该命令主要有三种子类型,Actions、Accessors和 Assertions:

  1. 1. Actions决定Selenium工具怎样操作Web系统,如:点击某个链接和选择某个下拉选项,若一个Action执行失败或发生错误,当前测试被终止执行。
  2. 2. Accessors检查当前系统状态,并将结果存放在变量中。如: storeTitle 命令。它们也被用来自动产生断言
  3. 3. Assertions类似于Accessors,不过它们验证系统是否遵从于期望的表现。如:保持页面标题是…、验证多选框…被选中。
  4. Selenium Assertions 可以被归纳为三种模式: “assert”, “verify“,”waitFor“。
  5. assert失败,测试终止,verify失败,测试继续进行,并在日志中记录失败。通常使用assert确保测试在正确的页面上进行,使用verify验证表单数据,页签等。
  6. waitFor等待某些条件变真(在对Ajax类应用中特别管用),当条件为真时,它将立刻成功,在预设时间内(setTimeout)条件没有变成真,它将失败并停止测试执行。‘

附上测试gmail登录的脚本。应该可以精简许多,明天在研究了。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re

class Test(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://accounts.google.com"
        self.verificationErrors = []
        self.accept_next_alert = True
    
    def test_(self):
        driver = self.driver
        driver.get(self.base_url + "/ServiceLogin?service=mail&passive=true&rm=false&continue=https://mail.google.com/mail/&ss=1&scc=1&ltmpl=default&ltmplcache=2")
        # ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
        # ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
        driver.find_element_by_id("Email").send_keys("******")
        driver.find_element_by_id("Passwd").send_keys("******")
        driver.find_element_by_id("signIn").click()
        # Warning: assertTextPresent may require manual changes
        #self.assertRegexpMatches(driver.find_element_by_css_selector("BODY").text, r"^[\s\S]*Gmail[\s\S]*$")
    
    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True
    
    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert.text
        finally: self.accept_next_alert = True
    
    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()
posted @ 2013-02-25 23:17  roicel  阅读(624)  评论(0编辑  收藏  举报