问题
I have a service that uses the googleads library in python, I want to unit test these functions but do not know how to go about mocking this aspect. When I used PHP and Zend Framework it was pretty easy to mock clients, as I could tell what was expected to be called, and mock what was returned, but I do not know how to do this here.
Could you point to a good resource to do learn more about it? Here's some example code I'd like to test (get_account_timezone):
from googleads import AdWordsClient
from googleads.oauth2 import GoogleRefreshTokenClient
from dateutil import tz
class AdWords:
ADWORDS_VERSION = 'v201509'
def __init__(self, client_id, client_secret, refresh_token, dev_token, customer_id):
"""AdWords __init__ function
Args:
client_id (str): OAuth2 client ID
client_secret (str): OAuth2 client secret
refresh_token (str): Refresh token
dev_token (str): Google AdWords developer token
customer_id (str): Google AdWords customer ID
"""
self.client_id = client_id
self.client_secret = client_secret
self.refresh_token = refresh_token
self.dev_token = dev_token
self.customer_id = customer_id
oauth2_client = GoogleRefreshTokenClient(
self.client_id,
self.client_secret,
self.refresh_token
)
self.client = AdWordsClient(
self.dev_token,
oauth2_client,
'Analytics',
self.customer_id
)
def get_account_timezone(self):
"""Get timezone that current AdWords account is using
Returns:
Timezone
"""
service = self.client.GetService('ManagedCustomerService', self.ADWORDS_VERSION)
response = service.get({
'fields': ['DateTimeZone']
})
if 'entries' not in response or len(response.entries) != 1:
return tz.tzutc()
account_timezone = response.entries[0].dateTimeZone
return tz.gettz(account_timezone)
Thank you,
fermin
EDIT: Here's the beginning of the test, I have some questions for it though. When setting instance = AdWords(...), it is generating a real instance of my AdWords class, instead of taking the mock, I am lost as to how to proceed. Asserting that GetService is called fails too.
import unittest
import sys
import mock
from os import path
sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))))
from analytics.services.adwords import AdWords
from dateutil import tz
import xmltodict
import datetime
import googleads
mock_credentials = {
'client_id': 'aaaa',
'client_secret': 'bbb',
'refresh_token': 'ccc',
'dev_token': 'ddd',
'customer_id': 'eee',
}
ADWORDS_VERSION = 'v201509'
mock_timezone_response = {
"totalNumEntries": 1,
"Page.Type": "ManagedCustomerPage",
"entries":
{
"dateTimeZone": "America/Los_Angeles"
},
}
class AdWordsServiceTests(unittest.TestCase):
@mock.patch('googleads.adwords.AdWordsClient', autospec=True)
@mock.patch('googleads.oauth2.GoogleRefreshTokenClient', autospec=True)
@mock.patch('dateutil.tz', autospec=True)
def test_get_account_timezone_mock(self, tz_mock, refresh_token_client_mock, adwords_client_mock):
adwords_client_instance = mock.Mock()
adwords_client_mock.return_value = mock_timezone_response
instance = AdWords(mock_credentials['client_id'], mock_credentials['client_secret'], mock_credentials['refresh_token'],
mock_credentials['dev_token'], mock_credentials['customer_id'])
instance.get_account_timezone()
assert adwords_client_mock is googleads.adwords.AdWordsClient
adwords_client_instance.GetService.assert_called_with('ManagedCustomerService', ADWORDS_VERSION)
回答1:
It is usually really easy to mock stuff in python with mock library. I do not guarantee this is the best way to test this code. Refactoring it can lead to more robust and easier to test code.
import unittest
import mock
class TestCaseName(unittest.TestCase):
@mock.patch('path_to_module.AdWordsClient', autospec=True)
@mock.patch('path_to_module.GoogleRefreshTokenClient', autospec=True)
@mock.patch('path_to_module.tz', autospec=True)
def test_get_account_timezone(self, tz_mock, adwords_client_mock, grefresh_token_client_mock):
adwards_client_instance = mock.Mock()
adwords_client_mock.return_value = test_get_account_timezone
instance = AdWords(...)
instance.get_account_timezone()
adwards_client_instance.GetService.assert_called_with(...)
You should check the documentation for exact methods of the mock library.
Alternative to mock is https://pypi.python.org/pypi/doubles/1.1.3
来源:https://stackoverflow.com/questions/34501583/mocking-googleads-for-unit-tests