selenium-Python之unittest(一)中我們說到,如何實現多文件、多用例如何通過一個腳本自動順序執行;
本篇博客在上一篇博客基礎上加入功能:將執行記錄由原來的輸出到控制檯轉移到輸出到文件裏面。
使用的測試代碼在selenium-Python之unittest(一)中,鏈接如下:
http://blog.csdn.net/weixin_39568072/article/details/78467293
之前的執行代碼如下:
#encoding=utf-8
from test import test01
from test import test02
import unittest
suite=unittest.TestSuite()
#方法一
# test_cases=[test01.BaiDuTest('test_baidu'),test02.SouGouTest('test_sougou')]
# suite.addTests(test_cases)
#方法二:
suite.addTest(test02.SouGouTest('test_sougou'))
suite.addTest(test01.BaiDuTest('test_baidu'))
if __name__=="__main__":
runner=unittest.TextTestRunner()
runner.run(suite)
這樣,輸出的執行結果是打印在控制檯中的,那麼如果想要把執行結果拿出來打印在文件,比如txt中呢?如何操作呢?見如下代碼:
test02.py代碼有小變動,加入一條斷言,判斷關鍵字是否在頁面:
#encoding=utf-8
import unittest
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
class SouGouTest(unittest.TestCase):
def setUp(self):
self.driver=webdriver.Chrome(executable_path='c:\\Python27\\chromedriver')
self.wait=WebDriverWait(self.driver,10)
print 'SouGouTest Start'
def test_sougou(self):
self.driver.get('https://www.sogou.com/')
sleep(1)
self.wait.until(lambda x:x.find_element("id","query")).send_keys('hello')
sleep(0.5)
self.wait.until(lambda x:x.find_element("id","stb")).click()
sleep(2)
self.assertIn(u"阿金",self.driver.page_source,'阿金not in page_source')
sleep(2)
def tearDown(self):
self.driver.quit()
print "SouGouTest Over"
if __name__=="__main__":
unittest.main()
執行腳本修改成如下:
run_txt.py
#encoding=utf-8
from test import test01
from test import test02
import unittest
suite=unittest.TestSuite()
suite.addTest(test02.SouGouTest('test_sougou'))
suite.addTest(test01.BaiDuTest('test_baidu'))
if __name__=="__main__":
with open('unittestTestReport','a') as fp:
runner=unittest.TextTestRunner(stream=fp,verbosity=2)
runner.run(suite)
執行run_txt.py後在控制檯中打印的執行結果如下:
C:\Python27\python.exe C:/Users/admin/Desktop/test_unittest/test_for_run/run_txt.py
SouGouTest Start
SouGouTest Over
BaiDuTest Start
BaiDuTest Over
Process finished with exit code 0
生成的報告unittestTestReport.txt中打印的執行結果如下:
test_sougou (test.test02.SouGouTest) ... FAIL
test_baidu (test.test01.BaiDuTest) ... ok
======================================================================
FAIL: test_sougou (test.test02.SouGouTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\admin\Desktop\test_unittest\test\test02.py", line 21, in test_sougou
self.assertIn(u"阿金",self.driver.page_source,'阿金not in page_source')
AssertionError: 阿金not in page_source
----------------------------------------------------------------------
Ran 2 tests in 31.469s
FAILED (failures=1)
這樣,測試執行結果就打印到了txt文件中了,而且with open(‘unittestTestReport’,’a’) as fp 中的 a 表示不會沖掉之前的測試執行結果,接着在前面結果後面寫入新的測試執行結果。