模拟Googleads进行单元测试

时间:2015-12-28 22:16:49

标签: python unit-testing mocking python-unittest

我有一个在python中使用googleads库的服务,我想对这些函数进行单元测试,但不知道如何去模拟这个方面。 当我使用PHP和Zend Framework时,很容易模拟客户端,因为我可以告诉我们预期会调用什么,并模拟返回的内容,但我不知道如何在这里执行此操作。

你能指出一个很好的资源来了解它吗? 这是我要测试的一些示例代码(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)

谢谢,

佛明

编辑:这是测试的开始,但我有一些问题。 设置实例= AdWords(...)时,它会生成我的AdWords课程的真实实例,而不是模拟,我对如何继续进行了迷失。 断言调用GetService也会失败。

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 个答案:

答案 0 :(得分:1)

使用模拟库在python中模拟东西通常很容易。我不保证这是测试此代码的最佳方法。重构它可以使代码更健壮,更容易测试。

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(...)

您应该查看文档以获取模拟库的确切方法。

模拟的替代方法是https://pypi.python.org/pypi/doubles/1.1.3