广州市天河区工程建设监督网站,wordpress图片主题 瀑布流经典,南昌网站建设工作室,wordpress本地头像文章目录 mock 测试unittest.mockMock类MagicMock类patch装饰器create_autospec函数断言的方法 pytest-mock 使用 mock 测试
在单元测试时#xff0c;有些数据需要依赖其他服务或者不好获取到#xff0c;此时需要使用mock来模拟对应的函数、对象等。 mock模拟数据的python… 文章目录 mock 测试unittest.mockMock类MagicMock类patch装饰器create_autospec函数断言的方法 pytest-mock 使用 mock 测试
在单元测试时有些数据需要依赖其他服务或者不好获取到此时需要使用mock来模拟对应的函数、对象等。 mock模拟数据的python框架 unittest.mock 标准模块有基于此的mock扩展包 faker 生成假数据 pytest-mock, 扩展模块 mock 作用
解决web开发中后端接口不存在时使用mock模拟数据返回依赖第三方接口时 mock模拟返回demo 演示效果
unittest.mock
Mock类
核心类Mock基类可以创建属性、方法并存储如何被调用Mock实例化的参数 spec, 字符串列表或者对象dir获取对象的属性名称表示该Mock对象可以访问的属性访问不在列表中的属性时报错AttributeError;spec_set属于spec的严格变体使用方法类似side_effect, 调用Mock对象时执行的函数常用引发异常或者动态改变函数的返回值; 如果是可迭代对象则每次调用Mock对象都获取一个值return_value, 指定调用Mock对象的返回值wraps包裹的函数Mock对象的调用实际是包裹函数的调用并返回类似side_effectname, Mock对象的名称 使用方法 from unittest.mock import Mock
class Lauf:def __init__(self, name, age):self.name nameself.age age# 创建对象
lauf Lauf(jack, 25)
mock_obj Mock(speclauf) # mock对象具有lauf的属性、方法可以进行属性赋值
mock_obj.name lili# side_effect 用于引发异常
mock Mock(side_effectKeyError(foo))
mock()
# 抛出异常
KeyError: foo
mock.side_effect 可重新赋值# side_effect 用于执行函数动作
m4 Mock(side_effectlambda: print(执行函数))
m4()
执行函数
m4.mock_calls # 查看调用记录# return_value 直接指定返回值
In [58]: m5 Mock(return_valuejack)
In [59]: m5()
Out[59]: jack# wraps 包裹
In [67]: def func():...: print(func is running...)...: In [68]: m8 Mock(wrapsfunc)
In [69]: m8()
func is running...
MagicMock类
MagicMock是 Mock的子类默认实现了大部分魔法方法简单使用
from unittest.mock import MagicMockclass Lauf:def __init__(self, name, age):self.name nameself.age age# 模拟方法
lauf.run_method MagicMock(return_valuerunning...)lauf.run_method(3,4,5,keyvalue) # 参数随意
running...# 断言
lauf.run_method.assert_called_once_with(3,4,5,keyvalue) # 带着这些参数被调用一次 patch装饰器
模拟xxx得到一个MagicMock对象使用
from unittest.mock import patchIn [83]: patch(os.path)...: def func(a): # 模拟os.path得到一个MagicMock对象传给函数...: print(a, a is os.path)...: ...: In [84]: func()
MagicMock namepath id1620313178896 True# 依次模拟得到多个MagicMock对象
patch(requests.post)
patch(requests.get)
def func(get_mock, post_mock):print(get_mock is requests.get) # Trueprint(post_mock is requests.post) # True# 模拟类的对象
# 为类的对象的属性、方法必须该类中存在 创建一个MagicMock对象
with patch.object(Lauf, method, return_valueNone) as mock_method:lauf Lauf(a, 10)lauf.method(1, 2, 3)# 断言
mock_method.assert_called_once_with(1, 2, 3)# 上下文内有效
foo {key: value}
original foo.copy()
with patch.dict(foo, {newkey: newvalue}, clearTrue):assert foo {newkey: newvalue} # 测试时foo变为新字典# 测试结束foo恢复
assert foo original# 操作魔法方法
m MagicMock()
m.__str__.return_value jack
str(m) # 返回jackm.__str__ MagicMock(return_valuexxx)create_autospec函数
创建mock对象并确保与模拟的函数、对象具有相同的接口patch(autospecTrue)
In [98]: def func(a,b,c):...: print(a,b,c)...: # 模拟函数并确保参数相同
In [99]: mock_func create_autospec(func, return_value3)In [100]: mock_func(1,2,3)
Out[100]: 3# 模拟对象并确保相同的接口
In [106]: mock_obj create_autospec(Lauf(jack, 23))In [107]: mock_obj.name
Out[107]: NonCallableMagicMock namemock.name specstr id1620277710272
mock_obj.name lili # 赋值In [108]: mock_obj.age
Out[108]: NonCallableMagicMock namemock.age specint id1620302996240 断言的方法
assert_called() Assert that the mock was called at least once.
mock Mock()
# 调用mock
mock()
# 断言
mock.assert_called()# 返回一个新的Mock对象
mock.method()
Mock namemock.method() id...
# mock.xx 随即返回一个新的 mock对象新的mock对象断言
mock.method .assert_called()assert_called_once() Assert that the mock was called exactly once.
mock Mock()
mock.assert_called_once() # 仅仅调用一次多/没调用 均异常assert_called_with(*args, **kwargs) This method is a convenient way of asserting that the last call has been made in a particular way: mock Mock()
mock.method(1, 2, 3, testwow)
mock.method.assert_called_with(1, 2, 3, testwow)assert_called_once_with(*args, **kwargs) Assert that the mock was called exactly once and that call was with the specified arguments. mock Mock(return_valueNone)
mock(foo, barbaz)
mock.assert_called_once_with(foo, barbaz)mock(other, barvalues)
mock.assert_called_once_with(other, barvalues)
Traceback (most recent call last):...
AssertionError: Expected mock to be called once. Called 2 times.
assert_any_call(*args, **kwargs) assert the mock has been called with the specified arguments.
mock Mock(return_valueNone)
mock(1, 2, argthing)
mock(some, thing, else)
mock.assert_any_call(1, 2, argthing)pytest-mock 使用
安装
pip install pytest pytest-mock使用