欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python單元測試工具doctest和unittest使用解析

 更新時間:2019年09月02日 09:24:22   作者:gdjlc  
這篇文章主要介紹了Python單元測試工具doctest和unittest使用解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

Python標準庫包含兩個測試工具。

doctest:一個簡單的模塊,為檢查文檔而設(shè)計,但也適合用來編寫單元測試。

unittest:一個通用的測試框架。

一、使用doctest進行單元測試

創(chuàng)建文件mymath.py,內(nèi)容

def square(x):
  '''
  計算平方并返回結(jié)果(下面是單元測試的格式)
  >>> square(2)
  >>> square(3)
  '''
  return x * x
if __name__ == '__main__':
  import doctest,mymath
  doctest.testmod(mymath)

在Sublime Text 3中運行只是提示[Finished in 0.2s]。

在cmd命令下切換到mymath.py所在目錄,運行python mymath.py -v后,有提示測試詳細信息,測試通過。如下圖:

把函數(shù)square里面的return x * x 改成 return x / x。

再次運行python mymath.py -v,提示測試不通過,如下圖:

二、使用unittest進行單元測試

還是用mymath.py測試,內(nèi)容:

def square(x):  
  return x * x

新建單元測試文件test_math.py,內(nèi)容:

import unittest, mymath
class mathTestCase(unittest.TestCase):  
  def test_square(self):    
    self.assertEqual(mymath.square(2), 4)
    self.assertEqual(mymath.square(3), 9)
if __name__ == '__main__':
  unittest.main()

運行后,顯示OK 測試通過。

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

把函數(shù)square里面的return x * x 改成 return x / x。

再次運行,這次顯示FAILED 測試不通過。

F
======================================================================
FAIL: test_square (__main__.mathTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "D:\projects\python\test_math.py", line 6, in test_square
  self.assertEqual(mymath.square(2), 4)
AssertionError: 1.0 != 4

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論