python测试框架之nose

勿忘初心2018-12-05 13:32

此文已由作者朱奇授权网易云社区发布。

欢迎访问网易云社区,了解更多网易技术产品运营经验

简介

nose官方网站上对nose的定义很精炼也很准确:nose扩展自unittest,让测试更简单,是python非常好的测试框架,原文如下:

nose is nicer testing for python,nose extends unittest to make testing easier.

nose的优点

  1. 由于扩展与unittest,nose对unnitest能够很好的兼容(优于pytest),这一点很重要。
  2. nose比unittest更容易使用上手

nose安装和使用

安装:

pip install nose

基本使用:

运行指定测试目录:

cd $file_path
nosetests

运行指定测试module:

nosetests only_test_this.py

运行指定测试case:

nosetests /path/to/test/file.py:test_function

运行时使用插件

nosetests –-plugins

其他详细用法见nostests Basic usage

test case

test case目录结构:

  • nose自动搜寻执行nosetests的测试目录下的moudele、package、子目录名
  • 命名规则匹配正则表达式:((?:^|[\b_\.-])[Tt]est以及所有unittest.TestCase 的子类都会被当做测试用例

因此常用的目录结构为:


编写测试

在一个完整的test case中,主要包含3个部分:Test Fixtures、Test functions、Test Data。其中Test Fixtures是nose框架提供的主要功能,剩下的两个是根据实际测试功能编写,因此这里主要介绍Test Fixtures

Test Fixtures

在nose测试框架中setup、teardown被称为Test Fixures,它的主要目的是初始化测试用例,执行测试化用例后,对测试用例执行的结果做后期处理。setup、teardown支持package、module、class、menthod级别使用

  1. package的setup 、teardown:放在__init__.py文件中,在整个测试的运行期间只运行一次
  2. module的setup 、teardown:在整个测试的运行期间只运行一次。
  3. class的setup 、teardown:每个测试方法执行时都会调用
@classmethod
    def setup_class(cls):
        logger.debug("setup_class: mysql connect")
        GetDB = getdb.GetDB('./config.conf', webServer.MYSQL_SENSION)
        cls.conn = GetDB.get_conn()

    @classmethod
    def teardown_class(cls):
        logger.debug("teardown_class: mysql disconnect")
        cls.conn.close()
  1. 测试方法的setup、teardown可以通过with_setup装饰器进行设置
@with_step(start_fuc, end_fuc)
    def test_abnormal_metriclist(self, projectId, namespace, dimensionname):
        mockdata = MetricListGet.MetricListGet()
        mockdata.set_projectId(projectId)
        mockdata.set_namespace(namespace)
        mockdata.set_dimension_name(dimensionname)
        resp = mockdata.get_data()

        if resp.status_code != 400:
            logger.error("test_normal_metriclist failed...")
            assert False


免费领取验证码、内容安全、短信发送、直播点播体验包及云服务器等套餐

更多网易技术、产品、运营经验分享请点击