Menu

  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay
  • Home
  • Work
    • Cloud
      • Virtualization
      • IaaS
      • PaaS
    • Java
    • Go
    • C
    • C++
    • JavaScript
    • PHP
    • Python
    • Architecture
    • Others
      • Assembly
      • Ruby
      • Perl
      • Lua
      • Rust
      • XML
      • Network
      • IoT
      • GIS
      • Algorithm
      • AI
      • Math
      • RE
      • Graphic
    • OS
      • Linux
      • Windows
      • Mac OS X
    • BigData
    • Database
      • MySQL
      • Oracle
    • Mobile
      • Android
      • IOS
    • Web
      • HTML
      • CSS
  • Life
    • Cooking
    • Travel
    • Gardening
  • Gallery
  • Video
  • Music
  • Essay

Python单元测试

16
Oct
2019

Python单元测试

By Alex
/ in Python
/ tags 单元测试
0 Comments
unittest
简介

属于标准库的一部分,类似于JUnit。下面是一个基本的例子:

Python
1
2
3
4
5
6
7
8
9
10
11
12
# 编写测试用例模块
import util        # 被测试模块
import unittest
class TestUtilFunc(unittest.TestCase):
    def setUp(self): pass     # 每个测试函数运行之前
    def tearDown(self): pass  # 每个测试函数运行之后
    def test_indexOf(self):    # 测试用例
        self.assertEqual(0,util.stringutils.indexOf('123','1'))
 
# 运行单元测试
if __name__ == '__main__'
    unittest.main()

从这个例子可以看到:

  1. 测试用例以类的形式进行分组,从 unittest.TestCase继承
  2. 测试方法以 test_开头
  3. unittest支持类似于JUnit的准备/清理机制
  4. 单元测试的入口点均为unittest.main()
  5. unittest.TestCase提供了一系列断言方法
跳过测试

可以在测试类、测试方法上添加装饰器,以便在特定条件下,跳过某些测试:

Python
1
2
3
4
5
6
# 无条件跳过
@unittest.skip("reason")
 
# 条件跳过
@unittest.skipIf( True, "reason" )
@unittest.skipUnless(sys.platform.startswith("win"), "reason") 
命令行
基本用法

你可以运行测试模块、测试类,甚至测试方法:

Shell
1
2
3
4
5
6
7
8
9
# 测试两个模块
python -m unittest test_module1 test_module2
# 测试一个类
python -m unittest test_module.TestClass
# 测试一个方法
python -m unittest test_module.TestClass.test_method
 
# 也可以指定模块的路径
python -m unittest tests/test_something.py
自动搜索用例

如果要自动搜索测试用例,执行: 

Shell
1
2
cd project_directory
python -m unittest discover

要支持自动搜索,测试用例必须编写为模块、或者包,且可以从项目根目录导入。 

默认情况下,仅仅需要命名为 test*.py的文件,可以通过 -p参数修改此行为。

pytest
简介

pytest是第三方框架,和unittest的主要区别是:

  1. 测试模块的文件名必须以 test_开头或 _test结尾
  2. 测试类名必须以 Test开头
  3. 支持模块、类、函数级别的准备/清理方法,unittest仅支持类级别
  4. 不提供断言方法,直接使用assert表达式
  5. 支持失败用例的重跑
安装
Shell
1
pip install -U pytest
示例
第一个用例 
test_sample.py
Python
1
2
3
4
5
6
7
8
# 被测试者
def func(x):
    return x + 1
 
 
def test_answer():
    # 断言
    assert func(3) == 5

运行 pytest即可执行测试。 不带任何参数表示,递归的寻找当前目录下test_*.py和*_test.py文件并执行其中定义的测试。

测试分组

可以将多个测试用例组合为类:

test_class.py
Python
1
2
3
4
5
6
7
8
class TestClass:
    def test_one(self):
        x = "this"
        assert "h" in x
 
    def test_two(self):
        x = "hello"
        assert hasattr(x, "check")

运行 pytest -q test_class.py表示仅仅测试上面这个文件。

断言异常发生
Python
1
2
3
4
5
6
7
8
9
10
11
import pytest
 
 
def f():
    raise SystemExit(1)
 
 
def test_mytest():
    # 断言f()调用会产生SystemExit异常
    with pytest.raises(SystemExit):
        f()
使用fixture

测试方法中的参数tmpdir提示系统,自动为此测试创建一个独特的临时目录。

Python
1
2
3
def test_needsfiles(tmpdir):
    print(tmpdir)
    assert 0
准备/清理

pytest支持不同级别的setup/teardown方法。

模块级别

整个模块仅仅调用一次:

Python
1
2
3
4
5
6
7
8
def setup_module(module):
    """ setup any state specific to the execution of the given module."""
 
 
def teardown_module(module):
    """ teardown any state that was previously setup with a setup_module
    method.
    """
类级别

对于类中的所有测试,调用一次:

Python
1
2
3
4
5
6
7
8
9
10
11
12
@classmethod
def setup_class(cls):
    """ setup any state specific to the execution of the given class (which
    usually contains tests).
    """
 
 
@classmethod
def teardown_class(cls):
    """ teardown any state that was previously setup with a call to
    setup_class.
    """
方法级别

对于每个测试方法,都会调用:

Python
1
2
3
4
5
6
7
8
9
10
def setup_method(self, method):
    """ setup any state tied to the execution of the given method in a
    class.  setup_method is invoked for every test method of a class.
    """
 
 
def teardown_method(self, method):
    """ teardown any state that was previously setup with a setup_method
    call.
    """ 
fixtures

pytest支持fixtures,所谓fixtures是一系列让测试可靠、可重复执行的机制。比起经典的xUnit风格的setup/teardown函数,pytest fixtures具有以下优势:

  1. 每个fixture具有精确的名称,通过在测试函数、模块、类,或者整个项目中声明这些名称即可自动激活
  2. fixture使用模块化设计,每个fixture名称会触发一个fixture函数,此函数本身亦可使用其它fixture
  3. fixture可以在简单的单元测试场景,到复杂的功能测试中使用
  4. 你可以根据配置、组件选项来参数化fixture和测试
  5. 可以跨越函数、类、模块、整个测试会话重用fixture
内置fixture列表
Fixture 说明
cache 返回一个缓存对象,可以跨越多个测试session共享数据:
Python
1
2
3
# key是由 / 分隔的字符串,通常第一部分是你的插件/应用的名称,避免和其它缓存用户冲突
cache.get(key, default)
cache.set(key, value) 
capsys 启用对输出到sys.stdout / sys.stderr中的文本的捕获,调用 capsys.readouterr()返回命名元组 (out ,err)
capsysbinary 类似上面,但是捕获的是byte而非text
tmpdir_factory [session scope] 返回临时目录工厂
tmp_path_factory [session scope] 返回临时路径工厂
tmpdir 返回一个临时目录对象
tmp_path 返回一个临时目录路径对象
注册fixture

Fixture由函数创建,任何函数加上 @pytest.fixture即可创建Fixture:

Python
1
2
3
4
@pytest.fixture
def smtp_connection():
    import smtplib
    return smtplib.SMTP("smtp.gmail.com", 587, timeout=5) 

你可以指定Fixture的共享范围:

Python
1
2
# 可选值 function, class, module, package, session
@pytest.fixture(scope="module") 
作为函数参数

直接将Fixture函数名作为参数,声明在被测试用例的参数列表中,即可使用Fixture: 

Python
1
2
3
def test_ehlo(smtp_connection):
    response, msg = smtp_connection.ehlo()
    assert response == 250 
清理fixture

在你的Fixture函数中使用yield语句,即可自动在Fixture超过作用域范围后自动清理: 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@pytest.fixture(scope="module")
def smtp_connection():
    smtp_connection = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
    # 提供
    yield smtp_connection
    print("teardown smtp")
    # 清理
    smtp_connection.close()
 
 
# 等价形式
@pytest.fixture(scope="module")
def smtp_connection():
    with smtplib.SMTP("smtp.gmail.com", 587, timeout=5) as smtp_connection:
        yield smtp_connection
参数化fixture

使用参数化fixture,可以让所有依赖于此fixture的测试运行多次:

Python
1
2
3
4
5
6
7
8
9
import pytest
import smtplib
 
@pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"])
def smtp_connection(request):
    smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)
    yield smtp_connection
    print("finalizing {}".format(smtp_connection))
    smtp_connection.close()

使用smtp_connection的用例会执行两次,一次连接到stmp服务器smtp.gmail.com,另一次连接到mail.python.org。

读取上下文

为Fixture函数传入 request对象,则可以动态获取当前被测试函数、类、模块的上下文信息:

Python
1
2
3
4
5
6
7
8
9
10
11
12
import pytest
import smtplib
 
 
@pytest.fixture(scope="module")
def smtp_connection(request):
    # 读取被测试模块的smtpserver属性
    server = getattr(request.module, "smtpserver", "smtp.gmail.com")
    smtp_connection = smtplib.SMTP(server, 587, timeout=5)
    yield smtp_connection
    print("finalizing {} ({})".format(smtp_connection, server))
    smtp_connection.close()

被测试模块可以提供stmpserver变量供Fixture读取:

Python
1
2
3
4
smtpserver = "mail.python.org"  # 被Fixture读取
 
def test_showhelo(smtp_connection):
    assert 0, smtp_connection.helo()
Fixture工厂

如果在单个测试中,需要多次得到全新的fixture,可以让Fixture函数返回一个函数而不是值: 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
@pytest.fixture
def make_customer_record():
    def _make_customer_record(name):
        return {"name": name, "orders": []}
    # 此Fixture函数返回一个工厂函数
    return _make_customer_record
 
 
def test_customer_records(make_customer_record):
                 # 可以多次生成fixture
    customer_1 = make_customer_record("Lisa")
    customer_2 = make_customer_record("Mike")
    customer_3 = make_customer_record("Meredith")
在类/模块/项目级别启用

在类级别启用fixture:

Python
1
2
3
4
5
6
7
8
9
@pytest.fixture()
def cleandir():
    newpath = tempfile.mkdtemp()
    os.chdir(newpath)
 
 
# 所有测试都会在一个临时目录下执行
@pytest.mark.usefixtures("cleandir")
class TestDirectoryInit:

支持同时使用多个fixture:

Python
1
@pytest.mark.usefixtures("cleandir", "anotherfixture")
← 2019年10月大明湖畔
利用kind搭建本地K8S集群 →

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Related Posts

  • 使用Mockito进行单元测试
  • Go语言单元测试和仿冒
  • Ginkgo学习笔记
  • 基于Spring Test和Mockito进行单元测试
  • Python并发编程

Recent Posts

  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
  • A Comprehensive Study of Kotlin for Java Developers
  • 背诵营笔记
  • 利用LangChain和语言模型交互
  • 享学营笔记
ABOUT ME

汪震 | Alex Wong

江苏淮安人,现居北京。目前供职于腾讯云,专注容器方向。

GitHub:gmemcc

Git:git.gmem.cc

Email:gmemjunk@gmem.cc@me.com

ABOUT GMEM

绿色记忆是我的个人网站,域名gmem.cc中G是Green的简写,MEM是Memory的简写,CC则是我的小天使彩彩名字的简写。

我在这里记录自己的工作与生活,同时和大家分享一些编程方面的知识。

GMEM HISTORY
v2.00:微风
v1.03:单车旅行
v1.02:夏日版
v1.01:未完成
v0.10:彩虹天堂
v0.01:阳光海岸
MIRROR INFO
Meta
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
Recent Posts
  • Investigating and Solving the Issue of Failed Certificate Request with ZeroSSL and Cert-Manager
    In this blog post, I will walk ...
  • A Comprehensive Study of Kotlin for Java Developers
    Introduction Purpose of the Study Understanding the Mo ...
  • 背诵营笔记
    Day 1 Find Your Greatness 原文 Greatness. It’s just ...
  • 利用LangChain和语言模型交互
    LangChain是什么 从名字上可以看出来,LangChain可以用来构建自然语言处理能力的链条。它是一个库 ...
  • 享学营笔记
    Unit 1 At home Lesson 1 In the ...
  • K8S集群跨云迁移
    要将K8S集群从一个云服务商迁移到另外一个,需要解决以下问题: 各种K8S资源的迁移 工作负载所挂载的数 ...
  • Terraform快速参考
    简介 Terraform用于实现基础设施即代码(infrastructure as code)—— 通过代码( ...
  • 草缸2021
    经过四个多月的努力,我的小小荷兰景到达极致了状态。

  • 编写Kubernetes风格的APIServer
    背景 前段时间接到一个需求做一个工具,工具将在K8S中运行。需求很适合用控制器模式实现,很自然的就基于kube ...
  • 记录一次KeyDB缓慢的定位过程
    环境说明 运行环境 这个问题出现在一套搭建在虚拟机上的Kubernetes 1.18集群上。集群有三个节点: ...
  • eBPF学习笔记
    简介 BPF,即Berkeley Packet Filter,是一个古老的网络封包过滤机制。它允许从用户空间注 ...
  • IPVS模式下ClusterIP泄露宿主机端口的问题
    问题 在一个启用了IPVS模式kube-proxy的K8S集群中,运行着一个Docker Registry服务 ...
  • 念爷爷
      今天是爷爷的头七,十二月七日、阴历十月廿三中午,老人家与世长辞。   九月初,回家看望刚动完手术的爸爸,发

  • 6 杨梅坑

  • liuhuashan
    深圳人才公园的网红景点 —— 流花山

  • 1 2020年10月拈花湾

  • 内核缺陷触发的NodePort服务63秒延迟问题
    现象 我们有一个新创建的TKE 1.3.0集群,使用基于Galaxy + Flannel(VXLAN模式)的容 ...
  • Galaxy学习笔记
    简介 Galaxy是TKEStack的一个网络组件,支持为TKE集群提供Overlay/Underlay容器网 ...
TOPLINKS
  • Zitahli's blue 91 people like this
  • 梦中的婚礼 64 people like this
  • 汪静好 61 people like this
  • 那年我一岁 36 people like this
  • 为了爱 28 people like this
  • 小绿彩 26 people like this
  • 彩虹姐姐的笑脸 24 people like this
  • 杨梅坑 6 people like this
  • 亚龙湾之旅 1 people like this
  • 汪昌博 people like this
  • 2013年11月香山 10 people like this
  • 2013年7月秦皇岛 6 people like this
  • 2013年6月蓟县盘山 5 people like this
  • 2013年2月梅花山 2 people like this
  • 2013年淮阴自贡迎春灯会 3 people like this
  • 2012年镇江金山游 1 people like this
  • 2012年徽杭古道 9 people like this
  • 2011年清明节后扬州行 1 people like this
  • 2008年十一云龙公园 5 people like this
  • 2008年之秋忆 7 people like this
  • 老照片 13 people like this
  • 火一样的六月 16 people like this
  • 发黄的相片 3 people like this
  • Cesium学习笔记 90 people like this
  • IntelliJ IDEA知识集锦 59 people like this
  • 基于Kurento搭建WebRTC服务器 38 people like this
  • Bazel学习笔记 37 people like this
  • PhoneGap学习笔记 32 people like this
  • NaCl学习笔记 32 people like this
  • 使用Oracle Java Mission Control监控JVM运行状态 29 people like this
  • Ceph学习笔记 27 people like this
  • 基于Calico的CNI 27 people like this
Tag Cloud
ActiveMQ AspectJ CDT Ceph Chrome CNI Command Cordova Coroutine CXF Cygwin DNS Docker eBPF Eclipse ExtJS F7 FAQ Groovy Hibernate HTTP IntelliJ IO编程 IPVS JacksonJSON JMS JSON JVM K8S kernel LB libvirt Linux知识 Linux编程 LOG Maven MinGW Mock Monitoring Multimedia MVC MySQL netfs Netty Nginx NIO Node.js NoSQL Oracle PDT PHP Redis RPC Scheduler ServiceMesh SNMP Spring SSL svn Tomcat TSDB Ubuntu WebGL WebRTC WebService WebSocket wxWidgets XDebug XML XPath XRM ZooKeeper 亚龙湾 单元测试 学习笔记 实时处理 并发编程 彩姐 性能剖析 性能调优 文本处理 新特性 架构模式 系统编程 网络编程 视频监控 设计模式 远程调试 配置文件 齐塔莉
Recent Comments
  • qg on Istio中的透明代理问题
  • heao on 基于本地gRPC的Go插件系统
  • 黄豆豆 on Ginkgo学习笔记
  • cloud on OpenStack学习笔记
  • 5dragoncon on Cilium学习笔记
  • Archeb on 重温iptables
  • C/C++编程:WebSocketpp(Linux + Clion + boostAsio) – 源码巴士 on 基于C/C++的WebSocket库
  • jerbin on eBPF学习笔记
  • point on Istio中的透明代理问题
  • G on Istio中的透明代理问题
  • 绿色记忆:Go语言单元测试和仿冒 on Ginkgo学习笔记
  • point on Istio中的透明代理问题
  • 【Maven】maven插件开发实战 – IT汇 on Maven插件开发
  • chenlx on eBPF学习笔记
  • Alex on eBPF学习笔记
  • CFC4N on eBPF学习笔记
  • 李运田 on 念爷爷
  • yongman on 记录一次KeyDB缓慢的定位过程
  • Alex on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • will on Istio中的透明代理问题
  • haolipeng on 基于本地gRPC的Go插件系统
  • 吴杰 on 基于C/C++的WebSocket库
©2005-2025 Gmem.cc | Powered by WordPress | 京ICP备18007345号-2