'Verifies that set_user_preferences returns appropriate errors.'

@patch('openedx.core.djangoapps.user_api.models.UserPreference.delete')
@patch('openedx.core.djangoapps.user_api.models.UserPreference.save')
def test_update_user_preferences_errors(self, user_preference_save, user_preference_delete):

    update_data = {self.test_preference_key: 'new_value'}
    with self.assertRaises(UserNotFound):
        update_user_preferences(self.user, update_data, user='no_such_user')
    with self.assertRaises(UserNotFound):
        update_user_preferences(self.no_such_user, update_data)
    with self.assertRaises(UserNotAuthorized):
        update_user_preferences(self.staff_user, update_data, user=self.user.username)
    with self.assertRaises(UserNotAuthorized):
        update_user_preferences(self.different_user, update_data, user=self.user.username)
    too_long_key = ('x' * 256)
    with self.assertRaises(PreferenceValidationError) as context_manager:
        update_user_preferences(self.user, {too_long_key: 'new_value'})
    errors = context_manager.exception.preference_errors
    self.assertEqual(len(errors.keys()), 1)
    self.assertEqual(errors[too_long_key], {'developer_message': get_expected_validation_developer_message(too_long_key, 'new_value'), 'user_message': get_expected_key_error_user_message(too_long_key, 'new_value')})
    for empty_value in ('', '            '):
        with self.assertRaises(PreferenceValidationError) as context_manager:
            update_user_preferences(self.user, {self.test_preference_key: empty_value})
        errors = context_manager.exception.preference_errors
        self.assertEqual(len(errors.keys()), 1)
        self.assertEqual(errors[self.test_preference_key], {'developer_message': get_empty_preference_message(self.test_preference_key), 'user_message': get_empty_preference_message(self.test_preference_key)})
    user_preference_save.side_effect = [Exception, None]
    with self.assertRaises(PreferenceUpdateError) as context_manager:
        update_user_preferences(self.user, {self.test_preference_key: 'new_value'})
    self.assertEqual(context_manager.exception.developer_message, u"Save    failed    for    user    preference    'test_key'    with    value    'new_value':    ")
    self.assertEqual(context_manager.exception.user_message, u"Save    failed    for    user    preference    'test_key'    with    value    'new_value'.")
    user_preference_delete.side_effect = [Exception, None]
    with self.assertRaises(PreferenceUpdateError) as context_manager:
        update_user_preferences(self.user, {self.test_preference_key: None})
    self.assertEqual(context_manager.exception.developer_message, u"Delete    failed    for    user    preference    'test_key':    ")
    self.assertEqual(context_manager.exception.user_message, u"Delete    failed    for    user    preference    'test_key'.")
