How to supply a mock class method for python unit test?(如何为 python 单元测试提供模拟类方法?)
问题描述
假设我有这样的课程.
class SomeProductionProcess(CustomCachedSingleTon):
@classmethod
def loaddata(cls):
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
现在在测试时,我想更改 loaddata() 方法中的逻辑.这将是一个不处理大数据的简单自定义逻辑.
Now at test time I want to change the logic inside the loaddata() method. It would be a simple custom logic that doesn't process large data.
我们如何使用 Python Mock UnitTest 框架在测试时提供 loaddata() 的自定义实现?
How do we supply custom implementation of loaddata() at testtime using Python Mock UnitTest framework?
推荐答案
这是一个使用mock的简单方法
Here is a simple way to do it using mock
import mock
def new_loaddata(cls, *args, **kwargs):
# Your custom testing override
return 1
def test_SomeProductionProcess():
with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):
obj = SomeProductionProcess()
obj.loaddata() # This will call your mock method
如果可以的话,我建议使用 pytest 而不是 unittest 模块.它使您的测试代码更加简洁,并减少了您使用 unittest.TestCase 样式测试获得的大量样板.
I'd recommend using pytest instead of the unittest module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with unittest.TestCase-style tests.
这篇关于如何为 python 单元测试提供模拟类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为 python 单元测试提供模拟类方法?
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
