Ejemplo n.º 1
0
class ProfileLangTest(TestCase):
    def setUp(self):
        self.person = PersonFactory()
        self.person.language = FRENCH_LANGUAGE
        self.person.save()

        self.url = reverse('profile_lang', args=[ENGLISH_LANGUAGE])
        self.client.force_login(self.person.user)

    def test_user_not_logged(self):
        self.client.logout()
        response = self.client.get(self.url)

        self.assertRedirects(response, '/login/?next={}'.format(self.url))

    def test_language_not_known(self):
        url = reverse('profile_lang', args=["unk"])
        response = self.client.get(url, HTTP_REFERER='/')
        self.person.refresh_from_db()

        self.assertRedirects(response, '/')
        self.assertEqual(self.person.language, FRENCH_LANGUAGE)

    def test_change_language(self):
        response = self.client.get(self.url, HTTP_REFERER='/')
        self.person.refresh_from_db()

        self.assertRedirects(response, '/')
        self.assertEqual(self.person.language, ENGLISH_LANGUAGE)
Ejemplo n.º 2
0
    def test_tutor_in_several_groups(self):
        a_tutor_person = PersonFactory()
        a_tutor_person.user.groups.add(Group.objects.get(name=TUTOR))
        a_tutor_person.user.groups.add(
            Group.objects.get(name=CENTRAL_MANAGER_GROUP))
        a_tutor_person.save()

        self.assertCountEqual(UserListView().get_queryset(), [a_tutor_person])
Ejemplo n.º 3
0
    def test_donot_return_student_in_no_groups(self):
        StudentFactory()
        a_central_manager_person = PersonFactory()
        a_central_manager_person.user.groups.add(
            Group.objects.get(name=CENTRAL_MANAGER_GROUP))
        a_central_manager_person.save()

        self.assertCountEqual(UserListView().get_queryset(),
                              [a_central_manager_person])
Ejemplo n.º 4
0
def step_impl(context: Context, group):
    user = PersonFactory(user__username="******",
                         user__first_name="Keyser",
                         user__last_name="Söze",
                         user__password="******").user

    user.groups.clear()

    if group.lower() == 'gestionnaire factulaire':
        user.groups.add(Group.objects.get(name=FACULTY_MANAGER_GROUP))
    elif group.lower() in ('gestionnaire central', 'central manager'):
        user.groups.add(Group.objects.get(name=CENTRAL_MANAGER_GROUP))
    elif group.lower() == "gestionnaire d'institution":
        user.groups.add(Group.objects.get(name="institution_administration"))

    user.save()

    context.user = user

    page = LoginPage(driver=context.browser,
                     base_url=context.get_url('/login/')).open()
    page.login("usual_suspect", 'Roger_Verbal_Kint')

    context.test.assertEqual(context.browser.current_url, context.get_url('/'))
Ejemplo n.º 5
0
class PersonTest(PersonTestCase):
    def setUp(self):
        self.an_user = user.UserFactory(username="******")
        self.user_for_person = user.UserFactory(username="******")
        self.person_with_user = PersonFactory(user=self.user_for_person,
                                              language="fr-be",
                                              first_name="John",
                                              last_name="Doe")
        self.person_without_user = PersonWithoutUserFactory()

    def test_find_by_id(self):
        tmp_person = PersonFactory()
        db_person = person.find_by_id(tmp_person.id)
        self.assertIsNotNone(tmp_person.user)
        self.assertEqual(db_person.id, tmp_person.id)
        self.assertEqual(db_person.email, tmp_person.email)

    @override_settings(INTERNAL_EMAIL_SUFFIX='osis.org')
    def test_person_from_extern_source(self):
        person_email = functools.partial(generate_person_email,
                                         domain='osis.org')
        p = PersonWithoutUserFactory.build(
            email=factory.LazyAttribute(person_email),
            source=person_source_type.DISSERTATION)
        with self.assertRaises(AttributeError):
            p.save()

    @override_settings(INTERNAL_EMAIL_SUFFIX='osis.org')
    def test_person_from_internal_source(self):
        person_email = functools.partial(generate_person_email,
                                         domain='osis.org')
        p = PersonWithoutUserFactory.build(
            email=factory.LazyAttribute(person_email))
        with self.assertDontRaise():
            p.save()

    @override_settings(INTERNAL_EMAIL_SUFFIX='osis.org')
    def test_person_without_source(self):
        person_email = functools.partial(generate_person_email,
                                         domain='osis.org')
        p = PersonWithoutUserFactory.build(
            email=factory.LazyAttribute(person_email), source=None)
        with self.assertDontRaise():
            p.save()

    def test_find_by_global_id(self):
        a_person = person.Person(global_id="123")
        a_person.save()
        dupplicated_person = person.Person(global_id="123")
        dupplicated_person.save()
        found_person = person.find_by_global_id("1234")
        return self.assertEqual(
            found_person, None,
            "find_by_global_id should return None if a record is not found.")

    def test_search_employee(self):
        a_lastname = "Dupont"
        a_firstname = "Marcel"
        a_person = person.Person(last_name=a_lastname,
                                 first_name=a_firstname,
                                 employee=True)
        a_person.save()
        self.assertEqual(person.search_employee(a_lastname)[0], a_person)
        self.assertEqual(
            len(person.search_employee("{}{}".format(a_lastname,
                                                     a_firstname))), 0)
        self.assertEqual(
            person.search_employee("{} {}".format(a_lastname, a_firstname))[0],
            a_person)
        self.assertIsNone(person.search_employee(None))
        self.assertEqual(len(person.search_employee("zzzzzz")), 0)

        a_person_2 = person.Person(last_name=a_lastname,
                                   first_name="Hervé",
                                   employee=True)
        a_person_2.save()
        self.assertEqual(len(person.search_employee(a_lastname)), 2)
        self.assertEqual(
            len(person.search_employee("{} {}".format(a_lastname,
                                                      a_firstname))), 1)

    def test_change_to_invalid_language(self):
        user = UserFactory()
        user.save()
        a_person = create_person_with_user(user)
        person.change_language(user, 'ru')
        self.assertNotEqual(a_person.language, "ru")

    def test_change_language(self):
        user = UserFactory()
        user.save()
        create_person_with_user(user)
        person.change_language(user, "en")
        a_person = person.find_by_user(user)
        self.assertEqual(a_person.language, "en")

    def test_calculate_age(self):
        a_person = PersonFactory()
        a_person.birth_date = datetime.datetime.now() - datetime.timedelta(
            days=((30 * 365) + 15))
        self.assertEqual(person.calculate_age(a_person), 30)
        a_person.birth_date = datetime.datetime.now() - datetime.timedelta(
            days=((30 * 365) - 5))
        self.assertEqual(person.calculate_age(a_person), 29)

    def test_is_central_manager(self):
        a_person = PersonFactory()
        self.assertFalse(a_person.is_central_manager)

        del a_person.is_central_manager
        a_person.user.groups.add(Group.objects.get(name=CENTRAL_MANAGER_GROUP))
        self.assertTrue(a_person.is_central_manager)

    def test_is_faculty_manager(self):
        a_person = PersonFactory()
        self.assertFalse(a_person.is_faculty_manager)

        del a_person.is_faculty_manager
        a_person.user.groups.add(Group.objects.get(name=FACULTY_MANAGER_GROUP))
        self.assertTrue(a_person.is_faculty_manager)

    def test_is_sic(self):
        a_person = PersonFactory()
        self.assertFalse(a_person.is_sic)

        a_person = SICFactory()
        self.assertTrue(a_person.is_sic)

    def test_show_username_from_person_with_user(self):
        self.assertEqual(self.person_with_user.username(), "user_with_person")

    def test_show_username_from_person_without_user(self):
        self.assertEqual(self.person_without_user.username(), None)

    def test_show_first_name_from_person_with_first_name(self):
        self.assertEqual(self.person_with_user.get_first_name(),
                         self.person_with_user.first_name)

    def test_show_first_name_from_person_without_first_name(self):
        self.person_with_user.first_name = None
        self.person_with_user.save()
        self.assertEqual(self.person_with_user.get_first_name(),
                         self.person_with_user.user.first_name)

    def test_show_first_name_from_person_without_user(self):
        self.person_with_user.first_name = None
        self.person_with_user.user = None
        self.person_with_user.save()
        self.assertEqual(self.person_with_user.get_first_name(), "-")

    def test_get_user_interface_language_with_person_user(self):
        self.assertEqual(
            get_user_interface_language(self.person_with_user.user), "fr-be")

    def test_get_user_interface_language_with_user_without_person(self):
        self.assertEqual(get_user_interface_language(self.an_user), "fr-be")

    def test_str_function_with_data(self):
        self.person_with_user.middle_name = "Junior"
        self.person_with_user.save()
        self.assertEqual(self.person_with_user.__str__(), "DOE, John Junior")

    def test_change_language_with_user_with_person(self):
        change_language(self.user_for_person, "en")
        self.person_with_user.refresh_from_db()
        self.assertEqual(self.person_with_user.language, "en")

    def test_change_language_with_user_without_person(self):
        self.assertFalse(change_language(self.an_user, "en"))

    def test_is_linked_to_entity_in_charge_of_learning_unit_year(self):
        person_entity = PersonEntityFactory(person=self.person_with_user)
        luy = LearningUnitYearFactory()

        self.assertFalse(
            self.person_with_user.
            is_linked_to_entity_in_charge_of_learning_unit_year(luy))

        EntityContainerYearFactory(
            learning_container_year=luy.learning_container_year,
            entity=person_entity.entity,
            type=REQUIREMENT_ENTITY)

        self.assertTrue(
            self.person_with_user.
            is_linked_to_entity_in_charge_of_learning_unit_year(luy))

    def test_is_linked_to_entity_in_charge_of_external_learning_unit_year(
            self):
        person_entity = PersonEntityFactory(person=self.person_with_user)
        luy = LearningUnitYearFactory()
        external_luy = ExternalLearningUnitYearFactory(learning_unit_year=luy)

        self.assertFalse(
            self.person_with_user.
            is_linked_to_entity_in_charge_of_learning_unit_year(luy))

        external_luy.requesting_entity = person_entity.entity
        external_luy.save()

        self.assertTrue(
            self.person_with_user.
            is_linked_to_entity_in_charge_of_learning_unit_year(luy))
Ejemplo n.º 6
0
class HomeTest(TestCase):
    def setUp(self):
        Group.objects.get_or_create(name='tutors')
        self.person = PersonFactory()
        self.tutor = TutorFactory(person=self.person)

        attribution_permission = Permission.objects.get(
            codename='can_access_attribution')
        self.person.user.user_permissions.add(attribution_permission)

        today = datetime.datetime.today()
        self.academic_year = AcademicYearFactory(
            year=today.year,
            start_date=today - datetime.timedelta(days=5),
            end_date=today + datetime.timedelta(days=5))
        self.learning_unit_year = LearningUnitYearFactory(
            academic_year=self.academic_year)
        self.learning_unit_year.learning_container_year = LearningContainerYearFactory(
            academic_year=self.learning_unit_year.academic_year,
            in_charge=True)
        self.learning_unit_year.save()
        self.attribution = AttributionFactory(
            function=function.CO_HOLDER,
            learning_unit_year=self.learning_unit_year,
            tutor=self.tutor,
            external_id=ATTRIBUTION_EXTERNAL_ID)

        self.url = reverse('attribution_home')
        self.client.force_login(self.person.user)

    def test_user_not_logged(self):
        self.client.logout()
        response = self.client.get(self.url)

        self.assertRedirects(response, "/login/?next={}".format(self.url))

    def test_user_without_permission(self):
        a_person = PersonFactory()
        self.client.force_login(a_person.user)

        response = self.client.get(self.url)

        self.assertEqual(response.status_code, ACCESS_DENIED)
        self.assertTemplateUsed(response, "access_denied.html")

    def test_person_without_global_id(self):
        self.person.global_id = None
        self.person.save()

        response = self.client.get(self.url)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['attributions'], None)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'], 0)
        self.assertEqual(response.context['tot_practical'], 0)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], None)
        self.assertEqual(response.context['error'], True)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

    def test_user_without_person(self):
        self.person.delete()

        response = self.client.get(self.url)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], None)
        self.assertEqual(response.context['attributions'], None)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'], None)
        self.assertEqual(response.context['tot_practical'], None)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], None)
        self.assertEqual(response.context['error'], False)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

    def test_user_without_tutor(self):
        self.tutor.delete()

        response = self.client.get(self.url)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['attributions'], None)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'], None)
        self.assertEqual(response.context['tot_practical'], None)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], None)
        self.assertEqual(response.context['error'], False)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

    def test_without_current_academic_year(self):
        self.academic_year.year -= 1
        self.academic_year.end_date = datetime.datetime.today(
        ) - datetime.timedelta(days=3)
        self.academic_year.save()

        response = self.client.get(self.url)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['attributions'], None)
        self.assertEqual(response.context['year'],
                         int(datetime.datetime.now().year))
        self.assertEqual(response.context['tot_lecturing'], 0)
        self.assertEqual(response.context['tot_practical'], 0)
        self.assertEqual(response.context['academic_year'], None)
        self.assertEqual(response.context['global_id'], None)
        self.assertEqual(response.context['error'], True)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

    @mock.patch('requests.get',
                side_effect=mock_request_none_attribution_charge)
    def test_without_attributions(self, mock_requests_get):
        response = self.client.get(self.url, mock_requests_get)

        self.assertTrue(mock_requests_get.called)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['attributions'], None)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'], 0)
        self.assertEqual(response.context['tot_practical'], 0)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], self.person.global_id)
        self.assertEqual(response.context['error'], False)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

    @override_settings()
    def test_when_not_configuration_for_attribution(self):
        del settings.ATTRIBUTION_CONFIG

        response = self.client.get(self.url)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['attributions'], None)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'], 0)
        self.assertEqual(response.context['tot_practical'], 0)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], self.person.global_id)
        self.assertEqual(response.context['error'], True)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

    @mock.patch('requests.get', side_effect=RequestException)
    def test_when_exception_occured_during_request_of_webservice(
            self, mock_requests_get):
        response = self.client.get(self.url)

        self.assertTrue(mock_requests_get.called)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['attributions'], None)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'], 0)
        self.assertEqual(response.context['tot_practical'], 0)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], self.person.global_id)
        self.assertEqual(response.context['error'], True)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

    @override_settings(ATTRIBUTION_CONFIG=get_attribution_config_settings())
    @mock.patch('requests.get',
                side_effect=mock_request_single_attribution_charge)
    def test_for_one_attribution(self, mock_requests_get):

        response = self.client.get(self.url)

        self.assertTrue(mock_requests_get.called)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'],
                         LEARNING_UNIT_LECTURING_DURATION)
        self.assertEqual(response.context['tot_practical'],
                         LEARNING_UNIT_PRACTICAL_EXERCISES_DURATION)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], self.person.global_id)
        self.assertEqual(response.context['error'], False)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

        self.assertEqual(len(response.context['attributions']), 1)
        attribution = response.context['attributions'][0]
        self.assertEqual(attribution['acronym'],
                         self.learning_unit_year.acronym)
        self.assertEqual(attribution['title'],
                         self.learning_unit_year.specific_title)
        self.assertEqual(attribution['start_year'],
                         self.attribution.start_year)
        self.assertEqual(attribution['lecturing_allocation_charge'],
                         str(LEARNING_UNIT_LECTURING_DURATION))
        self.assertEqual(attribution['practice_allocation_charge'],
                         str(LEARNING_UNIT_PRACTICAL_EXERCISES_DURATION))
        self.assertEqual(attribution['percentage_allocation_charge'], '75.0')
        self.assertEqual(attribution['weight'],
                         self.learning_unit_year.credits)
        self.assertEqual(attribution['url_schedule'], "")
        self.assertEqual(
            attribution['url_students_list_email'],
            'mailto:{}-{}@listes-student.uclouvain.be'.format(
                self.learning_unit_year.acronym.lower(),
                self.academic_year.year))
        self.assertEqual(attribution['function'], self.attribution.function)
        self.assertEqual(attribution['year'], self.academic_year.year)
        self.assertEqual(attribution['learning_unit_year_url'], "")
        self.assertEqual(attribution['learning_unit_year'],
                         self.learning_unit_year)
        self.assertEqual(attribution['tutor_id'], self.tutor.id)

    @mock.patch('requests.get',
                side_effect=mock_request_multiple_attributions_charge)
    def test_for_multiple_attributions(self, mock_requests_get):
        an_other_attribution = AttributionFactory(
            function=function.CO_HOLDER,
            learning_unit_year=self.learning_unit_year,
            tutor=self.tutor,
            external_id=OTHER_ATTRIBUTION_EXTERNAL_ID)

        response = self.client.get(self.url)

        self.assertTrue(mock_requests_get.called)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'],
                         LEARNING_UNIT_LECTURING_DURATION)
        self.assertEqual(response.context['tot_practical'],
                         LEARNING_UNIT_PRACTICAL_EXERCISES_DURATION)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], self.person.global_id)
        self.assertEqual(response.context['error'], False)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

        self.assertEqual(len(response.context['attributions']), 2)

    @mock.patch('requests.get',
                side_effect=mock_request_multiple_attributions_charge)
    def test_with_attribution_not_recognized(self, mock_requests_get):
        an_other_attribution = AttributionFactory(
            learning_unit_year=self.learning_unit_year,
            tutor=self.tutor,
            external_id=OTHER_ATTRIBUTION_EXTERNAL_ID)

        inexisting_external_id = "osis.attribution_8082"
        attribution_not_in_json = AttributionFactory(
            learning_unit_year=self.learning_unit_year,
            tutor=self.tutor,
            external_id=inexisting_external_id)

        response = self.client.get(self.url)

        self.assertTrue(mock_requests_get.called)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'],
                         LEARNING_UNIT_LECTURING_DURATION)
        self.assertEqual(response.context['tot_practical'],
                         LEARNING_UNIT_PRACTICAL_EXERCISES_DURATION)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], self.person.global_id)
        self.assertEqual(response.context['error'], False)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

        self.assertEqual(len(response.context['attributions']), 2)

    @mock.patch(
        'requests.get',
        side_effect=mock_request_multiple_attributions_charge_with_missing_values
    )
    def test_with_missing_values(self, mock_requests_get):
        an_other_attribution = AttributionFactory(
            learning_unit_year=self.learning_unit_year,
            tutor=self.tutor,
            external_id=OTHER_ATTRIBUTION_EXTERNAL_ID)

        response = self.client.get(self.url)

        self.assertTrue(mock_requests_get.called)

        self.assertTemplateUsed(response, 'tutor_charge.html')

        self.assertEqual(response.context['user'], self.person.user)
        self.assertEqual(response.context['year'],
                         int(self.academic_year.year))
        self.assertEqual(response.context['tot_lecturing'],
                         LEARNING_UNIT_LECTURING_DURATION)
        self.assertEqual(response.context['tot_practical'],
                         LEARNING_UNIT_PRACTICAL_EXERCISES_DURATION)
        self.assertEqual(response.context['academic_year'], self.academic_year)
        self.assertEqual(response.context['global_id'], self.person.global_id)
        self.assertEqual(response.context['error'], False)

        self.assertIsInstance(response.context['formset'], BaseFormSet)

        attributions = response.context['attributions']
        reduced_list_attributions = map(
            lambda attribution: [
                attribution["lecturing_allocation_charge"], attribution[
                    'practice_allocation_charge'], attribution[
                        'percentage_allocation_charge']
            ], attributions)
        self.assertIn([str(LEARNING_UNIT_LECTURING_DURATION), None, "25.0"],
                      reduced_list_attributions)
Ejemplo n.º 7
0
 def test_donot_return_teacher_only_in_tutor_group(self):
     a_tutor_person = PersonFactory()
     a_tutor_person.user.groups.add(Group.objects.get(name=TUTOR))
     a_tutor_person.save()
     self.assertCountEqual(UserListView().get_queryset(), [])
Ejemplo n.º 8
0
class TestUploadXls(TestCase):
    def setUp(self):
        today = datetime.datetime.today()
        twenty_days = datetime.timedelta(days=20)

        #Take same academic year as the one in the associated xls file
        an_academic_year = AcademicYearFactory(year=2017)

        a_learning_unit_year = LearningUnitYearFakerFactory(
            academic_year=an_academic_year, acronym=LEARNING_UNIT_ACRONYM)

        tutor = TutorFactory()

        an_academic_calendar = AcademicCalendarFactory(
            academic_year=an_academic_year,
            start_date=today - twenty_days,
            end_date=today + twenty_days,
            reference=academic_calendar_type.SCORES_EXAM_SUBMISSION)
        SessionExamCalendarFactory(number_session=number_session.ONE,
                                   academic_calendar=an_academic_calendar)
        AttributionFactory(learning_unit_year=a_learning_unit_year,
                           tutor=tutor)
        a_session_exam = SessionExamFactory(
            number_session=number_session.ONE,
            learning_unit_year=a_learning_unit_year)

        self.person_student_1 = PersonFactory(email=EMAIL_1)
        person_student_2 = PersonFactory(email=EMAIL_2)

        student_1 = StudentFactory(registration_id=REGISTRATION_ID_1,
                                   person=self.person_student_1)
        student_2 = StudentFactory(registration_id=REGISTRATION_ID_2,
                                   person=person_student_2)

        an_offer_year = OfferYearFactory(academic_year=an_academic_year,
                                         acronym=OFFER_ACRONYM)
        offer_enrollment_1 = OfferEnrollmentFactory(offer_year=an_offer_year,
                                                    student=student_1)
        offer_enrollment_2 = OfferEnrollmentFactory(offer_year=an_offer_year,
                                                    student=student_2)

        learning_unit_enrollment_1 = LearningUnitEnrollmentFactory(
            learning_unit_year=a_learning_unit_year,
            offer_enrollment=offer_enrollment_1)
        learning_unit_enrollment_2 = LearningUnitEnrollmentFactory(
            learning_unit_year=a_learning_unit_year,
            offer_enrollment=offer_enrollment_2)

        ExamEnrollmentFactory(
            session_exam=a_session_exam,
            learning_unit_enrollment=learning_unit_enrollment_1)
        ExamEnrollmentFactory(
            session_exam=a_session_exam,
            learning_unit_enrollment=learning_unit_enrollment_2)

        user = tutor.person.user
        self.client = Client()
        self.client.force_login(user=user)
        self.url = reverse(
            'upload_encoding',
            kwargs={'learning_unit_year_id': a_learning_unit_year.id})

    def test_with_no_file_uploaded(self):
        response = self.client.post(self.url, {'file': ''}, follow=True)
        messages = list(response.context['messages'])

        self.assertEqual(len(messages), 1)
        self.assertEqual(messages[0].tags, 'error')
        self.assertEqual(messages[0].message, _('no_file_submitted'))

    def test_with_incorrect_format_file(self):
        with open("assessments/tests/resources/bad_format.txt",
                  'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            self.assertEqual(len(messages), 1)
            self.assertEqual(messages[0].tags, 'error')
            self.assertEqual(messages[0].message, _('file_must_be_xlsx'))

    def test_with_no_scores_encoded(self):
        with open("assessments/tests/resources/empty_scores.xlsx",
                  'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            self.assertEqual(len(messages), 1)
            self.assertEqual(messages[0].tags, 'error')
            self.assertEqual(messages[0].message, _('no_score_injected'))

    def test_with_incorrect_justification(self):
        INCORRECT_LINES = '13'
        with open("assessments/tests/resources/incorrect_justification.xlsx",
                  'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(
                ('error', "%s : %s %s" % (_('justification_invalid_value'),
                                          _('Line'), INCORRECT_LINES)),
                messages_tag_and_content)

    def test_with_numbers_outside_scope(self):
        INCORRECT_LINES = '12, 13'
        with open("assessments/tests/resources/incorrect_scores.xlsx",
                  'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(
                ('error', "%s : %s %s" % (_('scores_must_be_between_0_and_20'),
                                          _('Line'), INCORRECT_LINES)),
                messages_tag_and_content)

    def test_with_correct_score_sheet(self):
        NUMBER_CORRECT_SCORES = "2"
        SCORE_1 = 16
        SCORE_2 = exam_enrollment_justification_type.ABSENCE_UNJUSTIFIED
        with open("assessments/tests/resources/correct_score_sheet.xlsx",
                  'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(('success', '%s %s' %
                           (NUMBER_CORRECT_SCORES, _('score_saved'))),
                          messages_tag_and_content)

            exam_enrollment_1 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_1)
            self.assertEqual(exam_enrollment_1.score_draft, SCORE_1)

            exam_enrollment_2 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_2)
            self.assertEqual(exam_enrollment_2.justification_draft, SCORE_2)

    def test_with_formula(self):
        NUMBER_SCORES = "2"
        SCORE_1 = 15
        SCORE_2 = 17
        with open("assessments/tests/resources/score_sheet_with_formula.xlsx",
                  'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(
                ('success', '%s %s' % (NUMBER_SCORES, _('score_saved'))),
                messages_tag_and_content)

            exam_enrollment_1 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_1)
            self.assertEqual(exam_enrollment_1.score_draft, SCORE_1)

            exam_enrollment_2 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_2)
            self.assertEqual(exam_enrollment_2.score_draft, SCORE_2)

    def test_with_incorrect_formula(self):
        NUMBER_CORRECT_SCORES = "1"
        INCORRECT_LINE = "13"
        SCORE_1 = 15
        with open("assessments/tests/resources/incorrect_formula.xlsx",
                  'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(
                ('error', "%s : %s %s" % (_('scores_must_be_between_0_and_20'),
                                          _('Line'), INCORRECT_LINE)),
                messages_tag_and_content)
            self.assertIn(('success', '%s %s' %
                           (NUMBER_CORRECT_SCORES, _('score_saved'))),
                          messages_tag_and_content)
            exam_enrollment_1 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_1)
            self.assertEqual(exam_enrollment_1.score_draft, SCORE_1)

    def test_with_registration_id_not_matching_email(self):
        INCORRECT_LINES = '12, 13'
        with open(
                "assessments/tests/resources/registration_id_not_matching_email.xlsx",
                'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(('error', "%s : %s %s" %
                           (_('registration_id_does_not_match_email'),
                            _('Line'), INCORRECT_LINES)),
                          messages_tag_and_content)

    def test_with_correct_score_sheet_white_spaces_around_emails(self):
        NUMBER_CORRECT_SCORES = "2"
        SCORE_1 = 16
        SCORE_2 = exam_enrollment_justification_type.ABSENCE_UNJUSTIFIED
        with open(
                "assessments/tests/resources/correct_score_sheet_spaces_around_emails.xlsx",
                'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(('success', '%s %s' %
                           (NUMBER_CORRECT_SCORES, _('score_saved'))),
                          messages_tag_and_content)

            exam_enrollment_1 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_1)
            self.assertEqual(exam_enrollment_1.score_draft, SCORE_1)

            exam_enrollment_2 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_2)
            self.assertEqual(exam_enrollment_2.justification_draft, SCORE_2)

    def test_with_correct_score_sheet_white_one_empty_email(self):
        self.person_student_1.email = None
        self.person_student_1.save()

        NUMBER_CORRECT_SCORES = "2"
        SCORE_1 = 16
        SCORE_2 = exam_enrollment_justification_type.ABSENCE_UNJUSTIFIED
        with open(
                "assessments/tests/resources/correct_score_sheet_one_empty_email.xlsx",
                'rb') as score_sheet:
            response = self.client.post(self.url, {'file': score_sheet},
                                        follow=True)
            messages = list(response.context['messages'])

            messages_tag_and_content = _get_list_tag_and_content(messages)
            self.assertIn(('success', '%s %s' %
                           (NUMBER_CORRECT_SCORES, _('score_saved'))),
                          messages_tag_and_content)

            exam_enrollment_1 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_1)
            self.assertEqual(exam_enrollment_1.score_draft, SCORE_1)

            exam_enrollment_2 = ExamEnrollment.objects.get(
                learning_unit_enrollment__offer_enrollment__student__registration_id
                =REGISTRATION_ID_2)
            self.assertEqual(exam_enrollment_2.justification_draft, SCORE_2)