【问题标题】:Unable to access mock attributes that were set while running无法访问在运行时设置的模拟属性
【发布时间】:2019-08-19 18:49:06
【问题描述】:

我为带有模拟对象的方法运行了一些单元测试。在方法中,设置了属性,但我似乎无法在单元测试中访问它们。当我尝试返回一个模拟对象时,而不是我试图访问的字符串

这是我的单元测试

    @mock.patch("bpy.data.cameras.new")
    def test_load_camera(self, mock_camera_data):
        loader = self.SceneLoader(self.json_data)
        self.mock_bpy.context.scene.objects.link.return_value = 5
        cam_data = {"name": "camera 1",
                    "type": "PERSP",
                    "lens_length": 50.0,
                    "lens_unit": "MILLIMETERS",
                    "translation": [
                        4.5,
                        74,
                        67
                    ],
                    "rotation": [
                        -0.008,
                        -0.002,
                        0.397,
                        0.918
                    ]
                    }
        data = mock.Mock()
        mock_camera_data.return_value = data
        loader._load_camera(cam_data)
        assert mock_camera_data.called_with("Camera")
        assert data.type == "PERSP"

我正在测试的方法是

def _load_camera(self, cam_data):
        camera_data = bpy.data.cameras.new("Camera")
        camera_data.type = cam_data["type"]

当我运行单元测试时,我得到了这个错误

AssertionError: assert <Mock name='new().type' id='140691645666360'> == 'PERSP'
E        +  where <Mock name='new().type' id='140691645666360'> = <Mock name='new()' id='140691645594760'>.type```

【问题讨论】:

    标签: python unit-testing mocking pytest magicmock


    【解决方案1】:

    想通了。我需要配置模拟,所以代码现在看起来像

        data = mock.Mock()
        data.configure_mock(type=None)
        mock_camera_data.return_value = data
        loader._load_camera(cam_data)
    

    您需要先在模拟中配置/设置属性,以便以后可以访问它。现在可以在方法运行后访问属性“type”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 2020-03-11
      • 2017-11-05
      • 2016-11-03
      相关资源
      最近更新 更多