gpt4 book ai didi

python - 使用python和mock模拟ReviewBoard第三方库

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:03 26 4
gpt4 key购买 nike

我使用 ReviewBoard API 库,今天我将代码移至单独的类,并希望通过一些测试来覆盖逻辑。我了解模拟和测试,但显然我对 python 及其库没有太多经验。这是真正的代码块:

<!-- language: python -->
from rbtools.api.client import RBClient

class ReviewBoardWrapper():

def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
pass

def Connect(self):
self.client = RBClient(self.url, username=self.username, password=self.password)
self.root = self.client.get_root()
pass

我想断言初始化以及调用 get_root() 方法。以下是我尝试实现这一目标的方法:

<!-- language: python -->
import unittest
import mock

from module_base import ReviewBoardWrapper as rb

class RbTestCase(unittest.TestCase):

@mock.patch('module_base.RBClient')
@mock.patch('module_base.RBClient.get_root')
def test_client_connect(self, mock_client, mock_method):
rb_client = rb('', '', '')
rb_client.Connect()
self.assertTrue(mock_method.called)
self.assertTrue(mock_client.called)

这是我遇到的错误:

$ python -m unittest module_base_tests
F.
======================================================================
FAIL: test_client_connect (module_base_tests.RbTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "module_base_tests.py", line 21, in test_client_connect
self.assertTrue(mock_client.called)
AssertionError: False is not true

----------------------------------------------------------------------
Ran 2 tests in 0.002s

FAILED (failures=1)

我做错了什么?我是否正确模拟了导入库的“本地副本”?问题是否完全出在不同的领域?

我也尝试过这样做:

@mock.patch('module_base.RBClient.__init__')

和/或这个:

self.assertTrue(mock_client.__init__.called)

最佳答案

在您帖子的示例中,模拟的顺序是相反的:

test_client_connect(self, mock_client, mock_method)

客户端实际上被模拟为第二个参数,方法调用被模拟为第一个参数。

但是,为了正确模拟客户端,您需要模拟客户端调用的返回值。模拟返回值并对返回值进行断言的示例如下:

class RbTestCase(unittest.TestCase):                                                                                                                                                                        

@mock.patch('module_base.RBClient')
def test_client_connect(self, mock_client):
client = mock.MagicMock()
mock_client.return_value = client
rb_client = rb('', '', '')
rb_client.Connect()
self.assertTrue(client.get_root.called)
self.assertTrue(mock_client.called)

关于python - 使用python和mock模拟ReviewBoard第三方库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com