python自动化测试框架nose

python除了unittest,还有一款更快捷的nose,nose可以说是对unittest的一种简化吧

但是他不需要unittest那种必须有固有的格式,他只需要文件,类名,方法名等含有test就可以

unittest是需要手动来写discover函数来遍历用例的

  • Name my test modules/files starting with ‘test_’.
  • Name my test functions starting with ‘test_’.
  • Name my test classes starting with ‘Test’.
  • Name my test methods starting with ‘test_’.
  • Make sure all packages with test code have an ‘init.py’ file.

官网地址http://pythontesting.net/framework/nose/nose-introduction/

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

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

def Testfunc():
    a = 1
    b = 2
    assert a == b
在D:Temp	est目录中进入命令行,执行nosetests:

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

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

  1. import nose

  2. nose.main()

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

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


import nose
result = nose.run()
print result

执行之,看到返回了True或False:

3、说明

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

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

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

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

nosetests only_test_this.py
nosetests test.module
nosetests another.test:TestCase.test_method
nosetests a.test:TestCase
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,最简单的失败和成功的用例如下:
def test():
    assert False
def test():
    pass
对于方法来说,最简单的setup和teardown是使用装饰器:
def setup_func():
    "set up test fixtures"
 
def teardown_func():
    "tear down test fixtures"
 
@with_setup(setup_func, teardown_func)
def test():
    "test ..."

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

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

setup (
    #...
   test_suite = 'nose.collector'
然后使用python setup.py test或python setup.py nosetests测试。
关注公众号 海量干货等你
原文地址:https://www.cnblogs.com/sowhat1412/p/12734346.html