Skip to main content
 首页 » 编程设计

python之为单元测试模拟 Googleads

2024年10月24日10kuangbin

我有一个使用 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) 

谢谢,

弗明

编辑:这是测试的开始,不过我有一些问题要问。 当设置 instance = 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)   

请您参考如下方法:

使用 mock 库在 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