如何模拟googleapiclient.discovery.build [英] How to mock googleapiclient.discovery.build

查看:129
本文介绍了如何模拟googleapiclient.discovery.build的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟对计算引擎进行API调用的结果以列出VM.但不幸的是无法模拟确切的功能.

I am trying to mock the result of API call made to compute engine to list VMs. But unfortunately couldn't mock an exact function.

我尝试使用PATCH和MOCK方法来模拟特定的调用,但仍然失败

I've tried using PATCH and MOCK methods to mock specific calls made, still unsuccessful

code.py文件看起来像这样

code.py file looks likes this

import googleapiclient.discovery
import logging

class Service:
    def __init__(self, project, event):
        self.project_id = project
        self.compute = googleapiclient.discovery.build('compute', 'v1',
                                                       cache_discovery=False)
        self.event = event
        self.zones = self._validate_event()

    def _validate_event(self):
        if "jsonPayload" not in self.event:
            zones = self.compute.zones().list(
                project=self.project_id).execute()['items']

        else:
            zones = self.compute.zones().get(project=self.project_id,
                                             zone=self.event["jsonPayload"]
                                             ["resource"]["zone"]).execute()

        logging.debug(f"Identified Zones are {zones}")
        return [zone["name"] for zone in zones]

我的测试文件如下

# in-built
from unittest import TestCase
from unittest.mock import patch

# custom
import code


class TestServiceModule(TestCase):
    def setUp(self):
        self.project_id = "sample-project-id"

    @patch('code.googleapiclient.discovery')
    def test__validate_event_with_empty_inputs(self, mock_discovery):
        mock_discovery.build.zones.list.execute.return_value = {"items": [
            {
                "name": "eu-west-1"
            }
        ]}

        obj = code.Service(event={}, project=self.project_id)

        print(obj.zones)


在上述测试用例中,我期望在打印obj.zones时看到"eu-west-1"作为值

In the above test case, I Expected to see "eu-west-1" as the value when I print obj.zones

推荐答案

您没有正确模拟 googleapiclient.discovery.build 方法.这是单元测试解决方案:

You didn't mock the googleapiclient.discovery.build method correctly. Here is the unit test solution:

例如

code.py :

import googleapiclient.discovery
import logging


class Service:
    def __init__(self, project, event):
        self.project_id = project
        self.compute = googleapiclient.discovery.build('compute', 'v1', cache_discovery=False)
        self.event = event
        self.zones = self._validate_event()

    def _validate_event(self):
        if "jsonPayload" not in self.event:
            zones = self.compute.zones().list(project=self.project_id).execute()['items']
        else:
            zones = self.compute.zones().get(project=self.project_id,
                                             zone=self.event["jsonPayload"]["resource"]["zone"]).execute()

        logging.debug(f"Identified Zones are {zones}")
        return [zone["name"] for zone in zones]

test_code.py :

from unittest import TestCase, main
from unittest.mock import patch
import code


class TestService(TestCase):
    def setUp(self):
        self.project_id = "sample-project-id"

    @patch('code.googleapiclient.discovery')
    def test__validate_event_with_empty_inputs(self, mock_discovery):
        # Arrange
        mock_discovery.build.return_value.zones.return_value.list.return_value.execute.return_value = {
            "items": [{"name": "eu-west-1"}]}

        # Act
        obj = code.Service(event={}, project=self.project_id)

        # Assert
        mock_discovery.build.assert_called_once_with('compute', 'v1', cache_discovery=False)
        mock_discovery.build.return_value.zones.assert_called_once()
        mock_discovery.build.return_value.zones.return_value.list.assert_called_once_with(project='sample-project-id')
        mock_discovery.build.return_value.zones.return_value.list.return_value.execute.assert_called_once()
        self.assertEqual(obj.zones, ["eu-west-1"])


if __name__ == '__main__':
    main()

带有覆盖率报告的单元测试结果:

unit test result with coverage report:

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK
Name                                      Stmts   Miss  Cover   Missing
-----------------------------------------------------------------------
src/stackoverflow/56794377/code.py           14      1    93%   16
src/stackoverflow/56794377/test_code.py      16      0   100%
-----------------------------------------------------------------------
TOTAL                                        30      1    97%

版本:

  • google-api-python-client == 1.12.3
  • Python 3.7.5

这篇关于如何模拟googleapiclient.discovery.build的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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