[Python Modules] unittest.mock
五夜光寒,照来积雪平于栈。西风何限,自起披衣看。
对此茫茫,不觉成长叹。何时旦,晓星欲散,飞起平沙雁。
在某个Python程序中看到这么一行
from unittest import mock
看起来像是一个Python自带的测试库。经查,unittest.mock
允许用户使用假的对象代替系统的真实对象。mock库中常用的是MagicMock, Mock, patch()
:
>>> from unittest.mock import MagicMock >>> thing = ProductionClass() >>> thing.method = MagicMock(return_value=3) >>> thing.method(3, 4, 5, key='value') 3
可以看出MagicMock
可以改变函数为固定输出。同事可以使用side_effect
参数使得函数具有其他功能,可以实现函数的功能或者报错。
>>> mock = Mock(side_effect=KeyError('foo')) >>> mock() Traceback (most recent call last): ... KeyError: 'foo'
>>> values = {'a': 1, 'b': 2, 'c': 3} >>> def side_effect(arg): ... return values[arg] ... >>> mock.side_effect = side_effect >>> mock('a'), mock('b'), mock('c') (1, 2, 3) >>> mock.side_effect = [5, 4, 3, 2, 1] >>> mock(), mock(), mock() (5, 4, 3)
利用patch()
装饰器可以声明一个测试环境下的类或对象。(到这里我才想到去查一查mock的意思)
A mock object is a dummy implementation for an interface or a class in which you define the output of certain method calls. Mock objects are configured to perform a certain behavior during a test. They typically record the interaction with the system and tests can validate that.
另:在这段程序中mock
的用法是给host程序传参一个虚假的对象
Applicaiton.register_service(mock.Mock())
NAME
unittest
MODULE REFERENCE
https://docs.python.org/3.7/library/unittest
DESCRIPTION
Python unit testing framework.
import unittest class InterArithmeticTestCase(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1+2), 3) self.assertEqual((0+1), 1) if __name__ == '__main__': unittest.main()