Reputation:
I followed this tutorial here and I can finally retrive all emails from my domain with my application.
Now I want to write some unit tests with mock for my application, but I dont know where to start.
I have read here about unit testing with mock and that the google api admin directory API comes with his own mock library. But I dont understand how to use it correctly.
My application test_email_user.py contains the import from my real application email_user.py but now what?
I have to fake the google api directory responses to my real application, but how?
greetings, sam
Upvotes: 2
Views: 1169
Reputation: 564
I'm not familiar with the Google Client API own mock library you mention but I do it easily with this 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": "[email protected]",
"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')
Upvotes: 2