示例#1
0
class UserActivationTest(TestCase):
    def setUp(self):
        self.user = EmailUserFactory(is_active=False)
        self.user.activation_key = self.user.create_activation_key()
        self.user.save()

    def test_basic_activation(self):
        activated_user = EmailUser.objects.activate_user(
            self.user.activation_key)
        self.assertEqual(self.user.pk, activated_user.pk)
        user = EmailUser.objects.get(pk=self.user.pk)
        self.assertTrue(user.is_active)
        self.assertEqual(user.activation_key, EmailUser.ACTIVATED)

    def test_already_activated(self):
        key = self.user.activation_key
        EmailUser.objects.activate_user(key)
        with self.assertRaises(ValidationError):
            EmailUser.objects.activate_user(key)

    def test_wrong_key(self):
        another_key = self.user.create_activation_key()

        with self.assertRaises(ValidationError):
            EmailUser.objects.activate_user(another_key)

    def test_bad_format(self):
        with self.assertRaises(ValidationError):
            EmailUser.objects.activate_user("not a sha1 string")

    def test_unique_emails(self):
        # Users' emails must be unique, case-insensitively
        user1 = EmailUserFactory()
        with self.assertRaises(ValidationError):
            EmailUserFactory(email=user1.email.upper())
示例#2
0
class ViewReportsButtonTest(ServiceInfoFrontendTestCase):
    def test_logout_and_login_as_staff(self):
        # Staff user sees the reports button even after logging out and in
        self.password = '******'
        self.user = EmailUserFactory(password=self.password)
        self.user.is_staff = True
        self.user.save()
        self.load_page_and_set_language()
        self.login()
        button = self.wait_for_element('view_reports_button')
        self.assertTrue(button.is_displayed())
        self.logout()
        # Give the page time to start reloading before looking for the button again
        time.sleep(1)
        self.login()
        # Give the page time to start reloading before looking for the button again
        time.sleep(1)
        button = self.wait_for_element('view_reports_button')
        self.assertTrue(button.is_displayed())
        # User can view reports page
        button.click()
        self.wait_for_element('report-table')

    def test_logout_and_login_as_non_staff(self):
        # Non-staff user sees the reports button, even after logging out
        # and in and changing language.  Even if superuser.
        self.password = '******'
        self.user = EmailUserFactory(password=self.password)
        self.user.is_superuser = True
        self.user.save()
        self.load_page_and_set_language()
        self.login()
        button = self.wait_for_element('view_reports_button',
                                       must_be_visible=False)
        self.assertTrue(button.is_displayed())

        # Log out and in again
        self.logout()
        # Give the page time to start reloading before looking for the menu again
        time.sleep(0.5)
        self.login()
        # Give the page time to start reloading before looking for the button again
        time.sleep(0.5)
        button = self.wait_for_element('view_reports_button',
                                       must_be_visible=False)
        self.assertTrue(button.is_displayed())

        # Set the language again
        form = self.wait_for_element('language-toggle')
        button = form.find_element_by_css_selector('[data-lang="%s"]' % 'en')
        button.click()
        # Give the page time to start reloading before looking for the button again
        time.sleep(0.5)
        button = self.wait_for_element('view_reports_button',
                                       must_be_visible=False)
        self.assertTrue(button.is_displayed())

        # User can view reports page
        button.click()
        self.wait_for_element('report-table')
class ViewReportsButtonTest(ServiceInfoFrontendTestCase):

    def test_logout_and_login_as_staff(self):
        # Staff user sees the reports button even after logging out and in
        self.password = '******'
        self.user = EmailUserFactory(password=self.password)
        self.user.is_staff = True
        self.user.save()
        self.load_page_and_set_language()
        self.login()
        button = self.wait_for_element('view_reports_button')
        self.assertTrue(button.is_displayed())
        self.logout()
        # Give the page time to start reloading before looking for the button again
        time.sleep(1)
        self.login()
        # Give the page time to start reloading before looking for the button again
        time.sleep(1)
        button = self.wait_for_element('view_reports_button')
        self.assertTrue(button.is_displayed())
        # User can view reports page
        button.click()
        self.wait_for_element('report-table')

    def test_logout_and_login_as_non_staff(self):
        # Non-staff user sees the reports button, even after logging out
        # and in and changing language.  Even if superuser.
        self.password = '******'
        self.user = EmailUserFactory(password=self.password)
        self.user.is_superuser = True
        self.user.save()
        self.load_page_and_set_language()
        self.login()
        button = self.wait_for_element('view_reports_button', must_be_visible=False)
        self.assertTrue(button.is_displayed())

        # Log out and in again
        self.logout()
        # Give the page time to start reloading before looking for the menu again
        time.sleep(0.5)
        self.login()
        # Give the page time to start reloading before looking for the button again
        time.sleep(0.5)
        button = self.wait_for_element('view_reports_button', must_be_visible=False)
        self.assertTrue(button.is_displayed())

        # Set the language again
        form = self.wait_for_element('language-toggle')
        button = form.find_element_by_css_selector('[data-lang="%s"]' % 'en')
        button.click()
        # Give the page time to start reloading before looking for the button again
        time.sleep(0.5)
        button = self.wait_for_element('view_reports_button', must_be_visible=False)
        self.assertTrue(button.is_displayed())

        # User can view reports page
        button.click()
        self.wait_for_element('report-table')
 def setUp(self):
     self.service = ServiceFactory(status=Service.STATUS_DRAFT,
                                   location="POINT (33.0000 35.0000)")
     self.password = '******'
     self.user = EmailUserFactory(is_staff=True, password=self.password)
     assert self.user.is_staff
     group = Group.objects.get(name='Staff')
     self.user.groups.add(group)
     assert self.user.has_perm('services.change_service')
     assert self.client.login(email=self.user.email, password=self.password)
示例#5
0
    def test_duplicate_registration(self):
        """Notify user of attempted duplicate registration."""

        user = EmailUserFactory(password='******')
        provider_type = ProviderTypeFactory()
        self.load_page_and_set_language()
        menu = self.wait_for_element('menu')
        registration = menu.find_elements_by_link_text('Provider Registration')[0]
        registration.click()
        form = self.wait_for_element('provider-form')
        self.assertHashLocation('/register')
        data = {
            'name': 'Joe Provider',
            'phone_number': '12-345678',
            'description': 'Test provider',
            'focal_point_name': 'John Doe',
            'focal_point_phone_number': '87-654321',
            'address': '1313 Mockingbird Lane, Beirut, Lebanon',
            'email': user.email,
            'password1': 'foobar',
            'password2': 'foobar',
            'number_of_monthly_beneficiaries': '37',
            'type': provider_type.name,
        }
        self.submit_form(form, data, button_class='form-btn-submit')
        error = self.wait_for_element('label[for="id_email"] .error', match=By.CSS_SELECTOR)
        self.assertIn('email already exists', error.text)
    def test_duplicating_services(self):
        # given
        user = EmailUserFactory(is_staff=True,
                                is_superuser=True,
                                is_active=True)
        token, created = Token.objects.get_or_create(user=user)

        romania = GeographicRegion.objects.get(slug='romania')
        self.assertIsNotNone(romania)
        ServiceFactory(region=romania, status='current')
        existing_service = Service.objects.all()
        self.assertEqual(len(existing_service), 1)

        # when
        duplicate_post = self.api_client.post(
            path='/v2/services/' + str(existing_service[0].id) +
            '/duplicate/?new_name=Test123',
            HTTP_SERVICEINFOAUTHORIZATION="Token %s" % token.key,
            format='json')
        self.assertEqual(duplicate_post.status_code, 201)

        # then
        duplicated_service = Service.objects.filter(name_en='Test123')
        self.assertEqual(Service.objects.all().count(), 2)
        self.assertEqual(len(duplicated_service), 1)
        self.assertNotEqual(existing_service[0].slug,
                            duplicated_service[0].slug)
    def test_ordering(self):
        # given
        user = EmailUserFactory(is_staff=True, is_superuser=True, is_active=True)
        token, created = Token.objects.get_or_create(user=user)
        service_type = ServiceType.objects.first()

        types_ordering = self.api_client.get('/v2/servicetypes/')
        self.assertEqual(types_ordering.status_code, 200)
        types_ordering = json.loads(types_ordering.content.decode('utf-8'))

        service_type = self.api_client.get('/v2/servicetypes/' + str(service_type.id) + '/')
        self.assertEqual(service_type.status_code, 200)
        service_type = json.loads(service_type.content.decode('utf-8'))

        # when
        types_ordering = sorted(types_ordering, key=lambda k: k['name'])
        service_type['comments_en'] = 'test'
        service_type['types_ordering'] = types_ordering
        type_post = self.api_client.put(
            path='/v2/servicetypes/' + str(service_type['id']) + '/',
            data=service_type,
            HTTP_SERVICEINFOAUTHORIZATION="Token %s" % token.key,
            format='json')
        self.assertEqual(type_post.status_code, 200)

        # then
        types = ServiceType.objects.all().order_by('number')
        self.assertEqual(types_ordering[0]['name'], types[0].name)
示例#8
0
class UserActivationTest(TestCase):
    def setUp(self):
        self.user = EmailUserFactory(is_active=False)
        self.user.activation_key = self.user.create_activation_key()
        self.user.save()

    def test_basic_activation(self):
        activated_user = EmailUser.objects.activate_user(self.user.activation_key)
        self.assertEqual(self.user.pk, activated_user.pk)
        user = EmailUser.objects.get(pk=self.user.pk)
        self.assertTrue(user.is_active)
        self.assertEqual(user.activation_key, EmailUser.ACTIVATED)

    def test_already_activated(self):
        key = self.user.activation_key
        EmailUser.objects.activate_user(key)
        with self.assertRaises(ValidationError):
            EmailUser.objects.activate_user(key)

    def test_wrong_key(self):
        another_key = self.user.create_activation_key()

        with self.assertRaises(ValidationError):
            EmailUser.objects.activate_user(another_key)

    def test_bad_format(self):
        with self.assertRaises(ValidationError):
            EmailUser.objects.activate_user("not a sha1 string")

    def test_send_email_to_user(self):
        # send_email_to_user() submits mail to Django and translates its content
        # We'll include a string in the template that we know Django has translated:
        english_text = "Are you sure?"
        french_text = "Êtes-vous sûr\xa0?"
        arabic_text = "هل أنت متأكد؟"

        our_template = Template('{% load i18n %}{% trans "' + english_text + '" %}')

        for lang, expected_text in [('', english_text), ('fr', french_text), ('ar', arabic_text),
                                    ('en', english_text)]:
            self.user.language = lang
            self.user.save()
            with patch('django.template.loader.get_template') as mock_get_template:
                mock_get_template.return_value = our_template
                self.user.send_email_to_user({}, '', '', '')

            # Test that one message has been sent.
            self.assertEqual(len(mail.outbox), 1)
            self.assertIn(expected_text, mail.outbox[0].body)
            # Empty the test outbox
            mail.outbox = []

    def test_unique_emails(self):
        # Users' emails must be unique, case-insensitively
        user1 = EmailUserFactory()
        with self.assertRaises(ValidationError):
            EmailUserFactory(email=user1.email.upper())
示例#9
0
    def test_confirm_registration(self):
        """New user activating their registration."""

        EmailUserFactory(
            password='******', is_active=False, activation_key='1234567890')
        self.load_page_and_set_language()
        self.browser.get(self.express_url + '#/register/verify/1234567890')
        self.wait_for_landing_page(timeout=2 * DEFAULT_TIMEOUT)
示例#10
0
 def setUp(self):
     self.user = EmailUserFactory(is_superuser=True)
     # Use the existing sites; their use of hard-coded pks breaks the ability to
     # add arbitrary additional sites for this test.
     self.orig_site_domain = 'serviceinfo.rescue.org'
     self.new_site_domain = 'serviceinfo-staging.rescue.org'
     self.orig_site = Site.objects.get(domain=self.orig_site_domain)
     self.new_site = Site.objects.get(domain=self.new_site_domain)
     utils.create_essential_pages(self.user, self.orig_site)
示例#11
0
 def setUp(self):
     self.service = ServiceFactory(status=Service.STATUS_DRAFT,
                                   location="POINT (33.0000 35.0000)")
     self.password = '******'
     self.user = EmailUserFactory(is_staff=True, password=self.password)
     assert self.user.is_staff
     group = Group.objects.get(name='Staff')
     self.user.groups.add(group)
     assert self.user.has_perm('services.change_service')
     assert self.client.login(email=self.user.email, password=self.password)
示例#12
0
    def test_user_exists(self):
        email = "*****@*****.**"
        EmailUserFactory(email=email)

        form = EmailUserCreationForm({
            'email': email,
            'password1': 'password',
            'password2': 'password'
        })
        self.assertFalse(form.is_valid())
        self.assertIn('email', form.errors)
示例#13
0
 def test_logout_and_login_as_staff(self):
     # Staff user sees the reports button even after logging out and in
     self.password = '******'
     self.user = EmailUserFactory(password=self.password)
     self.user.is_staff = True
     self.user.save()
     self.load_page_and_set_language()
     self.login()
     button = self.wait_for_element('view_reports_button')
     self.assertTrue(button.is_displayed())
     self.logout()
     # Give the page time to start reloading before looking for the button again
     time.sleep(1)
     self.login()
     # Give the page time to start reloading before looking for the button again
     time.sleep(1)
     button = self.wait_for_element('view_reports_button')
     self.assertTrue(button.is_displayed())
     # User can view reports page
     button.click()
     self.wait_for_element('report-table')
    def test_staff_see_all_current_data(self):
        user = EmailUserFactory(is_staff=True)
        provider = ProviderFactory()
        ProviderFactory()
        ServiceFactory(provider=provider, status=Service.STATUS_CURRENT)
        ServiceFactory(provider=provider, status=Service.STATUS_CURRENT)
        ServiceFactory(status=Service.STATUS_CURRENT)
        ServiceFactory(provider=provider, status=Service.STATUS_DRAFT)
        book = get_export_workbook_for_user(user)
        xlrd_book = save_and_read_book(book)

        # First sheet - providers
        sheet = xlrd_book.get_sheet(0)
        self.assertEqual(3, sheet.nrows - 1)

        # Second sheet - services
        sheet = xlrd_book.get_sheet(1)
        self.assertEqual(3, sheet.nrows - 1)
示例#15
0
 def test_staff_add_providers(self):
     # Remember, only one provider per user
     self.user.is_staff = True
     self.user.save()
     type1 = ProviderTypeFactory()
     provider1 = ProviderFactory.build(type=type1,
                                       user=self.user)  # Doesn't save
     user2 = EmailUserFactory()
     type2 = ProviderTypeFactory()
     provider2 = ProviderFactory.build(type=type2,
                                       user=user2)  # Doesn't save
     book = get_export_workbook([provider1, provider2])
     rsp = self.import_book(book)
     self.assertEqual(OK, rsp.status_code, msg=rsp.content.decode('utf-8'))
     self.assertTrue(
         Provider.objects.filter(name_en=provider1.name_en).exists())
     self.assertTrue(
         Provider.objects.filter(name_en=provider2.name_en).exists())
 def test_logout_and_login_as_staff(self):
     # Staff user sees the reports button even after logging out and in
     self.password = '******'
     self.user = EmailUserFactory(password=self.password)
     self.user.is_staff = True
     self.user.save()
     self.load_page_and_set_language()
     self.login()
     button = self.wait_for_element('view_reports_button')
     self.assertTrue(button.is_displayed())
     self.logout()
     # Give the page time to start reloading before looking for the button again
     time.sleep(1)
     self.login()
     # Give the page time to start reloading before looking for the button again
     time.sleep(1)
     button = self.wait_for_element('view_reports_button')
     self.assertTrue(button.is_displayed())
     # User can view reports page
     button.click()
     self.wait_for_element('report-table')
示例#17
0
 def setUp(self):
     self.test_service = ServiceFactory(location='POINT(5 23)')
     self.jira_record = self.test_service.jira_records.get(
         update_type=JiraUpdateRecord.NEW_SERVICE)
     self.staff_user = EmailUserFactory(is_staff=True)
    def test_random_data(self):
        provider = ProviderFactory()
        service1 = ServiceFactory(provider=provider, status=Service.STATUS_CURRENT)
        service2 = ServiceFactory(provider=provider, status=Service.STATUS_CURRENT)
        ServiceFactory(provider=provider, status=Service.STATUS_CURRENT)
        # Some additional services that should not show up
        ServiceFactory(status=Service.STATUS_CURRENT)  # not one of the providers we want
        ServiceFactory(provider=provider, status=Service.STATUS_DRAFT)  # Draft mode
        SelectionCriterionFactory(service=service1)
        SelectionCriterionFactory(service=service2)
        SelectionCriterionFactory()  # unwanted service

        # Querysets of just the objects we expect to be exported
        providers = Provider.objects.order_by('id')
        services = Service.objects.filter(status=Service.STATUS_CURRENT,
                                          provider__in=providers).order_by('id')
        criteria = SelectionCriterion.objects.filter(service__status=Service.STATUS_CURRENT,
                                                     service__provider__in=providers).order_by('id')

        xlwt_book = get_export_workbook(providers)
        book = save_and_read_book(xlwt_book)

        # First sheet - providers
        sheet = book.get_sheet(0)
        self.assertEqual(providers.count(), sheet.nrows - 1)
        self.assertEqual(PROVIDER_HEADINGS, sheet.row_values(0))
        for i, rownum in enumerate(range(1, sheet.nrows)):
            values = sheet.row_values(rownum)
            provider = providers[i]
            data = dict(zip(PROVIDER_HEADINGS, values))
            self.assertEqual(provider.id, data['id'])
            self.assertEqual(provider.name_ar, data['name_ar'])

        # Second sheet = services
        sheet = book.get_sheet(1)
        self.assertEqual(services.count(), sheet.nrows - 1)
        self.assertEqual(SERVICE_HEADINGS, sheet.row_values(0))
        for i, rownum in enumerate(range(1, sheet.nrows)):
            values = sheet.row_values(rownum)
            service = services[i]
            data = dict(zip(SERVICE_HEADINGS, values))
            self.assertEqual(service.id, data['id'])
            self.assertEqual(service.name_ar, data['name_ar'])
            provider = Provider.objects.get(id=data['provider__id'])
            self.assertEqual(provider, service.provider)

        # Third sheet - selection criteria
        sheet = book.get_sheet(2)
        self.assertEqual(SELECTION_CRITERIA_HEADINGS, sheet.row_values(0))
        self.assertEqual(criteria.count(), sheet.nrows - 1)
        for i, rownum in enumerate(range(1, sheet.nrows)):
            values = sheet.row_values(rownum)
            criterion = criteria[i]
            data = dict(zip(SELECTION_CRITERIA_HEADINGS, values))
            self.assertEqual(criterion.id, data['id'])
            self.assertEqual(criterion.text_ar, data['text_ar'])
            service = Service.objects.get(id=data['service__id'])
            self.assertEqual(service, criterion.service)

        # The exported workbook should also be valid for import by
        # a staff user
        user = EmailUserFactory(is_staff=True)
        validate_and_import_data(user, get_book_bits(xlwt_book))
示例#19
0
 def test_related_name(self):
     # Just make sure we can get to the provider using user.provider
     user = EmailUserFactory()
     provider = ProviderFactory(user=user, )
     self.assertEqual(user.provider, provider)
示例#20
0
 def setUp(self):
     self.user = EmailUserFactory(is_active=False)
     self.user.activation_key = self.user.create_activation_key()
     self.user.save()
示例#21
0
 def setUp(self):
     self.user = EmailUserFactory()
     self.provider = ProviderFactory(user=self.user)
     self.service = ServiceFactory(provider=self.provider)
示例#22
0
 def test_unique_emails(self):
     # Users' emails must be unique, case-insensitively
     user1 = EmailUserFactory()
     with self.assertRaises(ValidationError):
         EmailUserFactory(email=user1.email.upper())
示例#23
0
class ServiceAdminTest(TestCase):
    def setUp(self):
        self.service = ServiceFactory(status=Service.STATUS_DRAFT,
                                      location="POINT (33.0000 35.0000)")
        self.password = '******'
        self.user = EmailUserFactory(is_staff=True, password=self.password)
        assert self.user.is_staff
        group = Group.objects.get(name='Staff')
        self.user.groups.add(group)
        assert self.user.has_perm('services.change_service')
        assert self.client.login(email=self.user.email, password=self.password)

    def test_permissions(self):
        # Must have Staff group to access services in the admin
        self.user.groups.remove(Group.objects.get(name='Staff'))
        rsp = self.client.get(reverse('admin:services_service_change', args=[self.service.pk]))
        self.assertEqual(403, rsp.status_code)
        rsp = self.save_service_in_form()
        self.assertEqual(403, rsp.status_code)

    def save_service_in_form(self, **kwargs):
        """
        Simulate loading the service in a change form in the admin, updating
        some data from **kwargs, and submitting.
        Returns the response returned by the post.
        """
        data = model_to_dict(self.service)
        data['location'] = str(data['location'])
        # inline data
        data["selection_criteria-TOTAL_FORMS"] = 0
        data["selection_criteria-INITIAL_FORMS"] = 0
        data["selection_criteria-MIN_NUM_FORMS"] = 0
        data["selection_criteria-MAX_NUM_FORMS"] = 0
        # Drop any None values
        data = {k: v for k, v in data.items() if v is not None}
        # Update with caller data
        data.update(**kwargs)
        rsp = self.client.post(reverse('admin:services_service_change', args=[self.service.pk]),
                               data=data)
        return rsp

    def test_edit_service(self):
        # Make a change to the data
        rsp = self.save_service_in_form(name_en="New service name")
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual("New service name", service.name_en)

    def test_approve_button(self):
        rsp = self.save_service_in_form(name_en="New service name",
                                        _approve=True,  # the button we "clicked"
                                        )
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual("New service name", service.name_en)
        self.assertEqual(Service.STATUS_CURRENT, service.status)

    def test_approve_button_with_bad_data(self):
        rsp = self.save_service_in_form(name_en="New service name",
                                        location="not a valid location",
                                        _approve=True,  # the button we "clicked"
                                        )
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        self.assertIn('<ul class="errorlist"><li>Invalid geometry value.</li></ul>',
                      rsp.context['errors'])
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_DRAFT, service.status)

    def test_approve_button_with_missing_data(self):
        rsp = self.save_service_in_form(name_en="New service name",
                                        location='',
                                        _approve=True,  # the button we "clicked"
                                        )
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        self.assertIn('<ul class="errorlist"><li>No geometry value provided.</li></ul>',
                      rsp.context['errors'])
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_DRAFT, service.status)

    def test_reject_button(self):
        rsp = self.save_service_in_form(name_en="New service name",
                                        _reject=True,  # the button we "clicked"
                                        )
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual("New service name", service.name_en)
        self.assertEqual(Service.STATUS_REJECTED, service.status)

    def test_actions_appear(self):
        rsp = self.client.get(reverse('admin:services_service_changelist'))
        self.assertContains(rsp, "Approve new or changed service")
        self.assertContains(rsp, "Reject new or changed service")

    def test_buttons_appear(self):
        rsp = self.client.get(reverse('admin:services_service_change', args=[self.service.pk]))
        self.assertContains(rsp, "Save and approve")
        self.assertContains(rsp, "Save and reject")

    def test_approve_action(self):
        self.service.validate_for_approval()
        data = {
            'index': '0',  # "Go" button
            'action': 'approve',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'), data)
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        new_url = rsp['Location']
        rsp = self.client.get(new_url)
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_CURRENT, service.status)

    def test_reject_action(self):
        data = {
            'index': '0',  # "Go" button
            'action': 'reject',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'), data)
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        new_url = rsp['Location']
        rsp = self.client.get(new_url)
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_REJECTED, service.status)

    def test_approve_action_wrong_status(self):
        self.service.status = Service.STATUS_CURRENT
        self.service.save()
        data = {
            'index': '0',  # "Go" button
            'action': 'approve',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'), data, follow=True)
        self.assertEqual(200, rsp.status_code)
        self.assertIn('Only services in draft status may be approved',
                      [str(msg) for msg in rsp.context['messages']])

    def test_reject_action_wrong_status(self):
        self.service.status = Service.STATUS_CURRENT
        self.service.save()
        data = {
            'index': '0',  # "Go" button
            'action': 'reject',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'), data, follow=True)
        self.assertEqual(200, rsp.status_code)
        self.assertIn('Only services in draft status may be rejected',
                      [str(msg) for msg in rsp.context['messages']])

    def test_show_image_in_changelist(self):
        rsp = self.client.get(reverse('admin:services_service_changelist'))
        image_tag = '<img src="%s">' % self.service.get_thumbnail_url()
        self.assertContains(rsp, image_tag, html=True)

    def test_show_no_image_if_not_set(self):
        self.service.image = ''
        self.service.save()
        rsp = self.client.get(reverse('admin:services_service_changelist'))
        self.assertContains(rsp, 'no image')
示例#24
0
 def setUp(self):
     self.user = EmailUserFactory(is_superuser=True)
     create_essential_pages(self.user)
     self.page = Page.objects.latest('id')
     self.pr = PageRating.objects.create(page_obj=self.page)
     self.pr.save()
示例#25
0
 def test_login(self):
     """Login an existing user."""
     self.password = '******'
     self.user = EmailUserFactory(password=self.password)
     self.load_page_and_set_language()
     self.login()
示例#26
0
 def setUp(self):
     self.user = EmailUserFactory()
示例#27
0
class ServiceAdminTest(TestCase):
    def setUp(self):
        self.service = ServiceFactory(status=Service.STATUS_DRAFT,
                                      location="POINT (33.0000 35.0000)")
        self.password = '******'
        self.user = EmailUserFactory(is_staff=True, password=self.password)
        assert self.user.is_staff
        group = Group.objects.get(name='Staff')
        self.user.groups.add(group)
        assert self.user.has_perm('services.change_service')
        assert self.client.login(email=self.user.email, password=self.password)

    def test_permissions(self):
        # Must have Staff group to access services in the admin
        self.user.groups.remove(Group.objects.get(name='Staff'))
        rsp = self.client.get(
            reverse('admin:services_service_change', args=[self.service.pk]))
        self.assertEqual(403, rsp.status_code)
        rsp = self.save_service_in_form()
        self.assertEqual(403, rsp.status_code)

    def save_service_in_form(self, **kwargs):
        """
        Simulate loading the service in a change form in the admin, updating
        some data from **kwargs, and submitting.
        Returns the response returned by the post.
        """
        data = model_to_dict(self.service)
        data['location'] = str(data['location'])
        # inline data
        data["selection_criteria-TOTAL_FORMS"] = 0
        data["selection_criteria-INITIAL_FORMS"] = 0
        data["selection_criteria-MIN_NUM_FORMS"] = 0
        data["selection_criteria-MAX_NUM_FORMS"] = 0
        # Drop any None values
        data = {k: v for k, v in data.items() if v is not None}
        # Update with caller data
        data.update(**kwargs)
        rsp = self.client.post(reverse('admin:services_service_change',
                                       args=[self.service.pk]),
                               data=data)
        return rsp

    def test_edit_service(self):
        # Make a change to the data
        rsp = self.save_service_in_form(name_en="New service name")
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual("New service name", service.name_en)

    def test_approve_button(self):
        rsp = self.save_service_in_form(
            name_en="New service name",
            _approve=True,  # the button we "clicked"
        )
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual("New service name", service.name_en)
        self.assertEqual(Service.STATUS_CURRENT, service.status)

    def test_approve_button_with_bad_data(self):
        rsp = self.save_service_in_form(
            name_en="New service name",
            location="not a valid location",
            _approve=True,  # the button we "clicked"
        )
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        self.assertIn(
            '<ul class="errorlist"><li>Invalid geometry value.</li></ul>',
            rsp.context['errors'])
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_DRAFT, service.status)

    def test_approve_button_with_missing_data(self):
        rsp = self.save_service_in_form(
            name_en="New service name",
            location='',
            _approve=True,  # the button we "clicked"
        )
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        self.assertIn(
            '<ul class="errorlist"><li>No geometry value provided.</li></ul>',
            rsp.context['errors'])
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_DRAFT, service.status)

    def test_reject_button(self):
        rsp = self.save_service_in_form(
            name_en="New service name",
            _reject=True,  # the button we "clicked"
        )
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual("New service name", service.name_en)
        self.assertEqual(Service.STATUS_REJECTED, service.status)

    def test_actions_appear(self):
        rsp = self.client.get(reverse('admin:services_service_changelist'))
        self.assertContains(rsp, "Approve new or changed service")
        self.assertContains(rsp, "Reject new or changed service")

    def test_buttons_appear(self):
        rsp = self.client.get(
            reverse('admin:services_service_change', args=[self.service.pk]))
        self.assertContains(rsp, "Save and approve")
        self.assertContains(rsp, "Save and reject")

    def test_approve_action(self):
        self.service.validate_for_approval()
        data = {
            'index': '0',  # "Go" button
            'action': 'approve',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'),
                               data)
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        new_url = rsp['Location']
        rsp = self.client.get(new_url)
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_CURRENT, service.status)

    def test_reject_action(self):
        data = {
            'index': '0',  # "Go" button
            'action': 'reject',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'),
                               data)
        self.assertEqual(302, rsp.status_code, msg=rsp.content.decode('utf-8'))
        new_url = rsp['Location']
        rsp = self.client.get(new_url)
        self.assertEqual(200, rsp.status_code, msg=rsp.content.decode('utf-8'))
        service = Service.objects.get(pk=self.service.pk)
        self.assertEqual(Service.STATUS_REJECTED, service.status)

    def test_approve_action_wrong_status(self):
        self.service.status = Service.STATUS_CURRENT
        self.service.save()
        data = {
            'index': '0',  # "Go" button
            'action': 'approve',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'),
                               data,
                               follow=True)
        self.assertEqual(200, rsp.status_code)
        self.assertIn('Only services in draft status may be approved',
                      [str(msg) for msg in rsp.context['messages']])

    def test_reject_action_wrong_status(self):
        self.service.status = Service.STATUS_CURRENT
        self.service.save()
        data = {
            'index': '0',  # "Go" button
            'action': 'reject',  # selected action
            '_selected_action': [
                str(self.service.pk),  # selected checkbox
            ]
        }
        rsp = self.client.post(reverse('admin:services_service_changelist'),
                               data,
                               follow=True)
        self.assertEqual(200, rsp.status_code)
        self.assertIn('Only services in draft status may be rejected',
                      [str(msg) for msg in rsp.context['messages']])
示例#28
0
 def setUp(self):
     self.user = EmailUserFactory(is_active=False)
     self.user.activation_key = self.user.create_activation_key()
     self.user.save()