More Coverage

To be able to change the code safely, we need to cover all variations. Otherwise, we can’t be sure that we noticed an introduced bug or changed behavior.

To find all possible variations, we need to take a look at the source code. We need to identify conditions in the code because they are essential for the possible variations of the code. For example, if we take a look at this section:

    [...]
    
    if is_new_setup:
        pm.newFile(force=True)
       
    [...]

There are two possible variations:

  • Create a new and empty file in Maya
  • Leave the scene untouched

Both cases are important, and we need to make sure that we don’t break this behavior. So we add a test for that:

@mock.patch("[...]maya.api.filemanager.pm.newFile")
@mock.patch("[...]maya.api.filemanager.Environment")
@mock.patch("[...]maya.api.filemanager.save_scene_using_tmp")
@mock.patch("[...]maya.api.filemanager.set_current_file_info")
@mock.patch("[...]maya.api.filemanager.query_previous_files")
def test_variant_empty_should_create_new_scene(mock_query_previous_files, mock_set_current_file_info, mock_save_scene,
                                               mock_env_constructor, mock_create_new):
    mock_env = mock.MagicMock()
    mock_env.run_setup_handlers = mock.MagicMock()
    mock_env_constructor.return_value = mock_env

    shot = Shot('myAwesomeShot')
    user = User('Jan Honsbrok', 'janhon')
    current = File(shot=shot)
    mock_query_previous_files.return_value = [File(shot=shot, name='test', filetype='filetype', version=0)]
    mock_session = mock.MagicMock()

    create_maya_scene(shot, user=user, current=current, session=mock_session, variant='empty')

    mock_session.commit.assert_called_once()
    mock_set_current_file_info.assert_called_once()
    mock_create_new.assert_called_once()
    mock_env.run_setup_handlers.assert_called_once()
    mock_save_scene.assert_called_once()

We repeat this for all essential variations until we are satisfied that the tests hit all essential code paths. In the case of is_new_setup it was easy because we just mocked pm.newFile directly. In other cases, we would apply the same technique as above: extract method and mock.

Last modified August 24, 2020