5、編寫自動化測試指令碼
阿新 • • 發佈:2018-11-08
上面已經對頁面元素進行了封裝,接下來就是動手寫指令碼了。
這裡寫了2個指令碼,直接上程式碼:
1、test_baidu_news.py
# -*- coding:utf-8 -*- import unittest import sys,os from framework.browser_engine import BrowserEngine from pageobjects.home_baidu import Home_Baidu from pageobjects.news_page import News_Page import traceback class test_Baidu_News(unittest.TestCase): defsetUp(self): browser = BrowserEngine() self.driver = browser.getdriver() browser.open_browser() def tearDown(self): test_method_name = self._testMethodName runlog_path = r'F:\python_autotest\runlog' os.chdir(runlog_path) method_path = runlog_path + test_method_name print(method_path) if sys.exc_info()[0]: if os.path.exists(method_path): os.chdir(method_path) self.driver.get_screenshot_as_file('fail.png') with open('log.txt', 'w') as e: e.write(str(traceback.format_exc())) else: os.mkdir(test_method_name) os.chdir(test_method_name) self.driver.get_screenshot_as_file('fail.png') with open('log.txt', 'w') as e: e.write(str(traceback.format_exc())) super(test_Baidu_News, self).tearDown() self.driver.quit() def test_news_zhaolei(self): hb = Home_Baidu(self.driver) hb.news_ele().click() hb.sleep(1) np = News_Page(self.driver) np.news_input_ele().send_keys(u"趙雷") np.news_submit_ele().click() hb.sleep(2) if __name__ == '__main__': unittest.main()
這裡的重點在於tearDown方法,我增加了指令碼執行失敗自動截圖並打印出錯誤資訊的功能,用於指令碼失敗原因定位。
這裡多說下,測試用例最好都以test_開頭,因為涉及到後面批量執行指令碼,具體原因自行百度。
下面把另一個指令碼的程式碼也貼出來吧,其實是一樣的。
2、test_baidu_vedio.py
# -*- coding:utf-8 -*- import unittest import sys import os import traceback from framework.browser_engine import BrowserEngine from pageobjects.home_baidu import Home_Baidu from pageobjects.vedio_page import Vedio_Page class test_baidu_vedio(unittest.TestCase): def setUp(self): browser = BrowserEngine() self.driver = browser.getdriver() browser.open_browser() def tearDown(self): test_method_name = self._testMethodName runlog_path = r'F:\python_autotest\runlog' os.chdir(runlog_path) method_path = runlog_path + test_method_name print(method_path) if sys.exc_info()[0]: if os.path.exists(method_path): os.chdir(method_path) self.driver.get_screenshot_as_file('fail.png') with open('log.txt','w') as e: e.write(str(traceback.format_exc())) else: os.mkdir(test_method_name) os.chdir(test_method_name) self.driver.get_screenshot_as_file('fail.png') with open('log.txt', 'w') as e: e.write(str(traceback.format_exc())) super(test_baidu_vedio, self).tearDown() self.driver.quit() def test_vedio_zhoujielun(self): hb = Home_Baidu(self.driver) hb.vedio_ele().click() hb.sleep(1) vp = Vedio_Page(self.driver) vp.vedio_input_ele().send_keys(u"周杰倫") vp.vedio_submit_ele().click() vp.sleep(2) if __name__ == '__main__': unittest.main()