selenium-Python之unittest(二)

来源:互联网 发布:软件采购制度 编辑:程序博客网 时间:2024/06/08 15:04

selenium-Python之unittest(一)中我们说到,如何实现多文件、多用例如何通过一个脚本自动顺序执行;
本篇博客在上一篇博客基础上加入功能:将执行记录由原来的输出到控制台转移到输出到文件里面。
使用的测试代码在selenium-Python之unittest(一)中,链接如下:
http://blog.csdn.net/weixin_39568072/article/details/78467293

之前的执行代码如下:

#encoding=utf-8from test import test01from test import test02import unittestsuite=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-8import unittestfrom time import sleepfrom selenium import webdriverfrom selenium.webdriver.support.wait import WebDriverWaitclass 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-8from test import test01from test import test02import unittestsuite=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.pySouGouTest StartSouGouTest OverBaiDuTest StartBaiDuTest OverProcess finished with exit code 0

生成的报告unittestTestReport.txt中打印的执行结果如下:

test_sougou (test.test02.SouGouTest) ... FAILtest_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.469sFAILED (failures=1)

这样,测试执行结果就打印到了txt文件中了,而且with open(‘unittestTestReport’,’a’) as fp 中的 a 表示不会冲掉之前的测试执行结果,接着在前面结果后面写入新的测试执行结果。
这里写图片描述

原创粉丝点击