def test_unarchive_permission_denied(self):
        """
        Test the unarchive view when the user does not have sufficient permissions
        to unarchive a company.
        """
        company = ArchivedCompanyFactory()
        unarchive_route_name = admin_urlname(Company._meta,
                                             'unarchive-company')
        unarchive_query_args = {
            'company': company.pk,
        }
        unarchive_url = reverse_with_query_string(
            unarchive_route_name,
            unarchive_query_args,
        )
        user = create_test_user(
            permission_codenames=(CompanyPermission.view_company, ),
            is_staff=True,
            password=self.PASSWORD,
        )
        client = self.create_client(user=user)

        response = client.get(unarchive_url)
        assert response.status_code == status.HTTP_403_FORBIDDEN
        company.refresh_from_db()
        assert company.archived is True
    def test_valid_input_redirects_to_confirmation(self):
        """
        Test that valid POST input responds with a redirect to the confirmation
        page.
        """
        company_link_route_name = admin_urlname(Company._meta, 'dnb-link-select-ids')
        company_link_url = reverse(company_link_route_name)

        data = {
            'company': CompanyFactory().id,
            'duns_number': '123456789',
        }
        response = self.client.post(company_link_url, data=data)

        company_link_confirmation_route_name = admin_urlname(
            Company._meta,
            'dnb-link-review-changes',
        )
        company_link_confirmation_url = reverse_with_query_string(
            company_link_confirmation_route_name,
            data,
        )

        assert response.status_code == status.HTTP_302_FOUND
        assert response['location'] == company_link_confirmation_url
    def test_error_if_invalid_company_selected(self, company_2, expected_error):
        """Test that an error is displayed if the an invalid company is selected."""
        company = CompanyFactory()

        select_other_route_name = admin_urlname(Company._meta, 'merge-select-other-company')
        select_other_query_args = {
            'company_1': company.pk,
        }
        select_other_url = reverse_with_query_string(
            select_other_route_name,
            select_other_query_args,
        )

        value = str(company.pk) if company_2 is self.SAME_COMPANY else company_2

        response = self.client.post(
            select_other_url,
            data={
                'company_2': value,
            },
        )

        assert response.status_code == status.HTTP_200_OK

        form = response.context['form']

        assert 'company_2' in form.errors
        assert form.errors['company_2'] == [expected_error]
示例#4
0
def _make_confirm_merge_url(source_company, target_company):
    confirm_merge_route_name = admin_urlname(Company._meta, 'merge-confirm')
    confirm_merge_query_args = {
        'source_company': str(source_company.pk),
        'target_company': str(target_company.pk),
    }
    return reverse_with_query_string(confirm_merge_route_name, confirm_merge_query_args)
    def test_unarchive_view(
        self,
        company_callable,
        expected_status_code,
        expected_archived_value,
    ):
        """
        Test the unarchive view when called on companies in different states.
        """
        company = company_callable()
        unarchive_route_name = admin_urlname(Company._meta,
                                             'unarchive-company')
        unarchive_query_args = {
            'company': company.pk,
        }
        unarchive_url = reverse_with_query_string(
            unarchive_route_name,
            unarchive_query_args,
        )

        response = self.client.get(unarchive_url)

        assert response.status_code == expected_status_code
        company.refresh_from_db()
        assert company.archived is expected_archived_value
        if expected_archived_value is False:
            assert not company.archived_on
            assert not company.archived_by
            assert not company.archived_reason
示例#6
0
def select_primary_company(model_admin, request):
    """
    View for selecting the company to retain.

    This is the view where the user selects which company should remain as the
    active record and which one should be archived.

    Note that the IDs of the two companies to select from are passed in via the
    query string.

    SelectPrimaryCompanyForm is used to validate the POST body on submission of the form.
    """
    if not model_admin.has_change_permission(request):
        raise PermissionDenied

    company_1 = model_admin.get_object(request, request.GET.get('company_1'))
    company_2 = model_admin.get_object(request, request.GET.get('company_2'))

    if not (company_1 and company_2):
        raise SuspiciousOperation()

    is_post = request.method == 'POST'
    data = request.POST if is_post else None
    form = SelectPrimaryCompanyForm(company_1, company_2, data=data)

    if is_post and form.is_valid():
        confirm_route_name = admin_urlname(
            model_admin.model._meta,
            'merge-confirm',
        )
        confirm_query_args = {
            'source_company': form.cleaned_data['source_company'].pk,
            'target_company': form.cleaned_data['target_company'].pk,
        }
        confirm_url = reverse_with_query_string(confirm_route_name,
                                                confirm_query_args)
        return HttpResponseRedirect(confirm_url)

    template_name = 'admin/company/company/merge/step_2_primary_selection.html'
    title = gettext_lazy('Select which company should be retained')

    context = {
        **model_admin.admin_site.each_context(request),
        'option_1':
        _build_option_context(company_2, company_1),
        'option_2':
        _build_option_context(company_1, company_2),
        'form':
        form,
        'media':
        model_admin.media,
        'opts':
        model_admin.model._meta,
        'title':
        title,
    }
    return TemplateResponse(request, template_name, context)
示例#7
0
def _get_review_changes_url(company, duns_number):
    review_changes_route_name = admin_urlname(Company._meta,
                                              'dnb-link-review-changes')
    data = {
        'company': company.id,
        'duns_number': duns_number,
    }
    return reverse_with_query_string(
        review_changes_route_name,
        data,
    )
示例#8
0
    def test_proceeds_if_company_chosen(self, selected_company):
        """Test that if a valid selection is made, the user is redirected to the change list."""
        company_1 = CompanyFactory()
        company_2 = CompanyFactory()

        select_primary_route_name = admin_urlname(
            Company._meta, 'merge-select-primary-company')
        select_primary_query_args = {
            'company_1': str(company_1.pk),
            'company_2': str(company_2.pk),
        }
        select_primary_url = reverse_with_query_string(
            select_primary_route_name,
            select_primary_query_args,
        )

        response = self.client.post(
            select_primary_url,
            follow=True,
            data={
                'selected_company': selected_company,
            },
        )

        assert response.status_code == status.HTTP_200_OK
        assert len(response.redirect_chain) == 1

        confirm_merge_route_name = admin_urlname(Company._meta,
                                                 'merge-confirm')
        confirm_merge_query_args = {
            'source_company':
            (company_1 if selected_company != '1' else company_2).pk,
            'target_company':
            (company_1 if selected_company == '1' else company_2).pk,
        }
        confirm_merge_url = reverse_with_query_string(
            confirm_merge_route_name,
            confirm_merge_query_args,
        )

        assert response.redirect_chain[0][0] == confirm_merge_url
示例#9
0
    def test_proceeds_if_valid_company_provided(self):
        """Test the view redirects if a valid company is provided."""
        main_company = CompanyFactory()
        other_company = CompanyFactory()

        select_other_route_name = admin_urlname(Company._meta,
                                                'merge-select-other-company')
        select_other_query_args = {
            'company_1': main_company.pk,
        }
        select_other_url = reverse_with_query_string(
            select_other_route_name,
            select_other_query_args,
        )

        response = self.client.post(
            select_other_url,
            follow=True,
            data={
                'company_2': str(other_company.pk),
            },
        )

        assert response.status_code == status.HTTP_200_OK
        assert len(response.redirect_chain) == 1

        select_primary_route_name = admin_urlname(
            Company._meta, 'merge-select-primary-company')
        select_primary_query_args = {
            'company_1': main_company.pk,
            'company_2': other_company.pk,
        }
        select_primary_url = reverse_with_query_string(
            select_primary_route_name,
            select_primary_query_args,
        )

        assert response.redirect_chain[0][0] == select_primary_url
示例#10
0
def merge_select_other_company(model_admin, request):
    """
    First view as part of the merge duplicate companies process.

    Used to select the second company of the two to merge.

    Note that the ID of the first company is passed in via the query string.

    SelectOtherCompanyForm the form used to validate the POST body.
    """
    if not model_admin.has_change_permission(request):
        raise PermissionDenied

    company_1 = model_admin.get_object(request, request.GET.get('company_1'))

    if not company_1:
        raise SuspiciousOperation()

    is_post = request.method == 'POST'
    data = request.POST if is_post else None
    form = SelectOtherCompanyForm(company_1, data=data)

    if is_post and form.is_valid():
        select_primary_route_name = admin_urlname(
            model_admin.model._meta,
            'merge-select-primary-company',
        )
        select_primary_query_args = {
            'company_1': company_1.pk,
            'company_2': form.cleaned_data['company_2'].pk,
        }
        select_primary_url = reverse_with_query_string(
            select_primary_route_name,
            select_primary_query_args,
        )
        return HttpResponseRedirect(select_primary_url)

    template_name = 'admin/company/company/merge/step_1_select_other_company.html'
    title = gettext_lazy('Merge with another company')

    context = {
        **model_admin.admin_site.each_context(request),
        'opts': model_admin.model._meta,
        'title': title,
        'form': form,
        'media': model_admin.media,
        'object': company_1,
    }
    return TemplateResponse(request, template_name, context)
示例#11
0
    def __call__(self, request):
        """
        Check if OAuth2 expiration time is present in the session.

        If OAuth2 expires on has passed it means we have to logout the user.
        """
        if request.user.is_authenticated:
            oauth_expires_on = request.session.get('oauth.expires_on')
            if oauth_expires_on is not None and oauth_expires_on < time():
                django_logout(request)

                return redirect(
                    reverse_with_query_string('admin:login',
                                              {'next': request.path}))

        return self.get_response(request)
示例#12
0
def test_user_is_logged_out_from_admin_when_oauth2_session_has_expired():
    """Tests that user is logged out if OAuth2 session is expired."""
    adviser = AdviserFactory()

    admin_url = reverse('admin:index')
    request = get_request_with_session(admin_url)
    request.session['oauth.expires_on'] = int(FROZEN_TIME.timestamp()) - 1
    django_login(request, adviser)

    assert request.user.is_authenticated

    oauth_session_middleware = OAuthSessionMiddleware(_get_response)
    response = oauth_session_middleware(request)

    assert not request.user.is_authenticated

    assert response.status_code == status.HTTP_302_FOUND
    assert response.url == reverse_with_query_string('admin:login', {'next': request.path})
    assert 'oauth.state' not in request.session
    def test_unarchive_company_does_not_exist(self):
        """
        Test that a 400 is returned when an invalid value is passed in the query string.

        This could only happen if the query string was manipulated, or the referenced company
        was deleted.
        """
        unarchive_route_name = admin_urlname(Company._meta,
                                             'unarchive-company')
        unarchive_query_args = {
            'company': 'abc123',
        }
        unarchive_url = reverse_with_query_string(
            unarchive_route_name,
            unarchive_query_args,
        )

        response = self.client.get(unarchive_url)
        assert response.status_code == status.HTTP_400_BAD_REQUEST
    def test_link_exists(self):
        """Test that the link exists for a user with the change company permission."""
        company = CompanyFactory()

        change_route_name = admin_urlname(Company._meta, 'change')
        change_url = reverse(change_route_name, args=(company.pk,))

        response = self.client.get(change_url)
        assert response.status_code == status.HTTP_200_OK

        select_other_route_name = admin_urlname(Company._meta, 'merge-select-other-company')
        select_other_query_args = {
            'company_1': company.pk,
        }
        select_other_url = reverse_with_query_string(
            select_other_route_name,
            select_other_query_args,
        )

        assert select_other_url in response.rendered_content
示例#15
0
    def test_validation_errors_rendered(self, data_overrides, expected_errors):
        """
        Test that validation errors are rendered as expected.
        """
        review_changes_route_name = admin_urlname(Company._meta,
                                                  'dnb-link-review-changes')
        data = {
            'company': CompanyFactory().id,
            'duns_number': '123456789',
            **data_overrides,
        }
        review_changes_url = reverse_with_query_string(
            review_changes_route_name,
            {key: value
             for key, value in data.items() if value is not None},
        )

        response = self.client.get(review_changes_url, follow=True)

        assert response.status_code == status.HTTP_200_OK
        for expected_error in expected_errors:
            assert expected_error in response.rendered_content
def dnb_link_select_ids(model_admin, request):
    """
    View to select Data Hub company id and D&B duns number for linking records.
    Valid POSTs redirect to the change review page.
    """
    if not model_admin.has_change_permission(request):
        raise PermissionDenied()

    is_post = request.method == 'POST'
    data = request.POST if is_post else None
    form = SelectIdsToLinkForm(data=data)

    if is_post and form.is_valid():
        review_changes_route_name = admin_urlname(
            model_admin.model._meta,
            'dnb-link-review-changes',
        )
        review_changes_query_args = {
            'company': form.cleaned_data['company'].pk,
            'duns_number': form.cleaned_data['duns_number'],
        }
        review_changes_url = reverse_with_query_string(
            review_changes_route_name,
            review_changes_query_args,
        )
        return HttpResponseRedirect(review_changes_url)

    template_name = 'admin/company/company/dnb_link/step_1_select_ids.html'
    title = gettext_lazy('Link Company with D&B')

    context = {
        **model_admin.admin_site.each_context(request),
        'opts': model_admin.model._meta,
        'title': title,
        'form': form,
        'media': model_admin.media,
    }
    return TemplateResponse(request, template_name, context)
    def test_link_exists(self):
        """
        Test that the link exists for a user with the change company permission.
        """
        company = ArchivedCompanyFactory()

        change_route_name = admin_urlname(Company._meta, 'change')
        change_url = reverse(change_route_name, args=(company.pk, ))

        response = self.client.get(change_url)
        assert response.status_code == status.HTTP_200_OK

        unarchive_route_name = admin_urlname(Company._meta,
                                             'unarchive-company')
        unarchive_query_args = {
            'company': company.pk,
        }
        unarchive_url = reverse_with_query_string(
            unarchive_route_name,
            unarchive_query_args,
        )

        assert unarchive_url in response.rendered_content
示例#18
0
    def test_error_displayed_if_invalid_selection_made(
        self,
        swap,
        company_1_factory,
        company_2_factory,
        expected_error,
    ):
        """Tests that if an invalid selection is submitted, an error is returned."""
        company_1 = (company_2_factory if swap else company_1_factory)()
        company_2 = (company_1_factory if swap else company_2_factory)()
        selected_company = 2 if swap else 1

        select_primary_route_name = admin_urlname(
            Company._meta, 'merge-select-primary-company')
        select_primary_query_args = {
            'company_1': str(company_1.pk),
            'company_2': str(company_2.pk),
        }
        select_primary_url = reverse_with_query_string(
            select_primary_route_name,
            select_primary_query_args,
        )

        response = self.client.post(
            select_primary_url,
            data={
                'company_1': str(company_1.pk),
                'company_2': str(company_2.pk),
                'selected_company': selected_company,
            },
        )
        assert response.status_code == status.HTTP_200_OK
        form = response.context['form']
        assert form.errors == {
            NON_FIELD_ERRORS: [expected_error],
        }
示例#19
0
def test_reverse_with_query_string(query_args, expected_url):
    """Test reverse_with_query_string() for various query arguments."""
    assert reverse_with_query_string('test-disableable-collection',
                                     query_args) == expected_url