python學習筆記9-單元測試unittest

來源:互聯網
上載者:User

標籤:很多   open   erb   img   技術分享   日期   單元測試   學習筆記   self   

Python中有一個內建的單元測試架構是unittest模組,用它來做單元測試,它裡面封裝好了一些校正返回的結果方法和一些用例執行前的初始化操作。

在說unittest之前,先說幾個概念:

TestCase 也就是測試案例

TestSuite 多個測試案例集合在一起,就是TestSuite

TestLoader是用來載入TestCase到TestSuite中的

TestRunner是來執行測試案例的,測試的結果會儲存到TestResult執行個體中,包括運行了多少測試案例,成功了多少,失敗了多少等資訊

下面寫一個簡單的單元測試用例

import unittestfrom BeautifulReport  import BeautifulReportdef calc(x,y):    return x+yclass TestCalc(unittest.TestCase):    def test_pass_case(self):   #用例一定要以test開頭        print(‘這個通過用例‘)        res=calc(1,2)        self.assertEqual(3,res)    def setUp(self):#執行每個用例前的操作        print(‘我是setup..‘)    def tearDown(self):#執行每個用例後的操作        print(‘我是teardown‘)    @classmethod    def setUpClass(cls):        print(‘我是setupclass‘)    @classmethod    def tearDownClass(cls):        print(‘我是teardownclass‘)    def test_a(self):        print(‘a‘)    def test_fail_case(self):        print(‘這是失敗的測試案例‘)        res=calc(9,8)        self.assertEqual(98,res)if __name__==‘__main__‘:    #unittest.main() #單獨執行這個類中的case    # suite=unittest.TestSuite()    # suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCalc))    # runner = unittest.TextTestRunner(verbosity=2)    # runner.run(suite)    suite = unittest.TestSuite()    suite.addTests(unittest.makeSuite(TestCalc))#這個類裡面的所有測試案例    result=BeautifulReport(suite)    result.report(filename=‘測試報告‘,description=‘描述‘,log_path=‘.‘)

一些常見的斷言:

        assertEqual(a, b)     a == b              assertNotEqual(a, b)     a != b              assertTrue(x)     bool(x) is True              assertFalse(x)     bool(x) is False              assertIsNone(x)     x is None             assertIsNotNone(x)     x is not None           assertIn(a, b)     a in b            assertNotIn(a, b)     a not in b

那如何產生一個測試報告呢,需要加入另外一個模組了,HTMLTestRunner,這個模組需要自己安裝,使用執行測試案例就會產生一個html的測試報告,裡面會有每個測試案例的執行結果,代碼如下:

        import HTMLTestRunner                import unittest        class MyTest(unittest.TestCase):#繼承unittest.TestCase            def tearDown(self):                #每個測試案例執行之後做操作                print(‘111‘)            def setUp(self):                #每個測試案例執行之前做操作                print(22222)            def test_run(self):                # self.assertEqual(1,1)                self.assertIs(1,1)                #測試案例            def test_run2(self):                # self.assertEqual(1,1)                self.assertIs(1,1)                #測試案例            def test_run3(self):                # self.assertEqual(1,1)                self.assertIs(1,1)                #測試案例            def test_run1(self):                # self.assertEqual(1,1)                self.assertIs(1,1)                #測試案例        if __name__ == ‘__main__‘:            test_suite = unittest.TestSuite()#建立一個測試集合            test_suite.addTest(MyTest(‘test_run1‘))#測試套件中添加測試案例            #test_suite.addTest(unittest.makeSuite(MyTest))#使用makeSuite方法添加所有的測試方法            fp = open(‘res.html‘,‘wb‘)#開啟一個儲存結果的html檔案            runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=‘api測試報告‘,description=‘測試情況‘)            #產生執行用例的對象            runner.run(test_suite)            #執行測試套件

如果我們有很多個模組,每個模組下面都寫了很多python檔案,每個python檔案裡面都有測試案例,那怎麼把這個目錄下的用例都執行了呢,就要先找到這個目錄下的所有python檔案,然後找到裡面的測試案例,逐個執行,代碼如下:

        import unittest,HTMLTestRunner        suite = unittest.TestSuite()#建立測試套件        all_cases = unittest.defaultTestLoader.discover(‘.‘,‘test_*.py‘)        #找到某個目錄下所有的以test開頭的Python檔案裡面的測試案例        for case in all_cases:            suite.addTests(case)#把所有的測試案例添加進來        fp = open(‘res.html‘,‘wb‘)        runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=‘all_tests‘,description=‘所有測試情況‘)        runner.run(suite)        #運行測試

我們在後續進行持續整合的時候,要讓代碼自動運行,就會用到Jenkins了,但是上面產生的測試報告都是html格式的,Jenkins不認識,就在Jenkins裡面顯示不出來。那咱們就要產生一些Jenkins認識的測試報告,Jenkins認識xml格式的報告,那咱們就產生xml格式的唄,就需要用一個新的模組,xmlrunner,安裝直接 pip install xmlrunner即可,代碼如下:

import unittestimport xmlrunner#匯入這個模組class My(unittest.TestCase):     def test1(self,a,b,c):        self.assertEqual(a+b,c) if __name__==‘__main__‘:    test_suite = unittest.TestSuite()    test_suite.addTest(unittest.makeSuite(My))    runner = xmlrunner.XMLTestRunner(output=‘report‘)#指定報告放的目錄    runner.run(test_suite)

然後咱們運行,可以看到在report目錄下已經產生了xml格式的報告了,而且還自動把日期加上了

  

  

  

  

  

python學習筆記9-單元測試unittest

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.