简体   繁体   中英

Pytest PropertyMock as return_value for MagicMock does not get invoked

I am trying to mock the return_value for a MagicMock instance as a PropertyMock but it appears to be returning the PropertyMock object without invoking it ie does not return the actual value.

class MySerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        # ...
        fields = (
            "my_field"
        )

    my_field = serializers.SerializerMethodField()

    def get_my_field(self, instance):
        other_models = instance.other_models.filter(stuff="stuff")
        if other_models:
            # returns <class 'unittest.mock.PropertyMock'> instead of an actual value
            print(type(other_models.get().my_property))
            # throws error since it isn't receiving a string
            return ujson.loads(other_models.get().my_property)
        return {}


# test case
def test_hello(mocker):
    expected_value = ujson.dumps({'hello': 2})
    instance_mock = mocker.MagicMock()
    other_model_mock = mocker.MagicMock()
    other_model_mock.get().my_property = mocker.PropertyMock(return_value=expected_value)
    instance_mock.other_models.filter.return_value = other_model_mock

    serializer = MySerializer()
    observed_value = serializer.get_my_field(instance_mock)
    assert expected_value == observed_value

I did not need to set other_model_mock to be a MagicMock simply setting it to be a PropertyMock worked

expected_value = {'hello', 2}
instance_mock = mocker.MagicMock()
other_model_mock = mocker.PropertyMock()
other_model_mock.get().my_property.return_value = ujson.dumps(expected_value)
instance_mock.other_models.filter.return_value = other_model_mock
# ... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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