Search code examples
pythondjangomockingimporterrorgoogle-api-client

How to mock googleapiclient in a Django test environment


I'm trying to mock googleapiclient.discovery in a django unittest, I looked at how at this post which shows how to mock googleapiclient.discovery in general, so I tried this:

...
@mock.patch("myapp.views.googleapiclient.discovery")
def test_get_instances(self, mock_discovery):
    mock_discovery.build.return_value.service.return_value.instances.return_value.aggregatedList.return_value = {# some mock values}
...

This gave a "Module not found error", stating that "myapp.views" is not a package

The views.py in question is in the standard location for Django apps: mysite/myapp/views.py

views.py:

...
from googleapiclient import discovery

def get_instances(proj_id, servicekey)
    service = discovery.build('compute','v1', credentials=generate_credentials(servicekey))
    request = service.instances().aggregatedList(project=project_id)
...

I'm new to mocking so any advice is warmly welcome


Solution

  • I was meant to change

    from googleapiclient import discovery
    

    to

    import googleapiclient.discovery