简体   繁体   English

Python MagicMock.return_value 返回 MagicMock 而不是 return_value

[英]Python MagicMock.return_value returning MagicMock instead of return_value

I have a function that verifies if a given input string is a proper GCP zone:我有一个函数可以验证给定的输入字符串是否是正确的 GCP 区域:

def validate_zone(compute, project_id, zone):
    try:
        zone_response = compute.zones().get(project=project_id, zone=zone).execute()
        print(zone_response)
        print(zone_response.return_value)
        if ['status'] in zone_response:
            zone_details = {
                'status': zone_response['status'],
                'region': zone_response['region'],
                'name': zone_response['name']
            }
            return zone_details
        else:
            return "Zone {} not found for project {}".format(zone, project_id)
    except HttpError as error:
        print("Error calling zone {}: \n {}".format(zone, error))

I am trying to write a test to verify that but I can't mock the output of the compute method correctly.我正在尝试编写一个测试来验证这一点,但我无法正确模拟计算方法的输出。

@patch('googleapiclient.discovery')
def test_validate_zone(self, mock_response):
    compute = mock_response.build(serviceName='compute', version='v1')
    compute.zones().get(project_id=self.project_id, zone=self.zone).execute().return_value = {
        'status': 'status',
        'region': 'region',
        'name': 'name'
    }
    zone_response = inventory.validate_zone(compute, self.project_id, self.zone)
    print(zone_response)

This results in the zone_response output being a MagicMock object with its return_value being correct as developed in the test.这导致zone_response输出是一个 MagicMock 对象,其return_value与测试中开发的一样正确。

zone_response = MagicMock name='discovery.build().zones().get().execute()' id='139870134525456'
zone_response.return_value = {'status': 'status', 'region': 'region', 'name': 'name'}

Any ideas on what I'm doing wrong?关于我做错了什么的任何想法? I've been trying to write tests for this for quite a while so maybe my approach is just off.我已经尝试为此编写测试一段时间了,所以也许我的方法刚刚结束。

Turns out the issue was the () on the execute method in the test.原来问题出在测试中 execute 方法上的 ()。 So the correct test should be:所以正确的测试应该是:

@patch('inventory.discovery.build', serviceName='compute', version='v1')
    def test_validate_zone(self, compute):
        print(compute)
        compute.zones().get(project_id=self.project_id, zone=self.zone).execute.return_value = {
            'status': 'status',
            'region': 'region',
            'name': 'name'
        }
        zone_response = inventory.validate_zone(compute, self.project_id, self.zone)
        print(zone_response)

Source can be found at: https://realpython.com/python-mock-library/#managing-a-mocks-return-value来源可以在: https : //realpython.com/python-mock-library/#managing-a-mocks-return-value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM