0

I running some unit tests for a method with mock objects. In the method, attributes are set, but I can't seem to access them in the unit test. When I try I get back a mock object, not the string I am trying to access

Here is my unit test

    @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"

The method I am testing is

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

When I run the unit test, I get this error

AssertionError: assert <Mock name='new().type' id='140691645666360'> == 'PERSP'
E        +  where <Mock name='new().type' id='140691645666360'> = <Mock name='new()' id='140691645594760'>.type```
Vayelin
  • 75
  • 1
  • 2
  • 10

1 Answers1

0

Figured it out. I needed to do configure mock so the code now looks like

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

You need to configure/set the attribute first in the mock so that you can access it later. Now the attribute "type" can be accessed after the method has been run

Vayelin
  • 75
  • 1
  • 2
  • 10