Python 使用mock进行google apps api的单元测试-管理目录api
我遵循了这个教程,我终于可以用我的应用程序从我的域中检索所有电子邮件 现在我想用mock为我的应用程序编写一些单元测试,但我不知道从哪里开始 我读过关于使用mock进行单元测试的文章,并且GoogleAPI管理目录api附带了他自己的mock库。但是我不知道如何正确使用它 我的应用程序测试\u email\u user.py包含从我的真实应用程序email\u user.py导入的内容,但是现在呢 我必须对我的真实应用程序伪造GoogleAPI目录响应,但是怎么做呢 您好,Python 使用mock进行google apps api的单元测试-管理目录api,python,unit-testing,google-apps,Python,Unit Testing,Google Apps,我遵循了这个教程,我终于可以用我的应用程序从我的域中检索所有电子邮件 现在我想用mock为我的应用程序编写一些单元测试,但我不知道从哪里开始 我读过关于使用mock进行单元测试的文章,并且GoogleAPI管理目录api附带了他自己的mock库。但是我不知道如何正确使用它 我的应用程序测试\u email\u user.py包含从我的真实应用程序email\u user.py导入的内容,但是现在呢 我必须对我的真实应用程序伪造GoogleAPI目录响应,但是怎么做呢 您好, sam我不熟悉您提到
sam我不熟悉您提到的Google客户端API自己的模拟库,但我很容易做到这一点:
谢谢-但是你从哪里得到的代码?存在一些错误,如空白语法错误或缺少导入。另一个问题:如何将其用于pytest?有什么提示吗?我正在阅读pytest的文档,但是我不知道如何在测试中使用上面的代码。。。
import mock
class DirectoryHelper():
...
#Real method that calls the API
def get_users(self):
user_list = []
request = self.service.users().list(
customer=self.customer_id,
maxResults=500,
orderBy='email',
fields="nextPageToken,users(id,orgUnitPath,primaryEmail,name(givenName,familyName),agreedToTerms,suspended)"
)
while request:
logging.debug('Retrieving a page of users from directory...')
report_document = request.execute()
if 'users' in report_document:
for user in report_document['users']:
user_list.append(user)
request = self.service.users().list_next(
request, report_document
)
return user_list
#Mock method that simulate the API call
def get_mock_users(self):
return [
{
"id": "12345",
"primaryEmail": "mock@domain.com",
"name": {
"givenName": u"Mock",
"familyName": u"User"
},
"agreedToTerms": True,
"suspended": False,
"orgUnitPath": "/"
}
]
@mock.patch.object(DirectoryHelper, 'get_users', get_mock_users)
def test_sync_apps_users(self):
directory_helper = DirectoryHelper()
self.assertEquals(1, len(directory_helper.get_users()), 'Mock only contain one user')