'Makes use of before_after to force a race condition, in order to
confirm handling of such conditions is done correctly.'

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

    course_user = UserFactory(username='Username', email='a@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')
    with before_after.before_after('django.db.models.Model.save', after_ftn=cohorts.add_user_to_cohort(second_cohort, course_user.username), autospec=True):
        cohorts.add_user_to_cohort(first_cohort, course_user.username)
    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': second_cohort.id, 'previous_cohort_name': second_cohort.name})
    self.assertEqual(first_cohort.users.get(), course_user)
