模拟Googleads进行单元测试 [英] Mocking Googleads for Unit Tests

查看:98
本文介绍了模拟Googleads进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用python中的googleads库的服务,我想对这些函数进行单元测试,但不知道如何模拟这方面. 当我使用PHP和Zend Framework时,模拟客户端非常容易,因为我可以说出应该调用的内容,并模拟返回的内容,但是我不知道如何在这里进行操作.

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.

您能否指出一个好的资源来做更多的了解? 这是我要测试的一些示例代码(get_account_timezone):

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)

谢谢

fermin

这是测试的开始,不过我对此有一些疑问. 设置instance = AdWords(...)时,它会生成我的AdWords类的真实实例,而不是模拟,我对如何继续一无所知. 断言GetService的调用也失败.

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)  

推荐答案

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

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.

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

这篇关于模拟Googleads进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆