python单元测试框架-nose

python单元测试框架 nose简介

简介

nose是python单元测试的另一框架,nose可以自动识别继承于unittest.TestCase的测试单元,并执行测试,而且,nose也可以测试非继承于unittest.TestCase的测试单元。nose提供了丰富的API便于编写测试代码。

安装及使用

安装:

1
pip install nose

基本语法:

1
nosetests [options] [(optional) test files or directories]

扩展使用

nose自动收集单元测试,收集它当前工作目录下的源代码文件、目录以及包。任何的源代码文件、目录或者包只要匹配正则表达式,他们就会被自动收集。包的测试收集按照树的层级级别一级一级进行,因此package.tests、package.sub.tests、package.sub.sub2.tests将会被收集。

扩展插件

nose支持多种插件,可完成基本大部分测试需要。nose拥有很多内置的插件帮助进行输出抓取、错误查找、代码覆盖、文档测试(doctest)等等。

命令行执行命令可查看插件:

1
nosetests –plugins

若想查看详细信息,可执行

1
2
nosetests –plugins -v
nosetests –plugins -vv

nose使用

nose使用和unittest类似,unittest的断言,nose.tools中都可以选择使用
使用示例:
unittest:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import unittest

class NoseTest(unittest.TestCase):

def setUp(self):
print("=============setUp===============")

def test_Pass(self):
print("==========begin test=========")
a = 1
b = 2
self.assertTrue(a == b, '断言失败, %a != %a'% (a, b))

def tearDown(self):
print("==============tearDown===============")

if __name__ == '__main__':
unittest.main()

nose:

1
2
3
4
5
6
7
8
9
from nose.tools import eq_
from nose.tools import assert_equal

class noseTest():
a = 1
b = 2
#assert_equal(a, b, '%a != %a'%(a,b))
eq_(a, b)

nose也支持在代码中直接运行nose.main()或者nose.run()这样类似于unittest的方式,但是还是建议在命令行中运行nosetests来执行单元测试
参考示例:

1
2
nosetests -v HandleFrameByPageSource.py:test_handleFrameByPageSource --with-html --html-file=G:\workstation\report\handleframe.html

说明:

1
2
3
4
nosetests -v: 显示详细的运行信息和调试信息
HandleFrameByPageSource.py:test_handleFrameByPageSource :测试对象为该python文件下的test_handleFrameByPageSource类
--with-html :使用html插件,生成标准HTML格式测试报告
--html-file=G:\workstation\report\handleframe.html :测试结果输出为该路径下handleframe.html文件
文章目录
  1. 简介
  2. 安装及使用
  3. 扩展使用
    1. 扩展插件
    2. nose使用
|