一、目的
现阶段接口测试所使用的unittest单元测试框架,编写用例复杂,执行用例时灵活性不高,无法满足测试需求,且二次开发工作量大,存在未知风险,故调研Python现有的其他测试框架,已满足需要。
二、范围
Unittest单元测试框架
Pytes单元测试框架
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的作用域:function、module、session ,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的使用,并结合接口自动化测试为例子讲解。
原文:https://www.cnblogs.com/wls-test/p/12601717.html