看到就是賺到!Selenium完整框架——告別2017


這個框架大家可以拿過去直接用——作為送給大家的元旦禮物——船長對你們簡直太好了!

 

        學了這么長時間,又是定位,又是發郵件,還有亂七八糟的unittest,現在時候后把東西用起來了~而且學會了這一篇你就可以說自己會selenium自動化測試啦~~~看到就是賺到啊!

 

1、新建項目,結構如圖:

 

注意:整個項目除了最外層的是文件夾,其他的都是包(package)。也就是說每一個文件夾下面都是有一個__init__.py文件的。只有包才能順利的用import導入哦~~

 

2、文件介紹及代碼

baseinfo

        這里面只有一個__init__.py文件,里面放的是常量:比如郵件的設置信息、發送的固定URL等。

 


# coding: utf-8

''' 發送郵件參數 '''

Smtp_Server = 'smtp.mxhichina.com'
Smtp_Sender = 'abc@tenez.cn'
Smtp_Sender_Password = '**********'
Smtp_Receiver = ['312652826@qq.com', 'warrior_meng08@163.com']

 

module

        這個包下面有:__init__.py(確定它是包而不是文件夾的文件),getTestcase.py——獲取測試用例文件;getTestResult.py——獲取用例執行結果文件,以及sendEmail.py——發送郵件文件。這個包里放的都是封裝好的方法,也就是說以后我們只需要調用這些方法就可以實現相應的功能了。

         __init__.py

 這個文件里面的內容:

 

# coding: utf-8

import getTestcases
import sendEmail
import getTestResult

 

        正如大家看到的,這里面只有幾個import,這樣寫是為了后面利用from module import * 這種導入方式,如果不在__init__.py里寫這些導入的話,前面的那種導入方式是不能用的。

        getTestcase.py

 

# coding: utf-8

import unittest
import os

def testcaseDir(test_directory):

    ''' os.walk()傳入頂層文件夾路徑,返回三個內容: 1、根路徑; 2、路徑下所有文件夾名; 3、路徑下所有非文件夾名【2,3都是以列表形式返回】 這個是遍歷文件夾,然后遍歷對應文件夾下面的文件 '''

    # for a, b, c in os.walk(test_directory):
    # for dirs in b:
    # test_dir = '%s\\%s' % (test_directory, dirs)
    # test_discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py', top_level_dir=test_dir)
    # return test_discover

    ''' 事實證明加了文件夾也沒關系,但是不能是文件夾,必須是包,也就是你新建的時候必須選package(必須有__init__.py文件) '''

    discover = unittest.defaultTestLoader.discover(test_directory, pattern='test*.py', top_level_dir=test_directory)
    return discover

         這個方法是讀取testcase文件夾(包)【以后說的文件夾其實是包】里面的測試用例。大家也看到了,一開始我建的就是文件夾,然后怎么樣都讀不出testcase文件夾下面的文件夾里面的用例,最后我寫了一個具體的遍歷文件夾的方法,然后去讀用例,最后經人指點,加了__init__.py方法,把文件夾變成了包,瞬間就OK了。

        getTestResult.py    

 

# coding: utf-8

from selenium import webdriver
from time import sleep

def get_result(filename):
    driver = webdriver.Firefox()
    driver.maximize_window()    # 得到測試報告路徑
    result_url = "file://%s" % filename
    driver.get(result_url)
    sleep(3)
    res = driver.find_element_by_xpath("/html/body/div[1]/p[4]").text
    result = res.split(':')
    driver.quit()
    return result[-1]

 

    這個方法是將生成的測試報告對應的測試運行結果拿出來,到時候作為發送郵件的標題發送。

        sendEmail.py

 

# coding: utf-8

import smtplib
import baseinfoimport time
from email.mime.multipart
import MIMEMultipart from email.header import Header from email.mime.text import MIMEText def send_Mail(file_new, result): f = open(file_new, 'rb') # 讀取測試報告正文 mail_body = f.read() f.close() try: smtp = smtplib.SMTP(baseinfo.Smtp_Server, 25) sender = baseinfo.Smtp_Sender password = baseinfo.Smtp_Sender_Password receiver = baseinfo.Smtp_Receiver smtp.login(sender, password) msg = MIMEMultipart() text = MIMEText(mail_body, 'html', 'utf-8') text['Subject'] = Header('UI自動化測試報告', 'utf-8') msg.attach(text) now = time.strftime("%Y-%m-%d") msg['Subject'] = Header('[ 執行結果:' + result + ' ]'+ 'UI自動化測試報告' + now, 'utf-8') msg_file = MIMEText(mail_body, 'html', 'utf-8') msg_file['Content-Type'] = 'application/octet-stream' msg_file["Content-Disposition"] = 'attachment; filename="TestReport.html"' msg.attach(msg_file) msg['From'] = sender msg['To'] = ",".join(receiver) tmp = smtp.sendmail(sender, receiver, msg.as_string()) print tmp smtp.quit() return True except smtplib.SMTPException as e: print(str(e)) return False

 

        發送郵件的方法,說了好多遍了。都是一個道理。

test_report

        testReport_path.py

 

# coding: utf-8

import os

# 獲取當前文件夾路徑

def report_path():
    return os.path.split(os.path.realpath(__file__))[0]

 

testcase

    login

            testLogin1.py【測試用例1】

 

# coding: utf-8

from selenium import webdriver
import timeimport unittest
import baseinfo
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class TestLogin(unittest.TestCase): print '1.這是testLogin1用例打印內容,文件夾login' @ classmethod def setUpClass(self): self.driver = webdriver.Firefox() time.sleep(1) self.driver.maximize_window() @ classmethod def tearDownClass(self): time.sleep(1) self.driver.quit() def test_purchase(self): print(u"因未找到對應元素,測試用例未正常執行!")

 

     testLogin2【測試用例2】

 

# coding: utf-8

import unittest

class testLogin2(unittest.TestCase): def setUp(self): print '2.這是testLogin2文件夾下面的setup方法' def test11(self): return '3.return 方法返回' def testLogin(self): print 222

 

   testcase2

             testBuy.py【測試用例3】

# coding: utf-8

import unittest

class testBuy(unittest.TestCase): print '4.這是testBuy方法,來自testcase2文件夾' def testPrint(self): print '5.這是test_1打印的內容,文件夾是testcase2'

            testSell.py【測試用例4】

# coding: utf-8

print '6.這里只有print--testSell.py文件'

        與login和testcase2文件夾同級文件testcase_path.py

 

# coding: utf-8

import os

# 獲取當前文件夾路徑

def dir_path():
    return os.path.split(os.path.realpath(__file__))[0]

 

runtest.py    

 

# coding: utf-8

import time
from module import *
from testcase import testcase_path
from test_report import testReport_path
from HTMLTestRunner import HTMLTestRunner
if __name__ == '__main__': # 測試用例路徑 test_dir = testcase_path.dir_path() # 測試報告存放路徑 report_dir = testReport_path.report_path() # print report_dir now = time.strftime("%Y-%m-%d") filename = report_dir + '\\report-' + now + '.html' # print filename fp = open(filename, 'wb') runner = HTMLTestRunner(stream=fp, title='UI自動化測試報告', description='用例執行情況') runner.run(getTestcases.testcaseDir(test_dir)) fp.close() result = getTestResult.get_result(filename) print result mail = sendEmail.send_Mail(filename, result) if mail: print(u"郵件發送成功!") else: print(u"郵件發送失敗!")

 

  用例執行這里只有一個方法,其他全是調用module文件夾下面的方法。

大家注意一下我的用例,大家運行,可以看到輸出結果:

        只有1、4、6打印出來了哦,其他的是不會打印的,也就是說你在用例里寫的print是不會打印的,這是因為HTMLTestRunner.py規定的。船長試過自己修改過的可以打印用例里面的print了,但是會返回很多None,也就是說說出里面會有好多紅色的None。如果你能忍受這些None(沒有用),那就用船長修改過的HTMLTestRunner.py文件~~怎么修改船長前面介紹過。

 

        哇,直接可以用的代碼啊!!復制過去就能用的框架,看到就是賺到,花兩天時間就學會一個可以用的Selenium框架啊,純粹的福利啊~~~

 

        2017就要過去了,祝大家新年快樂~~船長在這里祝大家在2018年工作順利、夢想成真!

        感謝大家這么長時間的陪伴~~還有,打賞過船長的朋友在后台回復一下你的QQ號,船長拉你進一個船長的群,只有四個人,不閑聊,只給大家解決問題和發紅包,哈哈~~

        再次感謝大家的陪伴和支持!

 

希望2018善待我們這些努力、善良的人。加油!

 

We deserves!

 

微信公眾號搜索“自動化測試實戰”或掃描下方二維碼添加關注~~~


免責聲明!

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



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