我遵循了本教程 here我终于可以使用我的应用程序从我的域检索所有电子邮件。
现在我想用模拟为我的应用程序编写一些单元测试,但我不知道从哪里开始。
我已阅读here关于使用模拟进行单元测试以及 google api 管理目录 API 附带了他自己的模拟库。但我不明白如何正确使用它。
我的应用程序 test_email_user.py 包含来 self 的真实应用程序 email_user.py 的导入,但现在怎么办?
我必须伪造对我的真实应用程序的 google api 目录响应,但如何做到呢?
问候, 萨姆
最佳答案
我不熟悉你提到的 Google Client API 自己的模拟库,但我用这个 mock library 可以轻松做到这一点:
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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c11131f173c1813111d1512521f1311" rel="noreferrer noopener nofollow">[email protected]</a>",
"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')
关于python - 使用 Google Apps api 的模拟进行单元测试 - 管理目录 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893826/