網站自動化測試程式如何處理 Cookie?
這篇文章主要說明自動測試程式如何處理 Cookie與處理 Cookie的測試情境,
Cookie常被用來紀錄使用者網站瀏覽行為,這些依據使用者輸入來決定網頁呈現方式,通常會透過 Cookie來完成。
例如,是否已經有登入成功? 是否已經有選取語言介面?
網站自動化測試程式可以透過存取 Cookie來模擬或試驗證使用者的選取是否正確的被處理。
文章最後,我門用 Selenium/Python實作,舉一個測試實例說明
測試情境
許多網站都會提供語言選擇的選項,舉例來說這個網站 https://www.directpass.com/signin
畫面最下方有語言的選項:英語、法語、日本語
當選擇其中一個語言時,Cookie的 LOCALE就會被記錄
例如選擇日本語,Cookie LOCALE = ‘JA-JP’
我們希望做的測試腳本如下:
- 1. 瀏覽https://www.directpass.com/signin
- 2. 選取語言 “日本語”
- 3. 驗證Cookie “LOCALE” 是否為 “JA-JP”
程式說明
我們主要透過 get_cookie來取得 LOCALE 的值,並驗證是否為預期的 JA-JP
- LOCALE_cookie = driver.get_cookie(“LOCALE”)[‘value’]
- self.assertEqual(“JA-JP”, LOCALE_cookie)
Python 範例程式
[pastacode lang=”python” message=”” highlight=”” provider=”manual”]
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
class DirectPass_Cookie_test(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.directpass.com/signin"
def test_DP_LOCALE_Selection_Cookie(self):
driver = self.driver
driver.get(self.base_url)
driver.find_element_by_link_text("English").click()
select_language = driver.find_element_by_link_text(u'日本語')
select_language.click()
LOCALE_cookie = driver.get_cookie("LOCALE")['value']
self.assertEqual("JA-JP", LOCALE_cookie)
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
[/pastacode]
其他Cookie基本操作
[pastacode lang=”python” message=”” highlight=”” provider=”manual”]
#coding=utf-8
from selenium import webdriver
from time import sleep
driver=webdriver.Firefox()
url='http://www.google.com'
driver.get(url)
print driver.get_cookies()
driver.delete_all_cookies()
driver.add_cookie({'name':'Tony','value':'123456'})
driver.get(url)
print driver.get_cookies()
driver.quit()
[/pastacode]