1. 程式人生 > >selenium自動化登入測試用例

selenium自動化登入測試用例


# -*- coding: utf-8 -*-
from selenium import webdriver
import time
import datetime
import traceback
import logging
import os
# 測試用例執行函式
def work(browser):
    url = "http://yourdomain.com"
    browser.get(url)
    try:
        # 輸入賬號和密碼
        browser.find_element_by_name("username").send_keys(u"使用者名稱")
        browser.find_element_by_name("password").send_keys("123456")
        time.sleep(2)
 
        #點選按鈕提交登入表單
        browser.find_element_by_class_name("btn").click()
        time.sleep(5)
 
        # 驗證登入成功的url
        currUrl = browser.current_url
        if currUrl == "http://yourdomain.com/cate/index":
            print u"success"
        else:
            print u"failure"
            writeLog()
    except:
        print u"failure"
        writeLog()
 
# 寫錯誤日誌並截圖
def writeLog():
    # 組合日誌檔名(當前檔名+當前時間).比如:case_login_success_20150817192533
    basename = os.path.splitext(os.path.basename(__file__))[0]
    logFile = basename+"-"+datetime.datetime.now().strftime("%Y%m%d%H%M%S")+".log"
    logging.basicConfig(filename=logFile)
    s = traceback.format_exc()
    logging.error(s)
    browser.get_screenshot_as_file("./"+logFile+"-screenshot_error.png")
 
if __name__ == "__main__":
    browser = webdriver.Firefox()
    work(browser)
    browser.quit()