Nose是最流行的针对Python的测试库之一, 有很多的网上教程,但都有不全面。我就我自己的摸索,总结一下。


一、你的待测试的模块为:temperature.py

 

def to_celsius(t):
     return (t-32.0)*5.0/9.0 
def above_freezing(t): 
     return t>0

 

二、根据你的程序模块,编写你的测试模块文件。

你的测试模块文件必须以test_开头或是含有test,当运行Nose时,它会自动寻找其名称以"test_"开头的文件。
跟测试模块的名称一样,测试函数的名称也必须以test_开头。

 

三、比如测试模块 test_temperature, 模块中的要测试to_celsius()函数, 可以有各种测试的方法,

 

import nose
from temperature import to_celsius 
def test_freezing():
    assert to_celsius(32) ==0 
def test_boiling():
    assert to_celsius(212) ==100 
def test_roundoff():
    assert to_celsius(100) == 38 
if __name__ == '__main__':
    nose.runmodule()

注意, 要 import nose, 同时也要import temperature, 在以上code中,只是import 了 to_celsius  函数。

 

四、测试temperature模块的above_freezing()函数

 

import nose
frome temperature import above_freezing 
def test_above_freezing():
    assert above_freezing(89.4),'A temperature above freezing.'
    assert not above_freezing(-42),'A temperature below freezing.'
    assert not above_freezing(0),'A temperature at freezing.' 
if __name__ == '__main__':
   nose.runmodule()

 

五、在命令行下执行nosetests 即可

 

 六、更深一步,你可以定义test class, 在test class 中有 setup和teardown

 

setup:在测试用例开始时被执行, teardown:在测试用例结束后被执行

nose在文件中如果找到函数setup, setup_module, setUp 或者setUpModule等,那么会在该模块的所有测试执行之前执行该函数。如果找到函数 teardown,tearDown, teardown_module或者 tearDownModule 等,那么会在该模块所有的测试执行完之后执行该函数。

 

对于上面的代码,nose实际的执行过程是这样的:

setUp()->Testfunc1()->Testfunc2()->tearDown()

 

七、nose常用参数

 

nosetests  –v :debug模式,看到具体执行情况,推荐大家执行时用这个选项, nose会捕获标准输出,调试的print代码默认不会打印。

 

nosetest  –s 可打开output输出,否则全部通过时不打印stdout。

 

默认nosetests会执行所有的case,若想单独只执行一个case,执行nosetest --tests 后跟要测试的文件(nosetests后面直接跟文件名,其实也可以直接运行该case)。

 

nosetests --collect-only -v :不运行程序,只是搜集并输出各个case的名称

 

nosetests -x  :一旦case失败立即停止,不执行后续case

 

-w ,指定一个目录运行测试。目录可以是相对路径或绝对路径