一、nose
nose 是一个第三方单元测试框架,它完全兼容 unittest
,并且号称是一个更好用的测试框架。
那么 nose
除了具备 unittest
的所有功能外,还具有哪些优势呢?
1.1 用例编写
用例的编写方式除了编写继承于 unittest.TestCase 的测试类外,还可以编写成没有继承的测试类。比如,写成如下形式也会被 nose
视作一个测试类:
from nose.tools import raises
class TestStringMethods:
def test_upper(self):
assert 'foo'.upper() == 'FOO'
def test_isupper(self):
assert 'FOO'.isupper()
assert not 'Foo'.isupper()
@raises(TypeError)
def test_split(self):
s = 'hello world'
assert s.split() == ['hello', 'world']
# check that s.split fails when the separator is not a string
s.split(2)
复制代码
当然,测试类并没有继承 unittest.TestCase
,将不能使用其内置的各类 assertXXX
方法,进而导致用例出错时无法获得更加详细的上下文信息。(海量免费学习资料,软件测试交流:1140267353 群,还会有同行一起技术交流)
此外,nose
也支持定义函数来作为测试,这给许多简单的测试场景带来很大的便利:
def test_upper():
assert 'foo'.upper() == 'FOO'
复制代码
1.2 用例发现和执行
unittest
所支持的用例发现和执行能力,nose
均支持。 nose
支持用例自动(递归)发现:
- 默认发现当前目录下所有包含
test
的测试用例,但不包括以_
开头的用例- 使用
nosetests
命令
- 使用
- 通过
-w
参数指定要自动发现的目录,-m
参