python+selenium之測試報告自動化測試實例


自動化測試綜合實戰

項目背景

http://localhost/news/ 新聞子頁面進行登錄測試。

功能實現

  • 自動運行用例
  • 自動生成測試報告
  • 自動斷言與截圖
  • 自動將最新測試報告發送到指定郵箱
  • PageObject+Unittest

項目架構

 

 

 

 

瀏覽器driver定義

from selenium import webdriver

 

#啟動瀏覽器驅動

def browser():

    driver = webdriver.Firefox()

    # driver = webdriver.Chrome()

    # driver = webdriver.Ie()

    # driver=webdriver.PhantomJS()

 

    # driver.get("http://www.baidu.com")

 

    return driver

 

#調試運行

if __name__ == '__main__':

     browser()

 

用例運行前后的環境准備工作

import unittest

from driver import *

 

class StartEnd(unittest.TestCase):

    def setUp(self):

        self.driver=browser()

        self.driver.implicitly_wait(10)

        self.driver.maximize_window()

 

    def tearDown(self):

        self.driver.quit()

 

工具方法模塊(截圖,查找最新報告、郵件發送)

from  selenium import webdriver

import os

import smtplib

from email.mime.text import MIMEText

from email.header import Header

 

#截圖方法

def inser_img(driver,filename):

 

    #獲取當前模塊所在路徑

    func_path=os.path.dirname(__file__)

    # print("func_path is %s" %func_path)

 

    #獲取test_case目錄

    base_dir=os.path.dirname(func_path)

# print("base_dir is %s" %base_dir)

 

    #將路徑轉化為字符串

    base_dir=str(base_dir)

 

    #對路徑的字符串進行替換

    base_dir=base_dir.replace('\\','/')

    # print(base_dir)

 

 

    #獲取項目文件的根目錄路徑

    base=base_dir.split('/Website')[0]

    # print(base)

 

    #指定截圖存放路徑

    filepath=base+'/Website/test_report/screenshot/'+filename

    # print(filepath)

    driver.get_screenshot_as_file(filepath)

 

#查找最新的測試報告

def latest_report(report_dir):

    lists = os.listdir(report_dir)

    # print(lists)

 

    lists.sort(key=lambda fn: os.path.getatime(report_dir + '\\' + fn))

 

    # print("the latest report is " + lists[-1])

 

    file = os.path.join(report_dir, lists[-1])

    # print(file)

    return file

 

#將測試報告發送到郵件

def send_mail(latest_report):

    f=open(latest_report,'rb')

    mail_content=f.read()

    f.close()

 

    smtpserver = 'smtp.163.com'

 

    user = 'yuexiaolu2015@163.com'

    password = '...'

 

    sender = 'yuexiaolu2015@163.com'

    receives = ['yuexiaolu2015@126.com', 'yuexiaolu2015@sina.com']

 

    subject = 'Web Selenium 自動化測試報告'

 

    msg = MIMEText(mail_content, 'html', 'utf-8')

    msg['Subject'] = Header(subject, 'utf-8')

    msg['From'] = sender

    msg['To'] = ','.join(receives)

 

    smtp = smtplib.SMTP_SSL(smtpserver, 465)

    smtp.helo(smtpserver)

    smtp.ehlo(smtpserver)

    smtp.login(user, password)

 

    print("Start send email...")

    smtp.sendmail(sender, receives, msg.as_string())

    smtp.quit()

    print("Send email end!")

 

 

if __name__ == '__main__':

    driver=webdriver.Firefox()

    driver.get("http://www.sogou.com")

    inser_img(driver,"sogou.png")

    driver.quit()

 

 

 

 

 

 

Pageobject頁面對象封裝

BasePage.py —— 基礎頁面類

from  time import sleep
 
class Page():
 
    def __init__(self,driver):
        self.driver=driver
        self.base_url="http://localhost"
        self.timeout=20
 
    def _open(self,url):
        url_=self.base_url+url
        print('Test page is:%s' %url_)
        self.driver.maximize_window()
        self.driver.get(url_)
        sleep(2)
        assert self.driver.current_url == url_, 'Did ont land on %s' % url_
 
    def open(self):
        self._open(self.url)
 
    def find_element(self,*loc):
        return self.driver.find_element(*loc)

 

 

 

LoginPage.py —— 新聞登錄頁面

from  PageBase import *
from selenium import webdriver
from  selenium.webdriver.common.by import By
 
class LoginPage(Page):
    '''新聞登錄頁面'''
    url = '/news/'
 
    # 定位器——對相關元素進行定位
    username_loc = (By.NAME, 'username')
    password_loc = (By.NAME, 'password')
    submit_loc = (By.NAME, 'Submit')
 
 
    def type_username(self, username):
        self.find_element(*self.username_loc).clear()
        self.find_element(*self.username_loc).send_keys(username)
 
    def type_password(self, password):
        self.find_element(*self.password_loc).clear()
        self.find_element(*self.password_loc).send_keys(password)
 
    def type_submit(self):
        self.find_element(*self.submit_loc).click()
 
 
 
    def Login_action(self,username,password):
        self.open()
        self.type_username(username)
        self.type_password(password)
        self.type_submit()
 
 
    LoginPass_loc = (By.LINK_TEXT, '我的空間')
    loginFail_loc = (By.NAME, 'username')
 
    def type_loginPass_hint(self):
        return self.find_element(*self.LoginPass_loc).text
 
 
    def type_loginFail_hint(self):
        return self.find_element(*self.loginFail_loc).text

 

test_login.py ——unittest組織測試用例

  • 用戶名密碼正確點擊登錄
  • 用戶名正確,密碼錯誤點擊登錄
  • 用戶名和密碼為空點擊登錄

import unittest

from model import function,myunit

from page_object.LoginPage import *

from time import sleep

 

class LoginTest(myunit.StartEnd):

    # @unittest.skip('skip this case')

    def test_login1_normal(self):

        '''username password is normal'''

        print("test_login1_normal is start run...")

        po=LoginPage(self.driver)

        po.Login_action('51zxw',123456)

        sleep(3)

 

        #斷言與截屏

        self.assertEqual(po.type_loginPass_hint(),'我的空間')

        function.insert_img(self.driver,"51zxw_login1_normal.jpg")

        print("test_login1_normal is test end!")

 

 

    def test_login2_PasswdError(self):

        '''username is ok,passwd is error!'''

        print("test_login2_PasswdError is start run...")

        po=LoginPage(self.driver)

        po.Login_action("51zxw",12342)

        sleep(2)

 

        self.assertEqual(po.type_loginFail_hint(),'')

        function.insert_img(self.driver,"51zxw_login2_fail.jpg")

        print("test_login2_PasswdError is test end!")

    #

    # @unittest.skip

    def test_login3_empty(self):

        '''username password is empty'''

        print("test_login3_empty is start run...")

        po=LoginPage(self.driver)

        po.Login_action('','')

        sleep(2)

 

        #斷言與截屏

        self.assertEqual(po.type_loginFail_hint(),'')

        function.insert_img(self.driver,"51zxw_login3_empty.jpg")

        print("test_login3_empty is test end!")

 

if __name__ == '__main__':

    unittest.main()

 

run_test.py——執行測試用例

import unittest

from  function import *

from BSTestRunner import BSTestRunner

import time

 

report_dir = './test_report'

test_dir = './test_case'

 

print("start run testcase...")

discover = unittest.defaultTestLoader.discover(test_dir, pattern="test_login.py")

now = time.strftime("%Y-%m-%d %H_%M_%S")

report_name = report_dir + '/' + now + 'result.html'

 

print("start write report...")

# 運行前記得把BSTestRunner.py 120‘unicode’ 換成‘str’

with open(report_name, 'wb') as f:

    runner = BSTestRunner(stream=f, title="Test Report", description="localhost login test")

    runner.run(discover)

f.close()

 

print("find latest report...")

# 查找最新的測試報告

latest_report = latest_report(report_dir)

# 郵件發送報告

 

print("send email report...")

send_mail(latest_report)

print("test end!")

 

瀏覽器內核

Webkit:目前最主流的瀏覽器內核,webkit是蘋果公司開源的瀏覽器內核,其前身是KHTML。基於Webkit的瀏覽器很多,比如Safari,Chrome,Opera

Gecko:是Firefox瀏覽器的內核

Trident:是IE瀏覽器的內核

Blink:是webkit的一個分支版本,由google開發

無頭瀏覽器

無頭瀏覽器即headless browser,是一種沒有界面的瀏覽器。既然是瀏覽器那么瀏覽器該有的東西它都應該有,只是看不到界面而已。

PhantomJS

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

 

PhantomJS可以說是目前使用最為廣泛,也是最被認可的無頭瀏覽器。由於采用的是Webkit內核,因此其和目前的Safari,Chrome等瀏覽器兼容性十分好。

為什么要使用PhantomJS?

PhantomJS 是一個無界面, 基於Webkit 的javascript 引擎. 一般來說我們的自動化腳本是須要運行在服務器上的, 往往這個時候系統並沒有圖形界面(如liunx服務器), 或者配置太低跑個瀏覽器實在是浪費. 而不需要圖形界面的 PhantomJS 可謂是我們的不二之選.

PhantomJS安裝配置

下載地址:http://phantomjs.org/download.html

下載完成后將phantomjs.exe文件放置Python安裝目錄即可。

運行使用

driver=webdriver.PhantomJS()

 

參考文檔

http://www.cnblogs.com/diaosicai/p/6370321.html

http://blog.csdn.net/xtuhcy/article/details/52814210?locationNum=5


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM