一, 目的
现阶段接口测试所使用的 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/[email protected] | 支持 | @pytest.fixture(session="session", autouse=True)fixture 的作用域:function、module、session,autouse=True 使得函数将默认执行 |
用例标签 tags | 借助 unittest.skip()+comandParser 实现 | attrib 标签 from nose.plugins.attrib import [email protected](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 [email protected] ed(1)def test_lean_5():time.sleep(2)pass | pip install [email protected] (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 [email protected] (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 的使用, 并结合接口自动化测试为例子讲解.
来源: http://www.bubuko.com/infodetail-3484797.html