python 单元测试框架nose学习笔记一

本文介绍了Python的nose单元测试框架,包括安装、常用命令行参数和其自动发现测试用例的特点。通过示例展示了如何运行测试,强调了以[Tt]est开头的文件和类会被自动识别为测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习环境: python3.7

nose版本: 1.3.7

一:安装

      直接使用pip安装即可:

     pip install nose

二: 了解常用命令行参数

nose相关执行命令:

1、  nosetests  –h查看所有nose相关命令

2、  nosetests –s 执行并捕获输出 (即将代码中的print方法信息显示在屏幕上)

3、  nosetests –with-xunit输出xml结果报告

4、  nosetests -v: 查看nose的运行信息和调试信息 

5、  nosetests -w 目录:指定一个目录运行测试

 

nose 特点:  

a)         自动发现测试用例(包含[Tt]est文件以及文件包中包含test的函数)

b)         以test开头的文件

c)         以test开头的函数或方法

d)         以Test开头的类

经过研究发现,nose会自动识别[Tt]est的类、函数、文件或目录,以及TestCase的子类,匹配成功的包、任何python的源文件都会被当做测试用例,如果文件名不是[Tt]est开头且类名也不是[Tt]est开头时,nose将无法正确识别出测试用例。

实例:

文件名为: TestClass.py

class TestClass():

    def setUp(self):
        print ("MyTestClass setup")

    def tearDown(self):
        print ("MyTestClass teardown")

    def Testfunc1(self):
        print ("this is Testfunc1")

    def test_func2(self):
        print ("this is test_func2")

    def Testfunc3(self):
        print ("this is Testfunc3")

    def test_func4(self):
        print ("this is test_func4")

命令行下运行:  nosetests -s TestClass

运行结果如下:

MyTestClass setup
this is Testfunc1
MyTestClass teardown
.MyTestClass setup
this is Testfunc3
MyTestClass teardown
.MyTestClass setup
this is test_func2
MyTestClass teardown
.MyTestClass setup
this is test_func4
MyTestClass teardown
.
----------------------------------------------------------------------
Ran 4 tests in 0.019s

OK
 

不加-s参数执行结果如下: nosetests  TestClass

....
----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

使用-v参数执行结果如下: nosetests  -v TestClass

TestClass.TestClass.Testfunc1 ... ok
TestClass.TestClass.Testfunc3 ... ok
TestClass.TestClass.test_func2 ... ok
TestClass.TestClass.test_func4 ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

 

如果文件名且类名均不是以[Tt]est开头,那么nose将无法识别到测试用例

1、将文件名改为myClass.py  文件中的类名改成myClass

2、命令行运行 nosetests -s -v myClass 运行结果如下:

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

结果显示nose并没有发现测试用例

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值