博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

Python单元测试框架调研

Posted on 2020-03-30 22:15  二灯大师  阅读(252)  评论(0编辑  收藏  举报

一、目的

现阶段接口测试所使用的unittest单元测试框架,编写用例复杂,执行用例时灵活性不高,无法满足测试需求,且二次开发工作量大,存在未知风险,故调研Python现有的其他测试框架,已满足需要。

 

二、范围

Unittest单元测试框架

Pytes单元测试框架

Nose单元测试框架

 

三、框架简述

  • unittest: Python自带,最基础的单元测试框架编写用例有自己固定的格式,复杂插件较少,大部分需要自己手动编写
  • nose: 基于unittest开发,兼容unittest原生测试用例,易用性好,有许多插件
  • pytest基于unittest开发简单的assert语句实现丰富的断言,无需复杂的self.assert*函数,自动识别测试模块和测试函数,兼容unittest和nose测试集,丰富的插件,易用性较好。

 

三、详细功能对比

针对三种框架,根据框架的功能,进行了横向对比,详细数据如下面图1所示

项目

unittest

nose

pytest

执行器

自己写run_all_tests+discover+CommandParser+...

nosetests ...

py.test ...

用例发现Discover

支持

支持

支持

跳过用例

unittest.skip()unittest.skipIf()raise uniitest.SkipTest

from nose.plugins.skip import SkipTestraise SkipTest

@pytest.mark.skipif( condition)@pytest.mark.xfail

Fixtures

setUp/tearDown@classmethodsetUpClass...

支持

@pytest.fixture(session="session", autouse=True)fixture的作用域:functionmodulesession autouse=True使得函数将默认执行

用例标签tags

借助unittest.skip()+comandParser实现

attrib标签from nose.plugins.attrib import attr@attr(speed='slow')def test_big_download(): pass$ nosetests -a speed=slow

@pytest.mark.webtest自定义一个mark,如下,然后 py.test -v -m webtest 只运行标记了webtest的函数, py.test -v -m "not webtest"  来运行未标记webtest

超时机制Timeout

自己实现

from nose.tools import timedimport time@timed(1)def test_lean_5():time.sleep(2)pass

pip install pytest-timeout@pytest.mark.timeout(60)pytest --timeout=300

参数化

结合ddt使用

结合ddt使用

@pytest.mark.parametrize("a,b,expected", testdata)def test_timedistance_v0(a, b, expected):diff = a - bassert diff == expected

报告

HTMLTestRunner

pip install nose-htmloutput--with-html --html-file=

pip install -U pytest-htmlpy.test --html=./report.html

日志log

自己实现

--nologcapture 不使用log--logging-format=FORMAT使用自定义的格式显示日志--logging-datefmt=FORMAT 和上面类类似,多了日期格式--logging-filter=FILTER日志过滤,一般很少用,可以不关注--logging-clear-handlers 也可以不关注--logging-level=DEFAULT log的等级定义

pytest test_add.py --resultlog=./log.txtpytest test_add.py --pastebin=all

只列出用例collect-only

nosetests  --collect-onlynosetests -v --with-id

--collect-only -v

失败用例重跑rerun failures

nosetests -v --failed

pip install -U pytest-rerunfailures@pytest.mark.flaky(reruns=5)py.test --rerun=3

baseline对比

并发

改造unittest使用协程并发,或使用线程池+Beautiful Report

命令行并发

pytest-xdist:分发到不用的cpu或机器上

xml报告

--with-xunit

--xunit-file=... /pytest+Allure

Selenium支持

pytest-selenium


针对三中框架,综合对比数据如图
2所示

 

 

五、总结

总体来说,unittest比较基础,编写和执行灵活性不高,二次开发成本较高,适合需要单独定制功能的项目需求nose是在unittest基础上进行升级优化,但pytest更具有优势,不仅兼容原有unittest代码,强大断言功能,还有更加活跃的社区,众多的插件支持,便于快速扩展,更加方便效率更高。

新手使用入门,可以先从unittest学起,但是想要更灵活,建议使用pytest作为新的测试框架使用。

后面会进一步介绍,pytest的使用和unittest的使用,并结合接口自动化测试为例子讲解。