1. 程式人生 > >python+unittest框架整理

python+unittest框架整理

1.單個用例維護在單個.py檔案中可單個執行,也可批量生成元件批量執行

2.對定位引數,定位方法,業務功能指令碼,用例指令碼,用例批量執行指令碼,常用常量進行分層獨立,各自維護在單獨的.py檔案中

3.加入日誌,htlm報表,傳送郵件功能

框架結構

結構說明:

config:配置部分,瀏覽器種類和定位資訊維護在此處

constant:常量部分,固定不變的資料維護在此處

data:存放用於引數化的文字表格等檔案

encapsulation:定位等selenium功能二次封裝在此處

error_picture:存放錯誤截圖

function:業務功能指令碼維護在此處

log:存放log類

report:存放測試報告檔案

test_case:存放用例檔案

all_case.py:用來執行所有用例

debug_case.py:本人除錯用的,可以忽略

tst.log:生成的日誌

逐個介紹各個包下面的.py檔案,並附上原始碼(說明見註釋哈哈~):

複製程式碼

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017-05-11 13:42
 4 # config/config_01.py
 5 from selenium import webdriver
 6 import time
 7 from selenium.webdriver.common.action_chains import *
 8 
 9 
10 # config配置部分
11 
12 # 瀏覽器種類維護在此處
13 browser_config = {
14     'ie': webdriver.Ie,
15     'chrome': webdriver.Chrome
16 }
17 
18 # 定位資訊維護在此處,維護結構由外到內為:頁面名稱--頁面下元素名稱--元素的定位方式+引數
19 locat_config = {
20     '部落格園首頁': {
21         '找找看輸入框': ['id', 'zzk_q'],
22         '找找看按鈕': ['xpath', '//input[@value="找找看"]']
23     }
24 }

複製程式碼

複製程式碼

1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # @Time    : 2017-05-15 13:20
4 # constant/constant_1.py
5 
6 # 常量部分(固定不變使用頻繁的引數維護在此處)
7 LOGIN_URL = 'https://www.cnblogs.com/'

複製程式碼

複製程式碼

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017-05-15 13:20
 4 # encapsulation/encapsulation.py
 5 
 6 # 封裝部分維護在此
 7 
 8 from config.config_01 import locat_config
 9 from log.log import Logger
10 from selenium.webdriver.support.wait import WebDriverWait
11 
12 from selenium.webdriver.support import expected_conditions as EC
13 
14 class UIHandle():
15     logger = Logger()
16 
17     # 構造方法,用來接收selenium的driver物件
18     @classmethod
19     def __init__(cls, driver):
20         cls.driver = driver
21 
22     # 輸入地址
23     @classmethod
24     def get(cls, url):
25         cls.logger.loginfo(url)
26         cls.driver.get(url)
27 
28     # 關閉瀏覽器驅動
29     @classmethod
30     def quit(cls):
31         cls.driver.quit()
32 
33     # element物件(還可加入try,截圖等。。。)
34     @classmethod
35     def element(cls, page, element):
36         # 加入日誌
37         cls.logger.loginfo(page)
38         # 加入隱性等待
39         # 此處便可以傳入config_o1中的dict定位引數
40         el = WebDriverWait(cls.driver, 10).until(EC.presence_of_element_located(locat_config[page][element]))
41         # 加入日誌
42         cls.logger.loginfo(page+'OK')
43         return el
44     # element物件(還未完成。。。)
45     def elements(cls, page, element):
46         # 加入日誌
47         cls.logger.loginfo(page)
48         # 加入隱性等待
49         WebDriverWait(cls.driver, 10)
50         els = cls.driver.find_elements(*locat_config[page][element])
51         # 注意返回的是list
52         return els
53 
54     # send_keys方法
55     @classmethod
56     def Input(cls, page, element, msg):
57         el = cls.element(page, element)
58         el.send_keys(msg)
59 
60     # click方法
61     @classmethod
62     def Click(cls, page, element):
63         el = cls.element(page, element)
64         el.click()

複製程式碼

複製程式碼

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017-05-15 13:22
 4 # function/function_01.py
 5 # 業務功能指令碼(用例指令碼可呼叫此處的功能指令碼)
 6 
 7 from encapsulation.encapsulation import UIHandle
 8 from constant.constant_1 import LOGIN_URL
 9 from config.config_01 import browser_config
10 from time import sleep
11 
12 # 開啟部落格園首頁,進行找找看搜尋功能
13 def search(msg):
14     # 開啟瀏覽器
15     driver = browser_config['chrome']()
16     # 傳入driver物件
17     uihandle = UIHandle(driver)
18     #輸入url地址
19     uihandle.get(LOGIN_URL)
20     # 呼叫二次封裝後的方法,此處可見操作了哪個頁面,哪個元素,msg是要插入的值,插入值得操作在另外一個用例檔案中傳入
21     uihandle.Input('部落格園首頁', '找找看輸入框', msg)
22     uihandle.Click('部落格園首頁', '找找看按鈕')
23     uihandle.quit()

複製程式碼

複製程式碼

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017-05-17 11:19
 4 # log/log.py
 5 
 6 import logging
 7 import logging.handlers
 8 
 9 # 日誌類
10 class Logger():
11     LOG_FILE = 'tst.log'
12 
13     handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024, backupCount = 5) # 例項化handler
14     fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
15 
16     formatter = logging.Formatter(fmt)   # 例項化formatter
17     handler.setFormatter(formatter)      # 為handler新增formatter
18 
19     logger = logging.getLogger('tst')    # 獲取名為tst的logger
20     logger.addHandler(handler)           # 為logger新增handler
21     logger.setLevel(logging.DEBUG)
22     def loginfo(self, message):
23         self.logger.info(message)
24 
25     def logdebug(self, message):
26         self.logger.debug(message)

複製程式碼

複製程式碼

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017-05-15 15:30
 4 # test_case/test_case_1/start_case_01.py
 5 
 6 import unittest
 7 from function.function_01 import *
 8 # 用例
 9 class Case_02(unittest.TestCase):
10     u'''哇塞好玩'''
11     def setUp(self):
12         pass
13 
14     def test_zzk(self):
15         u'''輸入哇塞好玩後點擊找找看'''
16         search("哇塞好玩")
17         print('列印方法名:test_zzk')
18 
19     def tearDown(self):
20         pass
21 
22 if __name__ == "__main__":
23     unittest.main()

複製程式碼

複製程式碼

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2017-05-10 16:34
 4 # all_case.py
 5 
 6 import unittest
 7 import HTMLTestRunner
 8 import time,os,datetime
 9 import smtplib
10 from email.mime.text import MIMEText
11 from email.mime.multipart import MIMEMultipart
12 from email.mime.image import MIMEImage
13 
14 
15 
16 # 取test_case資料夾下所有用例檔案
17 def creatsuitel(lists):
18     testunit = unittest.TestSuite()
19     # discover 方法定義
20     discover = unittest.defaultTestLoader.discover(lists, pattern='start_*.py', top_level_dir=None)
21     #discover 方法篩選出來的用例,迴圈新增到測試套件中
22     for test_suite in discover:
23         for test_case in test_suite:
24             testunit.addTests(test_case)
25             print(testunit)
26     return testunit
27 list_1 = 'test_case\\test_case_1'
28 alltestnames = creatsuitel(list_1)
29 
30 #取前面時間加入到測試報告檔名中
31 now = time.strftime("%Y-%m-%M-%H_%M_%S", time.localtime(time.time()))
32 filename = "report\\"+now+'result.html' #定義個報告存放路徑,支援相對路徑。
33 fp = open(filename, 'wb')
34 runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Report_title', description='Report_description')
35 
36 if __name__ == "__main__":
37     # 執行測試用例集並生成報告
38     runner = unittest.TextTestRunner()

複製程式碼