您可以使用此代码创建一个
suds 模拟客户端。
from suds.client import Client
class AlwaysCallable(object):
"""
Represents a chainable-access object and proxies calls to ClientMock.
"""
name = None
def __init__(self, client_cls):
self._client_cls = client_cls
def __call__(self, *args, **kwargs):
try:
hook = object.__getattribute__(self._client_cls, self.name)
except AttributeError:
pass
else:
return hook(self._client_cls, *args, **kwargs)
def __getattr__(self, item):
new = object.__getattribute__(self, '__class__')(self._client_cls)
new.name = item
return new
class ClientMock(Client):
"""
Abstract mock suds client.
"""
def __init__(self, url, **kwargs):
pass
def __getattr__(self, item):
return AlwaysCallable(self.__class__)
def __unicode__(self):
return 'Client mock'
def __str__(self):
return 'Client mock'
接下来定义一个具体的ClientMock。
class UserCredentialsServiceClientMock(ClientMock):
"""
Mock object that implements remote side services.
"""
def GetUserInfo(cls, user_id):
"""
Stub for remote service.
"""
return UserInfo(id=user_id, name='Adam Smith')
现在你可以使用Mock库来模拟使用suds.client.Client的代码。
from unittest import TestCase
from mock import patch
from project.api import get_user_credentials
class UserCredentialsClientTestCase(TestCase):
def test_getting_user_credentials(self):
with patch('project.api.Client', new=UserCredentialsServiceClientMock):
self.assertEquals(get_user_credentials(1), 'Adam Smith')