python测试工具--nose简介

来源:互联网 发布:seo推广服务公司 编辑:程序博客网 时间:2024/05/19 03:41

查了查资料,就这篇说的比较浅显易懂~

转自:http://blog.csdn.net/lynn_kong/article/details/9445383

 

使用python开发的估计都知道unittest,与Java中的JUnit一样,编写测试用例需要遵守一定的规则。而nose继承自unittest,且比unittest更容易使用。

官网:https://nose.readthedocs.org/en/latest/index.html

 

1、安装

同其他python第三方组件一样,你可以尽情使用easy_install或pip,甚至是setuptools(但前提是你已经安装了它们):

easy_install nose,或者

pip install nose,或者

python setup.py install

安装后,nosetests就在你的python安装目录下的Scripts目录中。然后,你就可以使用nose了,就这么简单。

 

2、使用

举例说明,比如我有一个这样的目录:


先不管那个main.py,那个test目录下有一个test.py文件,内容如下,注意,这里没有unittest的任何影子:

  1. def Testfunc():  
  2.     a = 1  
  3.     b = 2  
  4.     assert a == b  

在D:\Temp\test目录中进入命令行,执行nosetests:


一切都是自动发现和执行。

 

当然也可以编码实现测试用例的执行,刚才那个main.py内容如下:

  1. import nose  
  2. nose.main()  

执行之,看到返回结果是一样的:


或者,main.py中的内容也可以是如下:

  1. import nose  
  2. result = nose.run()  
  3. print result  
执行之,看到返回了True或False:



3、说明

nose会自动识别源文件,目录或包中的测试用例。任何符合正则表达式:

  1. (?:^|[b_.-])[Tt]est  

的类、函数、文件或目录,以及TestCase的子类都会被识别并执行。

当然,可以显式的指定文件、模块或函数:

  1. nosetests only_test_this.py  
  2. nosetests test.module  
  3. nosetests another.test:TestCase.test_method  
  4. nosetests a.test:TestCase  
  5. nosetests /path/to/test/file.py:test_function  

如果一个对象包含了__test__属性,如果值不是True,该对象(以及它包含的所有对象)不会被nose发现

之前在nosetests参数选项中的-w,现在已经废弃,就是说,可以在nosetests的参数中直接指定多个目录,以空格分隔。

在测试用例中可以使用assert或raise

同JUnit一样,nose支持setup和teardown函数,在测试用例的前后执行。四种作用域:
1、package。可以在__init__.py中定义,setup方法名可以是setup, setup_package, setUp, or setUpPackage,而teardown方法名可以是teardown, teardown_package, tearDown or tearDownPackage。比如定义数据库的连接和释放。
2、module。在模块内定义setup,setup_module, setUp or setUpModule,和/或teardown,teardown_module, or tearDownModule。
3、class。
4、function。任何符合正则的函数都会被包装成FunctionTestCase,最简单的失败和成功的用例如下:

  1. def test():  
  2.     assert False  
  3. def test():  
  4.     pass  
对于方法来说,最简单的setup和teardown是使用装饰器:
  1. def setup_func():  
  2.     "set up test fixtures"  
  3.   
  4. def teardown_func():  
  5.     "tear down test fixtures"  
  6.  
  7. @with_setup(setup_func, teardown_func)  
  8. def test():  
  9.     "test ..."  

nose.tools提供了一些帮助函数,参见https://nose.readthedocs.org/en/latest/testing_tools.html

 

nose可以与setuptools无缝集成,在setup配置文件中:

  1. setup (  
  2.     #...  
  3.    test_suite = 'nose.collector'  
  4. )  

然后使用python setup.py test或python setup.py nosetests测试。

0 0
原创粉丝点击