Debnath Sinha
Debnath Sinha

Reputation: 1107

How can I mock the results of the GMail API?

We are using the GMail API and developing an application on top of it. Ideally I would like to have some golden emails to test the analytics engine against. This way I can develop the analytics engine without having to worry about fetching the emails and hence without a network connection. What is the best way to achieve this? I noticed that App Engine (which we use) now allows you to mock DataStore/memcache etc. and run nosetests, but I don't know how to do this across local appserver restarts.

Upvotes: 3

Views: 1018

Answers (3)

Ben Stuart
Ben Stuart

Reputation: 1

As a follow on from Arnaud's answer, the googleapis/google-api-python-client HttpMock is helpful, I found RequestMockBuilder to work better for my use case.

from googleapiclient.discovery import build
from googleapiclient.http import RequestMockBuilder

def read_response(filename):
    with open(filename, 'rb') as file:
        return file.read()

mock = RequestMockBuilder({
    'gmail.users.messages.list': (None, read_response('tests/unit/data/list_messages.json')),
})

build = build('gmail', 'v1', requestBuilder=mock)

The mock class allows you to pass a dictionary mapping API methods to appropriate responses. Unlike HttpMock, the builder expects responses as a JSON formatted string so a helper function may be required.

Upvotes: 0

Arnaud P
Arnaud P

Reputation: 12617

The Mock class provided by googleapis/google-api-python-client looks like a good candidate for your use case.

from googleapiclient.discovery import build
from googleapiclient.http import HttpMock

mock = HttpMock('mock-email-list.json', {'status': '200'})
gmail = build('gmail', 'v1', http=mock)
response = gmail.users().messages().list(userId='me').execute()
print(response)

Where mock-email-list.json content is of the form

{
   "messages":[
      {
         "id":"abcd",
         "threadId":"abcd"
      },
      {
         "id":"efgh",
         "threadId":"abcd"
      },
    ],
    "resultSizeEstimate":2
}

As a side note, after your test has run, you can also check what url the mock has been used for (by the gmail client):

assert mock.uri == 'https://gmail.googleapis.com/gmail/v1/users/me/messages?alt=json'

Upvotes: 1

Eric Koleda
Eric Koleda

Reputation: 12673

The Gmail API nor the client libraries provide special functionality for mocking email fetching. You'll need to build out the mocks on your own.

Upvotes: 0

Related Questions