'Make sure cohorts.add_user_to_cohort() properly adds a user to a cohort and
handles errors.'

@patch('openedx.core.djangoapps.course_groups.cohorts.tracker')
def test_add_user_to_cohort(self, mock_tracker):

    course_user = UserFactory(username='Username', email='a@b.com')
    UserFactory(username='RandomUsername', email='b@b.com')
    course = modulestore().get_course(self.toy_course_key)
    CourseEnrollment.enroll(course_user, self.toy_course_key)
    first_cohort = CohortFactory(course_id=course.id, name='FirstCohort')
    second_cohort = CohortFactory(course_id=course.id, name='SecondCohort')
    self.assertEqual(cohorts.add_user_to_cohort(first_cohort, 'Username'), (course_user, None, False))
    mock_tracker.emit.assert_any_call('edx.cohort.user_add_requested', {'user_id': course_user.id, 'cohort_id': first_cohort.id, 'cohort_name': first_cohort.name, 'previous_cohort_id': None, 'previous_cohort_name': None})
    self.assertEqual(cohorts.add_user_to_cohort(second_cohort, 'Username'), (course_user, 'FirstCohort', False))
    mock_tracker.emit.assert_any_call('edx.cohort.user_add_requested', {'user_id': course_user.id, 'cohort_id': second_cohort.id, 'cohort_name': second_cohort.name, 'previous_cohort_id': first_cohort.id, 'previous_cohort_name': first_cohort.name})
    (user, previous_cohort, prereg) = cohorts.add_user_to_cohort(first_cohort, 'new_email@example.com')
    self.assertEqual((user, previous_cohort, prereg), (None, None, True))
    mock_tracker.emit.assert_any_call('edx.cohort.email_address_preassigned', {'user_email': 'new_email@example.com', 'cohort_id': first_cohort.id, 'cohort_name': first_cohort.name})
    self.assertRaises(ValueError, (lambda : cohorts.add_user_to_cohort(second_cohort, 'Username')))
    self.assertRaises(User.DoesNotExist, (lambda : cohorts.add_user_to_cohort(first_cohort, 'non_existent_username')))
