'Test initialize connection.'

@mock.patch.object(qnap.QnapISCSIDriver, '_get_lun_naa_from_volume_metadata')
@mock.patch('cinder.volume.drivers.qnap.QnapAPIExecutor')
def test_initialize_connection_with_target_exist(self, mock_api_executor, mock_get_lun_naa_from_volume_metadata):

    fake_volume = VolumeClass('fakeDisplayName', 'fakeId', 100, 'fakeLunName')
    fake_connector = {'initiator': 'fakeInitiatorIqn'}
    mock_api_return = mock_api_executor.return_value
    mock_api_return.get_basic_info.return_value = ('ES1640dc    ', 'ES1640dc    ', '1.1.3')
    mock_api_return.get_iscsi_portal_info.return_value = FAKE_RES_DETAIL_ISCSI_PORTAL_INFO
    mock_get_lun_naa_from_volume_metadata.return_value = 'fakeLunNaa'
    mock_api_executor.return_value.get_lun_info.side_effect = [self.get_lun_info_return_value(), self.get_lun_info_return_value()]
    mock_api_return.get_all_iscsi_portal_setting.return_value = FAKE_RES_DETAIL_GET_ALL_ISCSI_PORTAL_SETTING
    mock_api_executor.return_value.map_lun.return_value = None
    mock_api_return.get_ethernet_ip.return_value = ['1.2.3.4']
    self.driver = qnap.QnapISCSIDriver(configuration=create_configuration('admin', 'qnapadmin', 'http://1.2.3.4:8080', '1.2.3.4', 'Pool1', True))
    self.driver.do_setup('context')
    expected_properties = {'target_discovered': True, 'target_portal': '1.2.3.4:fakeServicePort', 'target_iqn': 'fakeTargetIqn', 'target_lun': 1, 'volume_id': fake_volume['id'], 'target_portals': ['1.2.3.4:fakeServicePort'], 'target_iqns': ['fakeTargetIqn'], 'target_luns': [1]}
    expected_return = {'driver_volume_type': 'iscsi', 'data': expected_properties}
    self.assertEqual(expected_return, self.driver.initialize_connection(fake_volume, fake_connector))
    mock_api_return = mock_api_executor.return_value
    mock_api_return.get_iscsi_portal_info.assert_called_once_with()
    expected_call_list = [mock.call(LUNNAA='fakeLunNaa'), mock.call(LUNNAA='fakeLunNaa')]
    self.assertEqual(expected_call_list, mock_api_executor.return_value.get_lun_info.call_args_list)
    mock_api_return = mock_api_executor.return_value
    mock_api_return.get_all_iscsi_portal_setting.assert_called_once_with()
    mock_api_return.map_lun.assert_called_once_with('fakeLunIndex', 'fakeTargeIndex')
    mock_api_return.get_ethernet_ip.assert_called_once_with(type='data')
