下面以一個例子說明nose。
目錄結(jié)構(gòu)如下(foo模塊以及foo的測試代碼):
test@local:~$ tree /tmp/foomodule/
/tmp/foomodule/
|-- foo
| |-- a.py
| |-- b.py
| `-- __init__.py
`-- tests
|-- test_a.py
`-- test_b.py
模塊代碼如下:
# /tmp/foomodule/foo/a.py
def add(a, b):
return a + b
def double(a):
return a * 2
# /tmp/foomodule/foo/b.py
import memcache
class Cache:
def __init__(self, server):
self.cache = memcache.Client([server])
def get(self, name):
return self.cache.get(name)
def set(self, name, value):
return self.cache.set(name, value)
def delete(self, name):
return self.cache.delete(name)
def close(self):
self.cache.disconnect_all()
對應(yīng)的測試代碼:
# /tmp/foomodule/tests/test_a.py
from foo.a import add, double
def test_add():
v = add(10, 20)
assert v == 30
def test_double():
v = double(10)
assert v == 20
# /tmp/foomodule/tests/test_b.py
from foo.b import Cache
class TestCache:
def setUp(self):
self.cache = Cache("127.0.0.1:11211")
self.key = "name"
self.value = "smallfish"
def tearDown(self):
self.cache.close()
def test_00_get(self):
v = self.cache.get(self.key)
assert v == None
def test_01_set(self):
v = self.cache.set(self.key, self.value)
assert v == True
v = self.cache.get(self.key)
assert v == self.value
def test_02_delete(self):
v = self.cache.delete(self.key)
assert v == True
先不解釋姆吭,跑一跑(-v -s選項匠璧,針對當前路徑下tests目錄測試):
test@local:/tmp/foomodule$ nosetests -s -v
test_a.test_add ... ok
test_a.test_double ... ok
test_b.TestCache.test_00_get ... ok
test_b.TestCache.test_01_set ... ok
test_b.TestCache.test_02_delete ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.024s
OK
nosetests會自動進行集成測試衙解。nose默認是對當前目錄下tests目錄進行測試喉前,默認規(guī)則:文件(含有test),函數(shù)(test_開頭)轻专,類(Test開頭)忆矛。
主要使用assert 進行斷言。
更多精彩內(nèi)容请垛,請關(guān)注我的個人博客催训。