Python代碼覆蓋率工具coverage.py其實是一個第三方的包,同時支持Python2和Python3版本。
安裝也非常簡單,直接運行:
pip install coverage
首先我們編寫一個簡易計算器的程序:
# mymath.py def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(numerator, denominator): return float(numerator) / denominator
接着來編寫基於unittest的單元測試用例:
# test_mymath.py import mymath import unittest class TestAdd(unittest.TestCase): """ Test the add function from the mymath library """ def test_add_integers(self): """ Test that the addition of two integers returns the correct total """ result = mymath.add(1, 2) self.assertEqual(result, 3) def test_add_floats(self): """ Test that the addition of two floats returns the correct result """ result = mymath.add(10.5, 2) self.assertEqual(result, 12.5) def test_add_strings(self): """ Test the addition of two strings returns the two string as one concatenated string """ result = mymath.add('abc', 'def') self.assertEqual(result, 'abcdef') if __name__ == '__main__': unittest.main()
下面打開CMD命令窗口並進入代碼文件所在目錄。
1.使用coverage命令運行測試用例
coverage run test_mymath.py
2.生成覆蓋率報告
coverage report -m
-m參數表示顯示有哪些行沒有被覆蓋。
可以看到計算器程序mymath.py的測試覆蓋率是62%,其中13,17,21行未運行。
3.生成HTML報告
coverage html
運行后在代碼文件所在目錄生成了htmlcov文件夾,打開index.html查看報告
點擊報告中的mymath.py,可以打開該文件的覆蓋詳情,會飄紅展示哪些代碼未被運行。
因為我們的單元測試代碼只是測試了mymath.add(),所以其他函數里的代碼未被覆蓋,這時就需要我們補充測試用例了。
--------------------------------------------------------------------------------
關注微信公眾號(測試工程師小站)即可在手機上查閱,並可接收更多測試分享,發送【測試資料】更可獲取百G測試教程~