模拟外部图书馆返回值抛出访问违规例外
我正在使用外部库 sklearn.neighbors.KDTree 为我的方法编写 TC。
我的测试目标方法如下,
# target.py
from sklearn.neighbors import KDTree
@staticmethod
def mymethod(a, b):
...
dist, index = KDTree(a).query(b, k=3)
# manipulate the return value from KDTree.query
...
并且,我尝试作为TC的代码是这样的。
# mytest.py
from unittest import mock
@mock.patch('sklearn.neighbors.KDTree')
def test_mymethod(mock_kdtree):
# make test data and set mock
a = ...
b = ...
mock_kdtree.return_value.query.return_value = ...
# execute test target
mymethod(a, b)
assert mock_kdtree.called
运行 TC 时,它会在调用 dist, index = KDTree(a).query(b, k=3)
的行上抛出异常,Windows 致命异常:访问冲突
。
模拟 KDTree 返回值有问题吗?
I'm writing TC for my method using external library sklearn.neighbors.KDTree
.
My test target method is below,
# target.py
from sklearn.neighbors import KDTree
@staticmethod
def mymethod(a, b):
...
dist, index = KDTree(a).query(b, k=3)
# manipulate the return value from KDTree.query
...
and, the code I tried as TC is this.
# mytest.py
from unittest import mock
@mock.patch('sklearn.neighbors.KDTree')
def test_mymethod(mock_kdtree):
# make test data and set mock
a = ...
b = ...
mock_kdtree.return_value.query.return_value = ...
# execute test target
mymethod(a, b)
assert mock_kdtree.called
When running TC it throws exception, Windows fatal exception: access violation
on the line calling dist, index = KDTree(a).query(b, k=3)
.
Is there something wrong to mock KDTree return value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它没有正确地模拟该方法。
您通常会跳过设置类的模拟实例的步骤。
It is not mocking the method correctly.
You typically skip the step where you set the mock instance of the class.
对于可能遇到同样问题的人,我分享了我如何进行测试。
关键是从建议@jossefaz中使用
monkeypatch
。谢谢你!For someone who might be struggling with same problem, I share how I made my test.
The key is using
monkeypatch
, from the advice @jossefaz. Thank you!