學習環境: python3.7
nose版本: 1.3.7
一:安裝
直接使用pip安裝即可:
pip install nose
二: 瞭解常用命令行參數
nose相關執行命令:
1、 nosetests –h查看所有nose相關命令
2、 nosetests –s 執行並捕獲輸出 (即將代碼中的print方法信息顯示在屏幕上)
3、 nosetests –with-xunit輸出xml結果報告
4、 nosetests -v: 查看nose的運行信息和調試信息
5、 nosetests -w 目錄:指定一個目錄運行測試
nose 特點:
a) 自動發現測試用例(包含[Tt]est文件以及文件包中包含test的函數)
b) 以test開頭的文件
c) 以test開頭的函數或方法
d) 以Test開頭的類
經過研究發現,nose會自動識別[Tt]est的類、函數、文件或目錄,以及TestCase的子類,匹配成功的包、任何python的源文件都會被當做測試用例,如果文件名不是[Tt]est開頭且類名也不是[Tt]est開頭時,nose將無法正確識別出測試用例。
實例:
文件名爲: TestClass.py
class TestClass(): def setUp(self): print ("MyTestClass setup") def tearDown(self): print ("MyTestClass teardown") def Testfunc1(self): print ("this is Testfunc1") def test_func2(self): print ("this is test_func2") def Testfunc3(self): print ("this is Testfunc3") def test_func4(self): print ("this is test_func4")
命令行下運行: nosetests -s TestClass
運行結果如下:
MyTestClass setup
this is Testfunc1
MyTestClass teardown
.MyTestClass setup
this is Testfunc3
MyTestClass teardown
.MyTestClass setup
this is test_func2
MyTestClass teardown
.MyTestClass setup
this is test_func4
MyTestClass teardown
.
----------------------------------------------------------------------
Ran 4 tests in 0.019s
OK
不加-s參數執行結果如下: nosetests TestClass
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
使用-v參數執行結果如下: nosetests -v TestClass
TestClass.TestClass.Testfunc1 ... ok
TestClass.TestClass.Testfunc3 ... ok
TestClass.TestClass.test_func2 ... ok
TestClass.TestClass.test_func4 ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
如果文件名且類名均不是以[Tt]est開頭,那麼nose將無法識別到測試用例
1、將文件名改爲myClass.py 文件中的類名改成myClass
2、命令行運行 nosetests -s -v myClass 運行結果如下:
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
結果顯示nose並沒有發現測試用例