刚刚学了python,关于nose测试框架和python自带提供的pydoc test的比较:
使用nose框架:
使用nose框架有两种情况,一种是expect the result is true,一种是expect the result is fail
关于nose框架,装test的文件夹必须含有test,py文件名和要进行测试的类,function也是
第一种:使用assert_equal
def test_room():
gold = Room("GoldRoom",
"""This room has gold in it you can grab. There's a
door to the north.""")
assert_equal(gold.name, "GoldRoom")
assert_equal(gold.paths, {})
class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
return self.paths.get(direction, None)
def add_paths(self, paths):
self.paths.update(paths)
结果是:
然后当你期望得到error的时候,配合python的raise函数(相当于java的return一个exception对象):
def test_sentence():
x = [('noun','bear')]
assert_raises(ParserError,parse_verb,x)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
nose的话默认是在debug模式,所以如果有输出的话是不会显示出来的,但是如果你显示地令它处于s状态的话,就会输出:
nose还有一个setup()function and teardown()function,在里面填写你要在测试之前和测试之后进行的操作(感觉有点像aop):
def setup():
print "start"
def test_sentence():
x = [('noun','bear')]
assert_raises(ParserError,parse_verb,x)
def teardown():
print "end!"
(2)现在谈谈关于python内置的doc test:
官网上的文档是这么写的:
"""
This is the "example" module.
The example module supplies one function, factorial(). For example,
>>> factorial(5)
120
"""
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L
It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
在“”“ ”“”之间的内容为调用这个要测试的函数以及预期的结果,如果不成立的话,那么就会出错。
值得注意的是这种相当于插入注释的test方法必须在一开始的头部和function定义之初使用
如果出错的话:
但是如果无措就会无提示
另外还有一种单独文件的使用,其他blog也有,就不讨论了。
(3)与java的junit的对比:
public class test {
@Test
public void test(){
check c = new check();
assert c.name == "aaa";
}
}
java中使用annotation来确定表示这个是可以进行unittest的,总体感觉上来说感觉python的话使用nosetest比较方便,不过这也可能是因为我对junit并不是很熟悉的原因