'Verifies that set_user_preference returns appropriate errors.'

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

    with self.assertRaises(UserNotFound):
        set_user_preference(self.user, self.test_preference_key, 'new_value', username='no_such_user')
    with self.assertRaises(UserNotFound):
        set_user_preference(self.no_such_user, self.test_preference_key, 'new_value')
    with self.assertRaises(UserNotAuthorized):
        set_user_preference(self.staff_user, self.test_preference_key, 'new_value', username=self.user.username)
    with self.assertRaises(UserNotAuthorized):
        set_user_preference(self.different_user, self.test_preference_key, 'new_value', username=self.user.username)
    too_long_key = ('x' * 256)
    with self.assertRaises(PreferenceValidationError) as context_manager:
        set_user_preference(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 (None, '', '            '):
        with self.assertRaises(PreferenceValidationError) as context_manager:
            set_user_preference(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:
        set_user_preference(self.user, u'new_key_\u023b\u0127\u023a\u024d\u0142\u0247s', u'new_value_\u023b\u0127\u023a\u024d\u0142\u0247s')
    self.assertEqual(context_manager.exception.developer_message, u"Save    failed    for    user    preference    'new_key_\u023b\u0127\u023a\u024d\u0142\u0247s'    with    value    'new_value_\u023b\u0127\u023a\u024d\u0142\u0247s':    ")
    self.assertEqual(context_manager.exception.user_message, u"Save    failed    for    user    preference    'new_key_\u023b\u0127\u023a\u024d\u0142\u0247s'    with    value    'new_value_\u023b\u0127\u023a\u024d\u0142\u0247s'.")
