我有一个类在几个地方使用suds客户端来对另一个服务器进行一些xml调用。代码运行时没有问题,但是,我无法弄清楚如何在类构造函数中模拟suds客户端创建,这样它将创建一个模拟对象而不使用真正的套接字。我们尝试了多种mock.patch
的排列。 mocker.patch
等;但是那些运行导致套接字错误,其余导致 AttributeError 或 ImportError 。
这是班级的一个愚蠢的版本:
from suds.client import Client
from suds.transport.https import HttpAuthenticated
class MYClass(object):
def __init__(self, host, usern, passw, provisioning_timeout=90):
wsdl_url = 'https://{host}/server/GetWsdl?wsdl'.format(host=host)
transport = CustomTransport()
try:
self.client = Client(wsdl_url, transport=transport, timeout=5)
def run_wsdl(self, data):
result = self.client.service.testwsdl(data=data)
return result
这就是我试图通过单元测试
from me import my_class
from mock import patch
#These are some of the many permutations we've tried
@patch('my_class.MYClass.suds.client.Client') #ImportError, no suds
@patch('my_class.Client') #Socket use error in __init__
@patch('my_class.suds.client.Client') #ImportError, no suds
def test_sip_stuff(mock_client):
with patch.object(mock_client.client.service, 'testwsdl') as mockwsdl:
mockwsdl.return_value = good_wsdl_data
test_instance = my_class.MYClass(
host='10.10.10.20',
usern='user',
passw='pass'
)
return_value = test_instance.run_wsdl(data='something')
assert return_value == good_wsdl_data