使用過一段時間的Robot Framework測試框架,測試之前需要先搭環境,需要安裝的東西很多,這一點個人有些排斥。
每一個測試內容對應一個Test_Case,Robot有自己語法格式,如判斷、循環。實際使用中發現導入自定義Lib莫名報錯,很是頭疼。
腳本編寫完成,可以在UI界面運行,也可以使用命令行pybot + Robot項目運行。
Robot最大的優點,自動生成html格式的測試報告,免去腳本中一大堆測試結果處理、保存動作。缺點上文已描述,需要搭建環境,自定義語法個人很排斥。
於是,這幾天在網上尋找測試報告模板,最終覺得HTMLTestRunner非常不錯。
一、下載、配置
1.下載HTMLTestRunner.py文件:地址http://tungwaiyip.info/software/HTMLTestRunner.html
2.將該文件保存在python安裝路徑下的lib文件夾中。
二、使用
1.基本用法
1.1 import unittest
1.2 定義一個繼承自unittest.TestCase的測試用例類
1.3 定義setUp和tearDown,在每個測試用例前后做一些輔助工作。
1.4 定義測試用例,名字以test開頭。
1.5 一個測試用例應該只測試一個方面,測試目的和測試內容應很明確。主要是調用assertEqual、assertRaises等斷言方法判斷程序執行結果和預期值是否相符。
1.6 調用unittest.main()啟動測試
1.7 如果測試未通過,會輸出相應的錯誤提示。如果測試全部通過則不顯示任何東西,這時可以添加-v參數顯示詳細信息。
2.unittest模塊的常用方法
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b 2.7
assertIsNot(a, b) a is not b 2.7
assertIsNone(x) x is None 2.7
assertIsNotNone(x) x is not None 2.7
assertIn(a, b) a in b 2.7
assertNotIn(a, b) a not in b 2.7
assertIsInstance(a, b) isinstance(a, b) 2.7
assertNotIsInstance(a, b) not isinstance(a, b) 2.7
3.測試用例
#coding:utf-8
import unittest
import time
import random
import HTMLTestRunner
class Test_Class(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
print("test_shuffle")
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
print("test_choice")
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
def sun(self):
self.temp = 5 + 6
print("sun test")
self.assertEqual(self.temp,11)
if __name__ == "__main__":
testsuite = unittest.TestSuite()
# 添加測試用例到測試集中
testsuite.addTest(Test_Class("test_shuffle"))
testsuite.addTest(Test_Class("test_choice"))
testsuite.addTest(Test_Class("test_sample"))
testsuite.addTest(Test_Class("sun"))
# 生成測試報告文件
filename = 'D:\\result.html'
fp = file(filename, 'wb')
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title='測試結果',
description='測試報告.'
)
# runner = unittest.TextTestRunner()
runner.run(testsuite)
運行后測試結果會生成為D:\\result.html 的文件,當然測試結果的文件名稱你可以隨意命名,或者根據時間自動生成。直接打開后就可以看到測試結果。
三、測試報告
四、使用說明
1.test_case中print信息出現在report中,運行批處理窗口沒有打印信息。

2.Python shell中運行同樣如此

但還有一個問題,Python shell中運行時未產生測試報告,測試報告文件大小為0
