代码之家  ›  专栏  ›  技术社区  ›  Adam

未调用Pytest PropertyMock作为MagicMock的返回值

  •  0
  • Adam  · 技术社区  · 6 年前

    我是在嘲笑 return_value 为了一个 MagicMock 实例作为 PropertyMock 但它似乎正在返回 对象而不调用它,即不返回实际值。

    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
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Adam    6 年前

    我不需要设置 other_model_mock 成为一个 MagicMock 只需将其设置为 PropertyMock

    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
    # ...