Esempio n. 1
0
    def test_copy_read_only(self):
        """test that copy centers are uneditable once created."""
        copy_center = RegistrationCenterFactory(center_type=RegistrationCenter.Types.COPY)

        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        self.assertEqual(force_text(cm.exception.message), 'Copy centres are read-only.')
Esempio n. 2
0
 def test_copy_of(self):
     """Exercise build_copy_info() for a center that is a copy"""
     original = RegistrationCenterFactory()
     copy_center = RegistrationCenterFactory(copy_of=original)
     expected = '{}: {}'.format(STRINGS['copy_of'],
                                copy_center.copy_of.center_id)
     self.assertEqual(build_copy_info(copy_center), expected)
Esempio n. 3
0
    def setUp(self):
        subconstituency_name = os.environ.get('ROLLGEN_TEST_SUBCONSTITUENCY_NAME', '')
        subconstituency_name = subconstituency_name.decode('utf-8')

        if not subconstituency_name:
            subconstituency_name = generate_arabic_place_name()

        center_name = os.environ.get('ROLLGEN_TEST_CENTER_NAME', '')
        center_name = center_name.decode('utf-8')

        if not center_name:
            center_name = generate_arabic_place_name()

        subconstituency = SubConstituencyFactory(name_arabic=subconstituency_name)

        self.center = RegistrationCenterFactory(subconstituency=subconstituency, name=center_name)

        # For the center that has copies, I give it the max number of copies possible in order
        # to force the 'copied by' string to be as long as possible to reveal any line wrapping
        # problems that result.
        self.original_center = RegistrationCenterFactory()
        self.copy_centers = RegistrationCenterFactory.create_batch(settings.N_MAX_COPY_CENTERS,
                                                                   copy_of=self.original_center)

        self.election = ElectionFactory()
Esempio n. 4
0
    def setUp(self):
        self.center = RegistrationCenterFactory(
            name=generate_arabic_place_name())

        self.center_with_a_copy = RegistrationCenterFactory(
            name=generate_arabic_place_name())

        self.copy_center = RegistrationCenterFactory(
            name=generate_arabic_place_name(), copy_of=self.center_with_a_copy)

        # Create an unused center just to clutter things up a bit.
        self.unused_center = RegistrationCenterFactory(
            name=generate_arabic_place_name())

        # Create a few voters and register them at each of these centers (except the copy center
        # because voters can't register at copy centers).
        self.n_voters = 3

        archive_time = now()

        self.voters = {}
        for center in (self.center, self.center_with_a_copy,
                       self.unused_center):
            self.voters[center] = create_voters(self.n_voters, FEMALE, center)
            # Also create an archived registration for each center to ensure that
            # get_voter_roll() ignores it.
            voter = VoterFactory(post__center=center)
            registration = voter.registration
            registration.archive_time = archive_time
            registration.save()
Esempio n. 5
0
    def test_edit_view(self):
        self.center1 = RegistrationCenterFactory()
        self.center2 = RegistrationCenterFactory()
        data = {
            'name': 'My Changeset',
            'change': str(Changeset.CHANGE_CENTER),
            'how_to_select': str(Changeset.SELECT_CENTERS),
            'selected_centers_1': [str(self.center1.pk)],
            'target_center_1': str(self.center2.pk),
            'justification': 'Just because',
        }
        changeset = ChangesetFactory(
            name=data['name'],
            change=Changeset.CHANGE_CENTER,
            how_to_select=Changeset.SELECT_CENTERS,
            target_center=self.center2,
            justification='Just because',
        )
        changeset.selected_centers.add(self.center1)
        url = reverse('edit_changeset', kwargs={'pk': changeset.pk})

        rsp = self.client.get(url)
        self.assertEqual(OK, rsp.status_code)

        data['name'] = 'My Edited Changeset'
        data['justification'] = 'My edited justficiation'

        rsp = self.client.post(url, data=data, follow=False)
        self.assertEqual(302,
                         rsp.status_code)  # , msg=rsp.content.decode('utf-8'))
        self.assertRedirects(rsp, reverse('browse_changesets'))

        changeset = Changeset.objects.get()
        self.assertEqual(data['name'], changeset.name)
        self.assertEqual(data['justification'], changeset.justification)
Esempio n. 6
0
 def test_copied_by_one(self):
     """Exercise build_copy_info() for a center that has a single copy"""
     original = RegistrationCenterFactory()
     RegistrationCenterFactory(copy_of=original)
     expected = '{}: {}'.format(STRINGS['copied_by_singular'],
                                original.copied_by.all()[0].center_id)
     self.assertEqual(build_copy_info(original), expected)
Esempio n. 7
0
    def test_find_invalid_center_ids(self):
        """exercise find_invalid_center_ids()"""
        centers = [RegistrationCenterFactory(), RegistrationCenterFactory()]
        center_ids = [center.center_id for center in centers]
        center_ids += [99999, 88888]

        # Note that order is preserved
        self.assertEqual([99999, 88888], find_invalid_center_ids(center_ids))
Esempio n. 8
0
    def test_copy_center_must_remain_copy_center(self):
        """test that a copy center can't be made into a non-copy center"""
        original_center = RegistrationCenterFactory()
        copy_center = RegistrationCenterFactory(copy_of=original_center)
        copy_center.copy_of = None

        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        self.assertEqual(force_text(cm.exception.message), 'Copy centres are read-only.')
Esempio n. 9
0
 def test_mismatched_numbers(self):
     center1 = RegistrationCenterFactory()
     center2 = RegistrationCenterFactory()
     self.check_it_out("%d*%d" % (center1.center_id, center2.center_id),
                       POLLING_REPORT_CENTER_MISMATCH,
                       SMS.POLLING_REPORT_INVALID,
                       False,
                       False,
                       expect_center_opened=False)
Esempio n. 10
0
    def test_copy_read_only(self):
        """test that copy centers are uneditable once created."""
        copy_center = RegistrationCenterFactory(
            center_type=RegistrationCenter.Types.COPY)

        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        self.assertEqual(force_text(cm.exception.message),
                         'Copy centres are read-only.')
 def test_copy_center_is_readonly(self):
     """Ensure copy centers can't be changed except for deleted status"""
     original = RegistrationCenterFactory()
     copy = RegistrationCenterFactory(copy_of=original)
     center_admin = RegistrationCenterAdmin(RegistrationCenter, admin.site)
     fields = set(center_admin.get_fields(Mock(), obj=copy))
     readonly_fields = set(center_admin.get_readonly_fields(Mock(), obj=copy))
     readwrite_fields = list(fields - readonly_fields)
     self.assertEqual(readwrite_fields, ['deleted'])
Esempio n. 12
0
 def setUp(self):
     self.sms = SMSFactory()
     self.citizen = CitizenFactory(national_id=219782058018)
     self.center = RegistrationCenterFactory()
     RegistrationCenterFactory(center_id=self.center.center_id,
                               deleted=True)
     self.mock_response = Mock()
     self.reg_period = RegistrationPeriodFactory(start_time=PAST_DAY,
                                                 end_time=FUTURE_DAY)
Esempio n. 13
0
 def test_copy_registration_center(self):
     """test that people can't register against a copy center"""
     copy_center = RegistrationCenterFactory()
     copy_center.copy_of = self.center
     copy_center.save()
     # try to register
     result = process_registration_request(
         center_id=copy_center.center_id, national_id=self.citizen.national_id, sms=self.sms
     )
     self.assertEqual(result.message_code, constants.RESPONSE_CENTER_ID_INVALID)
Esempio n. 14
0
    def test_copy_center_requires_copy_type(self):
        """test that a copy center must have the correct type"""
        original_center = RegistrationCenterFactory()
        copy_center = RegistrationCenterFactory.build(copy_of=original_center)
        copy_center.center_type = RegistrationCenter.Types.GENERAL

        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        self.assertEqual(cm.exception.message,
                         'Copy centre type must be "copy".')
Esempio n. 15
0
 def test_copied_by_multiple(self):
     """Exercise build_copy_info() for a center that has multiple copies"""
     original = RegistrationCenterFactory()
     copy_centers = RegistrationCenterFactory.create_batch(3,
                                                           copy_of=original)
     copy_center_ids = sorted([center.center_id for center in copy_centers])
     copy_center_ids = (ARABIC_COMMA + ' ').join(map(str, copy_center_ids))
     expected = '{}: {}'.format(STRINGS['copied_by_plural'],
                                copy_center_ids)
     self.assertEqual(build_copy_info(original), expected)
Esempio n. 16
0
    def test_copy_of_copy_fails(self):
        """test that a copy center can't be a copy of another copy center"""
        original_center = RegistrationCenterFactory()
        copy_center = RegistrationCenterFactory(copy_of=original_center)
        copy_copy_center = RegistrationCenterFactory.build(copy_of=copy_center)

        with self.assertRaises(ValidationError) as cm:
            copy_copy_center.clean()
        self.assertEqual(cm.exception.message,
                         'A copy centre cannot copy another copy centre.')
Esempio n. 17
0
 def test_copy_registration_center(self):
     """test that people can't register against a copy center"""
     copy_center = RegistrationCenterFactory()
     copy_center.copy_of = self.center
     copy_center.save()
     # try to register
     result = process_registration_request(
         center_id=copy_center.center_id,
         national_id=self.citizen.national_id,
         sms=self.sms)
     self.assertEqual(result.message_code,
                      constants.RESPONSE_CENTER_ID_INVALID)
Esempio n. 18
0
    def test_noncopy_center_cannot_become_copy_center(self):
        """test that a non-copy center can't be made into a copy center"""
        original_center = RegistrationCenterFactory()
        copy_center = RegistrationCenterFactory()

        copy_center.copy_of = original_center
        copy_center.center_type = RegistrationCenter.Types.COPY

        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        self.assertEqual(force_text(cm.exception.message),
                         'A centre may not be changed to a copy centre.')
    def test_ensure_copied_center_undeletable(self):
        """Ensure centers that have copies can't be deleted"""
        original = RegistrationCenterFactory()
        copy = RegistrationCenterFactory(copy_of=original)
        center_admin = RegistrationCenterAdmin(RegistrationCenter, admin.site)
        self.assertIn('deleted', center_admin.get_readonly_fields(Mock(), obj=original))

        # However, if the copy is soft deleted, then it's OK to delete the original
        copy.deleted = True
        copy.save()
        center_admin = RegistrationCenterAdmin(RegistrationCenter, admin.site)
        self.assertNotIn('deleted', center_admin.get_readonly_fields(Mock(), obj=original))
Esempio n. 20
0
    def test_max_copies_per_center_limit(self):
        """test that register.models.N_MAX_COPY_CENTERS is respected"""
        original_center = RegistrationCenterFactory()
        create_batch(RegistrationCenterFactory,
                     settings.N_MAX_COPY_CENTERS,
                     copy_of=original_center)

        copy_center = RegistrationCenterFactory.build(copy_of=original_center)
        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        msg = 'Copy centre already has the maximum number of copies ({n_max}).'
        self.assertEqual(cm.exception.message,
                         msg.format(n_max=settings.N_MAX_COPY_CENTERS))
Esempio n. 21
0
 def setUp(self):
     self.original = RegistrationCenterFactory()
     self.copy = RegistrationCenterFactory(copy_of=self.original)
     self.polling_locations = get_all_polling_locations()
     self.election = ElectionFactory(
         polling_start_time=now() - datetime.timedelta(hours=1),
         polling_end_time=now() + datetime.timedelta(hours=1),
     )
     # add decoy elections before/after the real one
     self.decoy_before_election = ElectionFactory(
         polling_start_time=self.election.polling_start_time -
         datetime.timedelta(days=5),
         polling_end_time=self.election.polling_end_time -
         datetime.timedelta(days=5),
     )
     self.decoy_after_election = ElectionFactory(
         polling_start_time=self.election.polling_start_time +
         datetime.timedelta(days=5),
         polling_end_time=self.election.polling_end_time +
         datetime.timedelta(days=5),
     )
     self.test_office_1 = 1
     self.test_office_2 = 2
     self.test_region = 3
     self.polling_centers = {
         '11001': {
             'polling_center_code': 11001,
             'office_id': self.test_office_1,
             'subconstituency_id': 2,
             'region': Office.REGION_NAMES[self.test_region],
             'country': 'Libya'
         },
         '11002': {
             'polling_center_code': 11002,
             'office_id': self.test_office_2,
             'subconstituency_id': 2,
             'region': Office.REGION_NAMES[self.test_region],
             'country': 'Libya'
         },
         '11003': {
             'polling_center_code': 11003,
             'office_id': self.test_office_1,
             'subconstituency_id': 2,
             'region': Office.REGION_NAMES[self.test_region],
             'country': 'Libya'
         }
     }
     self.center_opens = []
     self.center_reports = []
     self.inactive_for_election = ['11003']
Esempio n. 22
0
 def setUp(self):
     self.center1 = RegistrationCenterFactory()
     self.center2 = RegistrationCenterFactory()
     self.center3 = RegistrationCenterFactory()
     self.data = {
         'name': 'My Changeset',
         'change': str(Changeset.CHANGE_CENTER),
         'how_to_select': str(Changeset.SELECT_CENTERS),
         # django-selectable appends "_1" to the field name for the form name that
         # has the actual data submitted:
         'selected_centers_1': [str(self.center1.pk), str(self.center2.pk)],
         'target_center_1': str(self.center3.pk),
         'justification': 'Just because',
     }
Esempio n. 23
0
    def test_delete_all_copy_centers(self):
        """test RegistrationCenterManager.delete_all_copy_centers()"""
        original_center = RegistrationCenterFactory()
        copy_center = RegistrationCenterFactory(copy_of=original_center)

        RegistrationCenter.objects.delete_all_copy_centers()

        # Ensure the copy center is gone...
        with self.assertRaises(RegistrationCenter.DoesNotExist):
            RegistrationCenter.objects.get(pk=copy_center.id)

        # ...but it still exists if you know where to look.
        self.assertEqual(
            copy_center,
            RegistrationCenter.objects.unfiltered().get(pk=copy_center.id))
Esempio n. 24
0
 def test_user_can_change_from_inactivated_center(self):
     # User should be able to change registration center, even if previous center was
     # inactivated.
     # Create a registration and inactivate the center
     citizen = CitizenFactory()
     inactivated_center = RegistrationCenterFactory()
     self.receive("%s %s" % (citizen.national_id, inactivated_center.center_id), self.conn, fields=self.fields)
     inactivated_center.reg_open = False
     inactivated_center.save()
     # User registers at a new center
     new_center = RegistrationCenterFactory()
     self.receive("%s %s" % (citizen.national_id, new_center.center_id), self.conn, fields=self.fields)
     self.assertEqual(constants.MESSAGE_1, self.get_last_response_code())
     new_reg = models.Registration.objects.get(citizen=citizen)
     self.assertEqual(new_reg.registration_center, new_center)
Esempio n. 25
0
 def setUp(self):
     super(BadMessageTestPhoneActivatedNeitherOneNorTwoNumbers,
           self).setUp()
     self.center = RegistrationCenterFactory()
     # Activate the phone to the center:
     StaffPhone.objects.create(phone_number=self.NUMBER,
                               registration_center=self.center)
Esempio n. 26
0
    def test_new_view_no_centers(self):
        """Pass criteria that generate no centers to the new job form and test output"""
        # This is the only validation that happens at the view level. All other validation happens
        # in the form.
        no_reg_center = RegistrationCenterFactory.build()
        no_reg_center.reg_open = False
        no_reg_center.save()
        with override_settings(ROLLGEN_OUTPUT_DIR=self.faux_output_dir):
            response = self.client.post(reverse('rollgen:new'),
                                        {'name': 'kjghdhjdhjghfkjhgdf',
                                         'center_selection_type': 'by_center_text_list',
                                         'center_text_list': [str(no_reg_center.center_id)],
                                         'phase': 'polling',
                                         'forgive_no_voters': False,
                                         'forgive_no_office': False,
                                         }
                                        )

        self.assertResponseOK(response)
        self.assertTemplateUsed(response, 'rollgen/new.html')

        context = response.context

        expected_keys = ('form', )
        self.assertTrue(set(expected_keys) < set(context.keys()))
        self.assertIsInstance(context['form'], NewJobForm)
        self.assertFormError(response, 'form', None,
                             "The criteria you specified didn't match any active centres.")
Esempio n. 27
0
 def test_center_may_be_soft_deleted(self):
     """Unicode method of StaffPhone associated with deleted center should not fail."""
     rc = RegistrationCenterFactory(deleted=True)
     phone = StaffPhoneFactory(registration_center=rc)
     # re-fetch the StaffPhone
     fetched_phone = StaffPhone.objects.get(id=phone.id)
     self.assertTrue(unicode(fetched_phone))
Esempio n. 28
0
    def test_can_repeat_reg(self):
        # User can send multiple messages from the same phone number for the
        # same voting center.
        citizen = CitizenFactory()
        center1 = RegistrationCenterFactory()
        # Message #1 - original registration
        self.receive("%s %s" % (citizen.national_id, center1.center_id),
                     self.conn,
                     fields=self.fields)
        # Citizen should be registered
        reg = models.Registration.objects.get(citizen=citizen)
        self.assertEqual(center1, reg.registration_center)
        self.assertEqual(constants.RESPONSE_VALID_REGISTRATION,
                         self.get_last_response_code())

        # Repeat - message 2
        self.receive("%s %s" % (citizen.national_id, center1.center_id),
                     self.conn,
                     fields=self.fields)
        # Citizen should be registered
        reg = models.Registration.objects.get(citizen=citizen)
        self.assertEqual(center1, reg.registration_center)
        # Repeated reg
        self.assertEqual(constants.MESSAGE_1, self.get_last_response_code())
        self.receive("%s %s" % (citizen.national_id, center1.center_id),
                     self.conn,
                     fields=self.fields)
        self.assertEqual(constants.MESSAGE_1, self.get_last_response_code())
Esempio n. 29
0
    def test_view_view(self):
        self.center2 = RegistrationCenterFactory(name='Centra Dua')
        changeset = ChangesetFactory(
            name='My Changeset',
            change=Changeset.CHANGE_CENTER,
            how_to_select=Changeset.SELECT_UPLOADED_NIDS,
            target_center=self.center2,
            justification='Just because',
        )
        per_page = UploadedCitizenBrowse.paginate_by
        self.assertIsNotNone(per_page)
        citizens = [CitizenFactory() for i in range(per_page + 2)]
        changeset.selected_citizens.add(*citizens)
        citizens = sorted(citizens, key=attrgetter('national_id'))

        # Get citizens affected by this changeset, sorted ascending by national ID
        url = reverse(
            'browse_uploadedcitizens') + "?changeset=%s&o=0" % changeset.pk
        rsp = self.client.get(url)
        self.assertEqual(OK, rsp.status_code)
        context = rsp.context
        object_list = context['object_list']
        self.assertLessEqual(len(object_list), per_page)
        # Should be on first page
        self.assertContains(rsp, citizens[0].national_id)
        self.assertContains(rsp, str(citizens[0]))
        # Last citizen ought to be on the next page
        self.assertNotContains(rsp, citizens[-1].national_id)
        self.assertNotContains(rsp, str(citizens[-1]))
Esempio n. 30
0
    def setUp(self):
        super(ViewsFailedJobTestCase, self).setUp()
        self.user = UserFactory(password='******')
        self.user.is_superuser = True
        self.user.save()
        self.assertTrue(
            self.client.login(username=self.user.username,
                              password='******'))

        # Generate a center with no voters to force an error when the job runs.
        self.no_voters_center = RegistrationCenterFactory(
            name=generate_arabic_place_name())

        phase = 'in-person'

        self.input_arguments['phase'] = phase
        self.input_arguments['center_ids'] = [self.no_voters_center.center_id]

        with override_settings(ROLLGEN_OUTPUT_DIR=self.faux_output_dir):
            self.job = Job(phase, [self.no_voters_center],
                           self.input_arguments, self.user.username,
                           self.output_path)
            try:
                self.job.generate_rolls()
            except NoVotersError as exception:
                # This is expected. (In fact, it's the whole point of the test.)
                handle_job_exception(exception, self.job.output_path)

        self.dirname = os.path.basename(self.job.output_path)
Esempio n. 31
0
    def test(self):
        center = RegistrationCenterFactory()
        elections = [
            {
                'polling_start_time': now() - datetime.timedelta(days=60)
            },
            {
                'polling_start_time': now() - datetime.timedelta(days=40)
            },
            {
                'polling_start_time': now() - datetime.timedelta(days=20)
            },
        ]

        for election in elections:
            election['polling_end_time'] = \
                election['polling_start_time'] + datetime.timedelta(hours=6)
            election['object'] = ElectionFactory(
                polling_start_time=election['polling_start_time'],
                polling_end_time=election['polling_end_time'],
            )
            election['staff_phone_1'] = StaffPhoneFactory(
                registration_center=center,
                creation_date=election['object'].work_start_time)
            election['staff_phone_2'] = StaffPhoneFactory(
                registration_center=center,
                creation_date=election['object'].work_end_time)

        for i, election in enumerate(elections, start=1):
            messages_for_center = message_log(
                election['object'])[center.center_id]
            self.assertEqual(len(messages_for_center), i * 2)
            # check for other junk leaking into the testcase
            for message in messages_for_center:
                self.assertEqual(message['type'], 'phonelink')
Esempio n. 32
0
    def test_new_view_no_centers(self):
        """Pass criteria that generate no centers to the new job form and test output"""
        # This is the only validation that happens at the view level. All other validation happens
        # in the form.
        no_reg_center = RegistrationCenterFactory.build()
        no_reg_center.reg_open = False
        no_reg_center.save()
        with override_settings(ROLLGEN_OUTPUT_DIR=self.faux_output_dir):
            response = self.client.post(
                reverse('rollgen:new'), {
                    'name': 'kjghdhjdhjghfkjhgdf',
                    'center_selection_type': 'by_center_text_list',
                    'center_text_list': [str(no_reg_center.center_id)],
                    'phase': 'polling',
                    'forgive_no_voters': False,
                    'forgive_no_office': False,
                })

        self.assertResponseOK(response)
        self.assertTemplateUsed(response, 'rollgen/new.html')

        context = response.context

        expected_keys = ('form', )
        self.assertTrue(set(expected_keys) < set(context.keys()))
        self.assertIsInstance(context['form'], NewJobForm)
        self.assertFormError(
            response, 'form', None,
            "The criteria you specified didn't match any active centres.")
Esempio n. 33
0
 def test_create_view(self):
     url = reverse('add_changeset')
     rsp = self.client.get(url)
     self.assertEqual(OK, rsp.status_code)
     self.center1 = RegistrationCenterFactory()
     self.center2 = RegistrationCenterFactory()
     data = {
         'name': 'My Changeset',
         'change': str(Changeset.CHANGE_CENTER),
         'how_to_select': str(Changeset.SELECT_CENTERS),
         'selected_centers_1': [str(self.center1.pk)],
         'target_center_1': str(self.center2.pk),
         'justification': 'Just because',
     }
     rsp = self.client.post(url, data=data, follow=True)
     self.assertRedirects(rsp, reverse('browse_changesets'))
Esempio n. 34
0
    def setUp(self):
        self.election = ElectionFactory()

        self.center = RegistrationCenterFactory(name=generate_arabic_place_name())
        self.office_id = self.center.office.id

        # Create a bunch of voters registered at each of these centers. The number of voters
        # matters somewhat.
        # station_distributor() will create a unisex station under certain conditions if
        # there are < N male or female voters, where N = UNISEX_TRIGGER (currently 25). The
        # names of the generated PDFs (which this code tests) have the gender embedded, so if I
        # change the # of voters and that causes a unisex station to be created, the filenames of
        # the generated PDFs will be different than these tests expect so the tests will fail.
        # I use a number of voters that guarantees I won't create a unisex station.
        n_voters = (settings.ROLLGEN_UNISEX_TRIGGER * 2) + 2

        self.voters = create_voters(n_voters, center=self.center)

        self.password = '******'
        self.user = UserFactory(password=self.password)

        # Each test gets a fresh work dir.
        self.output_path = tempfile.mkdtemp()
        self.input_arguments = INPUT_ARGUMENTS_TEMPLATE.copy()
        self.input_arguments['center_ids'] = [self.center.center_id]
Esempio n. 35
0
    def test_can_change_reg(self):
        # User can send multiple messages from the same phone number and change
        # their voting center.
        citizen = CitizenFactory()
        center1 = RegistrationCenterFactory()
        center2 = RegistrationCenterFactory()
        center3 = RegistrationCenterFactory()
        self.receive("%s %s" % (citizen.national_id, center1.center_id),
                     self.conn,
                     fields=self.fields)
        # Citizen should be registered
        reg = models.Registration.objects.get(citizen=citizen)
        self.assertEqual(center1, reg.registration_center)
        # Initial registration
        self.assertEqual(constants.RESPONSE_VALID_REGISTRATION,
                         self.get_last_response_code())

        # They change their mind and register for a different center
        self.receive("%s %s" % (citizen.national_id, center2.center_id),
                     self.conn,
                     fields=self.fields)
        # Citizen should be registered
        reg2 = models.Registration.objects.get(citizen=citizen)
        self.assertEqual(reg.pk, reg2.pk)
        # But at a new center
        self.assertEqual(center2, reg2.registration_center)
        self.assertEqual(constants.MESSAGE_1, self.get_last_response_code())
        # There's an archive
        archive = models.Registration.objects.archived().get(citizen=citizen)
        self.assertEqual(archive.archive_time, reg2.creation_date)
        # The archive has the previous data
        self.assertEqual(center1, archive.registration_center)

        # They change their mind and register for a different center
        self.receive("%s %s" % (citizen.national_id, center3.center_id),
                     self.conn,
                     fields=self.fields)
        # Citizen should be registered
        reg3 = models.Registration.objects.get(citizen=citizen)
        # But at a new center
        self.assertEqual(center3, reg3.registration_center)
        self.assertEqual(constants.MESSAGE_4, self.get_last_response_code())
        # most recent archive has the previous data
        archive = models.Registration.objects.archived().filter(citizen=citizen)\
            .order_by('-archive_time').first()
        self.assertEqual(center2, archive.registration_center)
Esempio n. 36
0
 def test_copied_by_multiple(self):
     """Exercise build_copy_info() for a center that has multiple copies"""
     original = RegistrationCenterFactory()
     copy_centers = RegistrationCenterFactory.create_batch(3, copy_of=original)
     copy_center_ids = sorted([center.center_id for center in copy_centers])
     copy_center_ids = (ARABIC_COMMA + ' ').join(map(str, copy_center_ids))
     expected = '{}: {}'.format(STRINGS['copied_by_plural'], copy_center_ids)
     self.assertEqual(build_copy_info(original), expected)
Esempio n. 37
0
    def test_all_related_by_copy(self):
        """exercise all_related_by_copy()"""
        original_center = RegistrationCenterFactory()
        # Create copies with center ids in unsorted order to verify all_related_by_copy() sorts
        # as promised.
        copies = []
        for center_id in (77777, 22222, 66666, 33333, 55555):
            copy_center = RegistrationCenterFactory(center_id=center_id, copy_of=original_center)
            copies.append(copy_center)

        copies.sort(key=lambda center: center.center_id)

        # test getting centers related to the original (parent) center
        actual_copies = original_center.all_related_by_copy()

        # original centers is always first in the returned list
        self.assertEqual(original_center, actual_copies[0])
        expected = copies
        actual = actual_copies[1:]
        self.assertEqual(expected, actual)

        # test getting centers related to one of the copies
        a_copy = copies[1]
        actual_copies = a_copy.all_related_by_copy()

        # original centers is always first in the returned list
        self.assertEqual(original_center, actual_copies[0])
        # expected remains the same as above
        actual = actual_copies[1:]
        self.assertEqual(expected, actual)

        # test that all_related_by_copy() doesn't return deleted centers
        a_copy = copies[1]
        a_copy.deleted = True
        a_copy.save()
        actual_copies = original_center.all_related_by_copy()
        expected = [copies[0]] + copies[2:]
        actual = actual_copies[1:]
        self.assertEqual(expected, actual)

        # test that all_related_by_copy() is the identity function for non-copy centers
        copyless_center = RegistrationCenterFactory()
        actual_copies = copyless_center.all_related_by_copy()
        self.assertEqual(copyless_center, actual_copies[0])
        self.assertEqual(len(actual_copies), 1)
Esempio n. 38
0
    def test_split_center_ok(self):
        """test that a split center can be created"""
        split_center_subcon, unused = \
            SubConstituency.objects.get_or_create(id=SPLIT_CENTER_SUBCONSTITUENCY_ID)

        center = RegistrationCenterFactory.build(center_type=RegistrationCenter.Types.SPLIT,
                                                 subconstituency=split_center_subcon)
        # This should not raise an error
        center.clean()
Esempio n. 39
0
    def test_copy_of_copy_fails(self):
        """test that a copy center can't be a copy of another copy center"""
        original_center = RegistrationCenterFactory()
        copy_center = RegistrationCenterFactory(copy_of=original_center)
        copy_copy_center = RegistrationCenterFactory.build(copy_of=copy_center)

        with self.assertRaises(ValidationError) as cm:
            copy_copy_center.clean()
        self.assertEqual(cm.exception.message, 'A copy centre cannot copy another copy centre.')
Esempio n. 40
0
    def test_copy_center_requires_copy_type(self):
        """test that a copy center must have the correct type"""
        original_center = RegistrationCenterFactory()
        copy_center = RegistrationCenterFactory.build(copy_of=original_center)
        copy_center.center_type = RegistrationCenter.Types.GENERAL

        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        self.assertEqual(cm.exception.message, 'Copy centre type must be "copy".')
Esempio n. 41
0
    def test_copy_center_requires_copy_info(self):
        """test that a center with copy type requires copy_of info"""
        copy_center = RegistrationCenterFactory.build(center_type=RegistrationCenter.Types.COPY)
        copy_center.copy_of = None

        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        self.assertEqual(cm.exception.message,
                         'Centre type "copy" requires copy centre information.')
Esempio n. 42
0
    def test_split_center_ok(self):
        """test that a split center can be created"""
        split_center_subcon, unused = \
            SubConstituency.objects.get_or_create(id=SPLIT_CENTER_SUBCONSTITUENCY_ID)

        center = RegistrationCenterFactory.build(
            center_type=RegistrationCenter.Types.SPLIT,
            subconstituency=split_center_subcon)
        # This should not raise an error
        center.clean()
Esempio n. 43
0
 def test_split_center_must_use_split_subcon(self):
     """test that a split center must be associated with the correct subcon"""
     some_random_subcon = SubConstituencyFactory()
     center = RegistrationCenterFactory.build(center_type=RegistrationCenter.Types.SPLIT,
                                              subconstituency=some_random_subcon)
     with self.assertRaises(ValidationError) as cm:
         center.clean()
     msg = "Split centers must be associated with subconstituency {}."
     msg = msg.format(SPLIT_CENTER_SUBCONSTITUENCY_ID)
     self.assertEqual(cm.exception.message, msg)
Esempio n. 44
0
 def test_view_view(self):
     self.center1 = RegistrationCenterFactory(name='Centero Uno')
     self.center2 = RegistrationCenterFactory(name='Centra Dua')
     changeset = ChangesetFactory(
         name='My Changeset',
         change=Changeset.CHANGE_CENTER,
         how_to_select=Changeset.SELECT_CENTERS,
         target_center=self.center2,
         justification='Just because',
     )
     changeset.selected_centers.add(self.center1)
     changeset.selected_centers.add(self.center2)
     url = reverse('read_changeset', kwargs={'pk': changeset.pk})
     rsp = self.client.get(url)
     self.assertEqual(OK, rsp.status_code)
     self.assertContains(rsp, self.center1.pk)
     self.assertContains(rsp, self.center2.pk)
     self.assertContains(rsp, 'Just because')
     self.assertContains(rsp, 'My Changeset')
Esempio n. 45
0
 def test_nonsplit_center_cannot_use_split_subcon(self):
     """test that a non-split center cannot be associated with the split-specific subcon"""
     split_center_subcon, unused = \
         SubConstituency.objects.get_or_create(id=SPLIT_CENTER_SUBCONSTITUENCY_ID)
     center = RegistrationCenterFactory.build(center_type=RegistrationCenter.Types.GENERAL,
                                              subconstituency=split_center_subcon)
     with self.assertRaises(ValidationError) as cm:
         center.clean()
     msg = "Only split centers may be associated with subconstituency {}."
     msg = msg.format(SPLIT_CENTER_SUBCONSTITUENCY_ID)
     self.assertEqual(cm.exception.message, msg)
Esempio n. 46
0
    def test_max_copies_per_center_limit(self):
        """test that register.models.N_MAX_COPY_CENTERS is respected"""
        original_center = RegistrationCenterFactory()
        create_batch(RegistrationCenterFactory, settings.N_MAX_COPY_CENTERS,
                     copy_of=original_center)

        copy_center = RegistrationCenterFactory.build(copy_of=original_center)
        with self.assertRaises(ValidationError) as cm:
            copy_center.clean()
        msg = 'Copy centre already has the maximum number of copies ({n_max}).'
        self.assertEqual(cm.exception.message, msg.format(n_max=settings.N_MAX_COPY_CENTERS))