Pulpcode

捕获,搅碎,拼接,吞咽

0%

使用nose写单元测试

最近也是因为琐事一堆,所以一直都没有更新博客,慢慢会把欠的债都补回来。

这篇博客主要介绍一些如何使用python的 nose来写单元测试,算是介绍nose这个工具,而不是如何去写好一个单元测试。

不用unittest

我很少用unitest,因为1,没有nose好用。2是因为那个一点不像python的风格,能像java

setup和teardown

nose里面有多种可用的setup和teardown

Package级别的

写在init.py文件里包装

1
2
3
4
5
def setup_package():
pass

def teardown_package():
pass

Module级别的

1
2
3
4
5
def setup_module():
pass

def teardown_module():
pass

Class级别的

包装class,所以只执行一次

1
2
3
4
5
6
7
8
9
class TestClass():

@classmethod
def setup_class(cls):
pass

@classmethod
def teardown_class(cls):
pass

当然你是知道在nose中,不需要写类,只写函数可能就足够了,所以直接在一个文件中写:

1
2
3
4
5
6
7
8
9
10
11
def setup():
xxxx

def teardown():
xxxx

def test_xxx():
xxxx

def test_yyy():
xxxx

类似的,也是对整个文件而言

Class 方法级别

包装每一个test方法,所以每一个test函数的前后都会执行。

1
2
3
4
5
6
7
class TestClass():

def setup(self):
pass

def teardown(self):
pass

包装某个函数

1
2
3
4
5
6
7
8
9
10
11
from nose.tools import with_setup

def setup_function():
pass

def teardown_function():
pass

@with_setup(setup_function, teardown_function)
def test_something():
pass

命令行

默认执行的nosetests不会有任何print信息,如下方法可以。

1
nosetests -s  xxx.py

显示详细信息

1
nosetests -v xxx.py

执行用例中的某个函数或者类

1
nosetests xxx:yyy