当前位置: 首页 > news >正文

unittest、nosetest、pytest

参考:Choosing The Perfect Python Testing Framework: Unittest Vs. Pytest Vs.

UnitTest vs Nose2 vs Pytest

FeatureUnittest   Pytest Nose2
Test DiscoveryYesYesYes
Fixture SupportYesYesYes
ParameterizationNoYesYes
Plugin EcosystemLimitedExtensiveLimited
Test Naming ConventionClass/MethodFunctionClass/Method
Assertion MethodsYesYesYes
ConfigurationManual AutomaticAutomatic

Unittest: The Built-in Testing Framework

Unittest is a built-in testing framework in Python, inspired by the testing frameworks available in other programming languages like Java.

It follows a traditional xUnit-style approach, where tests are organized into classes and methods. Unittest provides a rich set of assertion methods to validate the expected behavior of code.

Key Features of Unittest
  • Supports test automation and discovery
  • Provides a rich set of assertion methods for accurate test validation
  • Enables test case customization through subclassing
  • Supports fixtures for test setup and teardown
  • Generates test reports and statistics
  • Integrates with other testing tools and libraries

Pytest: The Powerful and Flexible Testing Framework

Now let’s talk about Pytest, another popular testing framework that developers adore for its simplicity. Pytest takes a more flexible and intuitive approach compared to Unittest. Its main goal is to make testing easy and straightforward.

Unlike Unittest, you don’t have to write test classes with Pytest. Instead, you can write simple test functions, just like jotting down your tests on sticky notes.

Pytest also embraces the principle of “convention over configuration” and offers powerful features such as fixtures, parameterization, and advanced test selection.

By leveraging Pytest, developers can focus on writing tests without being overwhelmed by complex setup and configurations. It’s all about making testing a breeze!

Key Features of Pytest
  • Supports test discovery and execution without the need for boilerplate code
  • Offers a wide range of powerful plugins for extended functionality
  • Simplifies test writing with intuitive and expressive syntax
  • Provides fixtures for test setup and teardown
  • Supports parallel test execution
  • Generates detailed test reports and code coverage analysis
pytest具有很多第三方插件

并且可以自定义扩展:如pytest-selenium(集成selenium)、pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CPU分发)、pytest--ordering(控制测试运行的顺序);

测试用例的skip和xfail处理 

运行后生成测试报告(htmlReport)

安装pytest-html:

pip install -U pytest-html

如何使用:

py.test test_pyexample.py --html=report.html
更详细的测试报告

安装 pytest-cov:

pip install pytest-cov 

如何使用

py.test --cov-report=html --cov=./ test_code_target_dir
Console参数介绍
--cov=[path], measure coverage for filesystem path (multi-allowed), 指定被测试对象,用于计算测试覆盖率
--cov-report=type, type of report to generate: term, term-missing, annotate, html, xml (multi-allowed), 测试报告的类型
--cov-config=path, config file for coverage, default: .coveragerc, coverage配置文件
--no-cov-on-fail, do not report coverage if test run fails, default: False,如果测试失败,不生成测试报告
--cov-fail-under=MIN, Fail if the total coverage is less than MIN. 如果测试覆盖率低于MIN,则认为失败
多进程运行

安装pytest-xdist:

pip install -U pytest-xdist

如何使用:

py.test test_pyexample.py -n NUM

其中NUM填写并发的进程数。

1个case扩展参数 
import pytest@pytest.mark.parametrize("test_input,expected",[("3+5",8),("2+5",7),("7*5",30)])
def test_eval(self,test_input, expected):# eval 将字符串str当成有效的表达式来求值,并返回结果assert eval(test_input) == expected

Nose2: The Simplified and Extensible Testing Framework

参考:Note to Users — nose 1.3.7 documentation

Last but not least, let’s talk about Nose2. Nose2 is a testing framework that builds upon Unittest’s foundation. It aims to enhance the test discovery and execution process by providing a more user-friendly interface and additional functionalities.

Nose2 can automatically discover and run your tests, generate detailed reports, and handle test fixtures and plugins efficiently.

Key Features of Nose2
  • Test Discovery: Automatically finds and runs test cases across modules and directories.
  • Test Execution: Runs tests selectively at the case, method, or class level.
  • Test Fixtures: Supports setup and teardown functions/methods for test environment management.
  • Test Runner: Generates detailed reports in various formats (console, XML, HTML).
  • Plugin System: Extensible with plugins for coverage analysis, test isolation, etc.
  • Parallel Execution: Runs tests concurrently for faster execution.
  • Test Configuration: Customizable options for test directories, exclusions, and discovery behavior.

nose执行相关命令
  1. nosetests -h 查看所有nose命令与说明
  2. nosetests  查看是否安装nose成功
  3. nosetests -with-xunit输出xml结果报告
  4. nosetests -v 查看运行信息和调试信息,例如会给出当前正在运行哪个测试。
  5. nosetests -w 目录:指定一个目录运行测试,目录可以是相对路径或绝对路径。
  6. nosetests -f 执行测试
  7. nosttests -p 查看可用plugins信息
  8. nosetests --tests=NAMES 执行这些测试
  9. nosetests -s,不捕获输出,会让你的程序里面的一些命令行上的输出显示出来。例如print所输出的内容。

  10. nosetests -a: -a myTag TestClass

from nose.plugins.attrib import attr@attr(myTag='main')def test_func2(self):print ("this is test_func2")
1个case扩展参数 
from nose.plugins.attrib import attr
from parameterized import parameterized, parameterized_class@parameterized.expand([(a)(b)(c)])@attr(myTag='main')def test_func2(self, param):print ("this is test_func2 " + param)

相关文章:

  • 【Tomcat与网络4】Tomcat的连接器设计
  • CSC联合培养博士申请亲历|联系外导的详细过程
  • 栈的应用:括号匹配问题_有效的括号
  • 防御保护---防火墙的智能选路
  • 机器学习入门-----sklearn
  • 《幻兽帕鲁》好玩吗?幻兽帕鲁能在Mac上运行吗?
  • torch训练简单例子
  • C语言入门到精通之练习37:输入3个数a,b,c,按大小顺序输出。
  • AES加密原理
  • LeetCode 每日一题 2024/1/29-2024/2/4
  • 突破编程_C++_面试(基础知识(5))
  • 正点原子--STM32定时器学习笔记(2)
  • CSS Day11- 动画
  • Redis抓取数据到Logstash再推到Elasticsearch集群
  • 【Linux Day15 TCP网络通讯】
  • 03Go 类型总结
  • Codepen 每日精选(2018-3-25)
  • ES6 学习笔记(一)let,const和解构赋值
  • HTTP请求重发
  • JAVA之继承和多态
  • linux学习笔记
  • Netty 4.1 源代码学习:线程模型
  • Netty+SpringBoot+FastDFS+Html5实现聊天App(六)
  • NLPIR语义挖掘平台推动行业大数据应用服务
  • Redis 懒删除(lazy free)简史
  • Storybook 5.0正式发布:有史以来变化最大的版本\n
  • 半理解系列--Promise的进化史
  • 开发基于以太坊智能合约的DApp
  • 你不可错过的前端面试题(一)
  • 腾讯优测优分享 | 你是否体验过Android手机插入耳机后仍外放的尴尬?
  • 小程序、APP Store 需要的 SSL 证书是个什么东西?
  • 一个完整Java Web项目背后的密码
  • 移动端解决方案学习记录
  • 阿里云ACE认证学习知识点梳理
  • 我们雇佣了一只大猴子...
  • ​软考-高级-系统架构设计师教程(清华第2版)【第15章 面向服务架构设计理论与实践(P527~554)-思维导图】​
  • # Panda3d 碰撞检测系统介绍
  • #经典论文 异质山坡的物理模型 2 有效导水率
  • (09)Hive——CTE 公共表达式
  • (cljs/run-at (JSVM. :browser) 搭建刚好可用的开发环境!)
  • (翻译)Entity Framework技巧系列之七 - Tip 26 – 28
  • (九)信息融合方式简介
  • (一)Linux+Windows下安装ffmpeg
  • ***linux下安装xampp,XAMPP目录结构(阿里云安装xampp)
  • .NET 4.0网络开发入门之旅-- 我在“网” 中央(下)
  • .net MVC中使用angularJs刷新页面数据列表
  • .NET 的程序集加载上下文
  • .Net 中的反射(动态创建类型实例) - Part.4(转自http://www.tracefact.net/CLR-and-Framework/Reflection-Part4.aspx)...
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例
  • .Net调用Java编写的WebServices返回值为Null的解决方法(SoapUI工具测试有返回值)
  • /dev/sda2 is mounted; will not make a filesystem here!
  • /etc/motd and /etc/issue
  • @Autowired自动装配
  • @RequestParam,@RequestBody和@PathVariable 区别
  • @Transactional类内部访问失效原因详解