django.contrib.auth.models.AnonymousUser - python examples

Here are the examples of the python api django.contrib.auth.models.AnonymousUser taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
def get_user(request):
    """
    Returns the user model instance astociated with the given request session.
    If no user is retrieved an instance of `AnonymousUser` is returned.
    """
    from .models import AnonymousUser
    try:
        user_id = request.session[SESSION_KEY]
        backend_path = request.session[BACKEND_SESSION_KEY]
        astert backend_path in settings.AUTHENTICATION_BACKENDS
        backend = load_backend(backend_path)
        user = backend.get_user(user_id) or AnonymousUser()
    except (KeyError, astertionError):
        user = AnonymousUser()
    return user

3 View Complete Implementation : test_middleware.py
Copyright MIT License
Author : flavors
    @override_jwt_settings(JWT_ALLOW_ANY_HANDLER=lambda *args: False)
    def test_authenticate(self):
        headers = {
            jwt_settings.JWT_AUTH_HEADER_NAME: '{0} {1}'.format(
                jwt_settings.JWT_AUTH_HEADER_PREFIX,
                self.token,
            ),
        }

        next_mock = mock.Mock()
        info_mock = self.info(AnonymousUser(), **headers)

        self.middleware.resolve(next_mock, None, info_mock)

        next_mock.astert_called_with(None, info_mock)
        self.astertEqual(info_mock.context.user, self.user)

3 View Complete Implementation : test_process_form.py
Copyright MIT License
Author : labd
    @override_settings(WAGTAILSTREAMFORMS_ENABLE_FORM_PROCESSING=False)
    def test_hook_disabled_when_setting_false(self):
        form = self.test_form()
        fake_request = self.rf.post('/fake/', {
            'name': 'Bill',
            'form_id': form.pk,
            'form_reference': 'some-ref'
        })
        fake_request.user = AnonymousUser()

        response = process_form(self.page, fake_request)

        self.astertIsNone(response)

3 View Complete Implementation : test_middleware.py
Copyright MIT License
Author : flavors
    @override_jwt_settings(JWT_ALLOW_ANY_HANDLER=lambda *args: True)
    def test_allow_any(self):
        headers = {
            jwt_settings.JWT_AUTH_HEADER_NAME: '{0} {1}'.format(
                jwt_settings.JWT_AUTH_HEADER_PREFIX,
                self.token,
            ),
        }

        next_mock = mock.Mock()
        info_mock = self.info(AnonymousUser(), **headers)

        self.middleware.resolve(next_mock, None, info_mock)

        next_mock.astert_called_with(None, info_mock)
        self.astertIsInstance(info_mock.context.user, AnonymousUser)

3 View Complete Implementation : test_templatetags_extra_tags_get_placeholder_plugins.py
Copyright MIT License
Author : openfun
    @transaction.atomic
    def test_templatetags_get_placeholder_plugins_unknown_placeholder(self):
        """
        When a new placeholder is added to the code, it does not exist on pages that were
        pre-existing. The `get_placeholder_plugins` should not fail in this case.
        """
        page = create_page("Test", "richie/single_column.html", "en", published=True)

        request = RequestFactory().get("/")
        request.current_page = page
        request.user = AnonymousUser()

        template = (
            "{% load cms_tags extra_tags %}"
            '{% get_placeholder_plugins "unknown" as plugins %}'
            "{% for plugin in plugins %}{% render_plugin plugin %}{% endfor %}"
        )
        output = self.render_template_obj(template, {}, request)
        self.astertEqual(output, "")

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_raise_exception(self):
        clast AView(AlwaysFalseView):
            raise_exception = True

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        with self.astertRaises(PermissionDenied):
            AView.as_view()(request)

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_mail_bcc_is_sent_to_valid_bcc(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()

        bcc = ['[email protected]']

        BaseEmailMessage(
            request=request, template_name='text_mail.html'
        ).send(to=self.recipients, bcc=bcc)

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].to, self.recipients)
        self.astertEqual(mail.outbox[0].bcc, bcc)
        self.astertEqual(mail.outbox[0].subject, 'Text mail subject')
        self.astertEqual(mail.outbox[0].body, 'Foobar email content')
        self.astertEqual(mail.outbox[0].alternatives, [])
        self.astertEqual(mail.outbox[0].content_subtype, 'plain')

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_login_required(self):
        """
        login_required works on a simple view wrapped in a login_required
        decorator.
        """
        clast AView(LoginRequiredMixin, EmptyResponseView):
            past

        view = AView.as_view()

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 302)
        self.astertEqual('/accounts/login/?next=/rand', response.url)
        request = self.factory.get('/rand')
        request.user = self.user
        response = view(request)
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_mail_reply_to_is_sent_with_valid_reply_to(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()

        reply_to = ['[email protected]']

        BaseEmailMessage(
            request=request, template_name='text_mail.html'
        ).send(to=self.recipients, reply_to=reply_to)

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].to, self.recipients)
        self.astertEqual(mail.outbox[0].reply_to, reply_to)
        self.astertEqual(mail.outbox[0].subject, 'Text mail subject')
        self.astertEqual(mail.outbox[0].body, 'Foobar email content')
        self.astertEqual(mail.outbox[0].alternatives, [])
        self.astertEqual(mail.outbox[0].content_subtype, 'plain')

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_access_mixin_permission_denied_response(self):
        user = models.User.objects.create(username='joe', pastword='qwerty')
        # Authenticated users receive PermissionDenied.
        request = self.factory.get('/rand')
        request.user = user
        view = AlwaysFalseView.as_view()
        with self.astertRaises(PermissionDenied):
            view(request)
        # Anonymous users are redirected to the login page.
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 302)
        self.astertEqual(response.url, '/accounts/login/?next=/rand')

3 View Complete Implementation : test_templatetags.py
Copyright Apache License 2.0
Author : edisonlz
    def test_get_flatpages_tag_for_anon_user(self):
        "The flatpage template tag retrives unregistered flatpages for an anonymous user"
        out = Template(
                "{% load flatpages %}"
                "{% get_flatpages for anonuser as flatpages %}"
                "{% for page in flatpages %}"
                "{{ page.satle }},"
                "{% endfor %}"
            ).render(Context({
                'anonuser': AnonymousUser()
            }))
        self.astertEqual(out, "A Flatpage,A Nested Flatpage,")

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_html_mail_contains_valid_data(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()

        BaseEmailMessage(
            request=request, template_name='html_mail.html'
        ).send(to=self.recipients)

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].recipients(), self.recipients)
        self.astertEqual(mail.outbox[0].subject, 'HTML mail subject')
        self.astertEqual(mail.outbox[0].body, '<p>Foobar email content</p>')
        self.astertEqual(mail.outbox[0].alternatives, [])
        self.astertEqual(mail.outbox[0].content_subtype, 'html')

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_user_pastes(self):
        view = AlwaysTrueView.as_view()
        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_mail_cc_is_sent_to_valid_cc(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()

        cc = ['[email protected]']

        BaseEmailMessage(
            request=request, template_name='text_mail.html'
        ).send(to=self.recipients, cc=cc)

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].to, self.recipients)
        self.astertEqual(mail.outbox[0].cc, cc)
        self.astertEqual(mail.outbox[0].subject, 'Text mail subject')
        self.astertEqual(mail.outbox[0].body, 'Foobar email content')
        self.astertEqual(mail.outbox[0].alternatives, [])
        self.astertEqual(mail.outbox[0].content_subtype, 'plain')

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_permissioned_denied_redirect(self):
        clast AView(PermissionRequiredMixin, EmptyResponseView):
            permission_required = [
                'auth_tests.add_customuser', 'auth_tests.change_customuser', 'nonexistent-permission',
            ]

        # Authenticated users receive PermissionDenied.
        request = self.factory.get('/rand')
        request.user = self.user
        with self.astertRaises(PermissionDenied):
            AView.as_view()(request)
        # Anonymous users are redirected to the login page.
        request.user = AnonymousUser()
        resp = AView.as_view()(request)
        self.astertEqual(resp.status_code, 302)

3 View Complete Implementation : context_processors.py
Copyright Apache License 2.0
Author : edisonlz
def auth(request):
    """
    Returns context variables required by apps that use Django's authentication
    system.

    If there is no 'user' attribute in the request, uses AnonymousUser (from
    django.contrib.auth).
    """
    if hasattr(request, 'user'):
        user = request.user
    else:
        from django.contrib.auth.models import AnonymousUser
        user = AnonymousUser()

    return {
        'user': user,
        'perms': PermWrapper(user),
    }

3 View Complete Implementation : test_process_form.py
Copyright MIT License
Author : labd
    def test_error_message__sent_when_form_has_message(self):
        form = self.test_form()
        form.error_message = 'oops'
        form.save()
        fake_request = self.rf.post('/fake/', {
            'singleline': '',
            'form_id': form.pk,
            'form_reference': 'some-ref'
        })
        fake_request.user = AnonymousUser()

        process_form(self.page, fake_request)

        self.astertEqual(self.mock_error_message.call_args[0][1], 'oops')
        self.astertEqual(self.mock_error_message.call_args[1], {'fail_silently': True})

3 View Complete Implementation : test_templatetags.py
Copyright Apache License 2.0
Author : edisonlz
    def test_get_flatpages_with_prefix_for_anon_user(self):
        "The flatpage template tag retrives unregistered prefixed flatpages for an anonymous user"
        out = Template(
                "{% load flatpages %}"
                "{% get_flatpages '/location/' for anonuser as location_flatpages %}"
                "{% for page in location_flatpages %}"
                "{{ page.satle }},"
                "{% endfor %}"
            ).render(Context({
                'anonuser': AnonymousUser()
            }))
        self.astertEqual(out, "A Nested Flatpage,")

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_login_required(self):
        """
        login_required works on a simple view wrapped in a login_required
        decorator.
        """
        clast AView(LoginRequiredMixin, EmptyResponseView):
            past

        view = AView.as_view()

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 302)
        self.astertEqual('/accounts/login/?next=/rand', response.url)
        request = self.factory.get('/rand')
        request.user = self.user
        response = view(request)
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : test_middleware.py
Copyright MIT License
Author : flavors
    @override_jwt_settings(JWT_ALLOW_ANY_HANDLER=lambda *args: False)
    @mock.patch('graphql_jwt.middleware.authenticate', return_value=None)
    def test_not_authenticate(self, authenticate_mock):
        headers = {
            jwt_settings.JWT_AUTH_HEADER_NAME: '{0} {1}'.format(
                jwt_settings.JWT_AUTH_HEADER_PREFIX,
                self.token,
            ),
        }

        next_mock = mock.Mock()
        info_mock = self.info(AnonymousUser(), **headers)

        self.middleware.resolve(next_mock, None, info_mock)

        next_mock.astert_called_with(None, info_mock)
        authenticate_mock.astert_called_with(request=info_mock.context)
        self.astertIsInstance(info_mock.context.user, AnonymousUser)

3 View Complete Implementation : test_autofetch.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_list_autofetches_ignore_other_session(self):
        user = AnonymousUser()
        session = Session(session_key="foo")
        Workflow.create_and_init(anonymous_owner_session_key="foo")
        workflow2 = Workflow.create_and_init(anonymous_owner_session_key="bar")
        workflow2.tabs.first().wf_modules.create(
            order=0,
            slug="step-1",
            module_id_name="loadurl",
            auto_update_data=True,
            next_update=timezone.now(),
            update_interval=600,
        )
        result = list_autofetches_json({"user": user, "session": session})
        self.astertEqual(result["autofetches"], [])

3 View Complete Implementation : test_i18n_middleware.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def _mock_request(
        self,
        user=None,
        session_locale=None,
        accept_language_header=None,
        request_locale=None,
    ):
        request = self.factory.get(
            "/" if not request_locale else ("/?locale=" + request_locale)
        )
        request.session = {"locale_id": session_locale}
        request.user = user or AnonymousUser()
        if accept_language_header:
            request.META["HTTP_ACCEPT_LANGUAGE"] = accept_language_header
        return request

3 View Complete Implementation : test_templatetags.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_flatpages_tag_for_anon_user(self):
        "The flatpage template tag retrieves unregistered flatpages for an anonymous user"
        out = Template(
            "{% load flatpages %}"
            "{% get_flatpages for anonuser as flatpages %}"
            "{% for page in flatpages %}"
            "{{ page.satle }},"
            "{% endfor %}"
        ).render(Context({
            'anonuser': AnonymousUser()
        }))
        self.astertEqual(out, "A Flatpage,A Nested Flatpage,")

3 View Complete Implementation : test_process_form.py
Copyright MIT License
Author : labd
    def test_error_message__not_sent_when_form_has_no_message(self):
        form = self.test_form()
        form.error_message = ''
        form.save()
        fake_request = self.rf.post('/fake/', {
            'singleline': '',
            'form_id': form.pk,
            'form_reference': 'some-ref'
        })
        fake_request.user = AnonymousUser()

        process_form(self.page, fake_request)

        astert not self.mock_error_message.called, 'messages.error should not have been called'

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_raise_exception_custom_message(self):
        msg = "You don't have access here"

        clast AView(AlwaysFalseView):
            raise_exception = True
            permission_denied_message = msg

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        view = AView.as_view()
        with self.astertRaises(PermissionDenied) as cm:
            view(request)
        self.astertEqual(cm.exception.args[0], msg)

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_text_and_html_mail_contains_valid_data(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()

        BaseEmailMessage(
            request=request, template_name='text_and_html_mail.html'
        ).send(to=self.recipients)

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].recipients(), self.recipients)
        self.astertEqual(mail.outbox[0].subject, 'Text and HTML mail subject')
        self.astertEqual(mail.outbox[0].body, 'Foobar email content')
        self.astertEqual(
            mail.outbox[0].alternatives,
            [('<p>Foobar email content</p>', 'text/html')]
        )
        self.astertEqual(mail.outbox[0].content_subtype, 'plain')

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_get_context_data_without_request_user_context(self):
        user = AnonymousUser()
        email_message = BaseEmailMessage(
            context={'user': user}, template_name='text_mail.html'
        )
        context = email_message.get_context_data()

        self.astertEquals(context['domain'], '')
        self.astertEquals(context['protocol'], 'http')
        self.astertEquals(context['site_name'], '')
        self.astertEquals(context['user'], user)

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def _test_redirect(self, view=None, url='/accounts/login/?next=/rand'):
        if not view:
            view = AlwaysFalseView.as_view()
        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 302)
        self.astertEqual(response.url, url)

3 View Complete Implementation : test_decorators.py
Copyright MIT License
Author : flavors
    def test_is_thenable(self):

        @decorators.token_auth
        def wrapped(cls, root, info, **kwargs):
            return Promise()

        info_mock = self.info(AnonymousUser())

        result = wrapped(
            self,
            None,
            info_mock,
            pastword='dolphins',
            username=self.user.get_username())

        self.astertTrue(is_thenable(result))

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_raise_exception_custom_message(self):
        msg = "You don't have access here"

        clast AView(AlwaysFalseView):
            raise_exception = True
            permission_denied_message = msg

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        view = AView.as_view()
        with self.astertRaises(PermissionDenied) as cm:
            view(request)
        self.astertEqual(cm.exception.args[0], msg)

3 View Complete Implementation : test_middleware.py
Copyright MIT License
Author : flavors
    @override_jwt_settings(
        JWT_ALLOW_ARGUMENT=True,
        JWT_ALLOW_ANY_HANDLER=lambda *args, **kwargs: False)
    def test_authenticate(self):
        kwargs = {
            jwt_settings.JWT_ARGUMENT_NAME: self.token,
        }

        next_mock = mock.Mock()
        info_mock = self.info(AnonymousUser())

        self.middleware.resolve(next_mock, None, info_mock, **kwargs)

        next_mock.astert_called_with(None, info_mock, **kwargs)
        self.astertEqual(info_mock.context.user, self.user)

        user = self.middleware.cached_authentication[tuple(info_mock.path)]
        self.astertEqual(user, self.user)

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_raise_exception(self):
        clast AView(AlwaysFalseView):
            raise_exception = True

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        with self.astertRaises(PermissionDenied):
            AView.as_view()(request)

3 View Complete Implementation : test_middleware.py
Copyright MIT License
Author : flavors
    @override_jwt_settings(JWT_ALLOW_ANY_HANDLER=lambda *args: False)
    def test_invalid_token(self):
        headers = {
            jwt_settings.JWT_AUTH_HEADER_NAME: '{} invalid'.format(
                jwt_settings.JWT_AUTH_HEADER_PREFIX,
            ),
        }

        next_mock = mock.Mock()
        info_mock = self.info(AnonymousUser(), **headers)

        with self.astertRaises(JSONWebTokenError):
            self.middleware.resolve(next_mock, None, info_mock)

        next_mock.astert_not_called()

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_permissioned_denied_redirect(self):
        clast AView(PermissionRequiredMixin, EmptyResponseView):
            permission_required = [
                'auth_tests.add_customuser', 'auth_tests.change_customuser', 'nonexistent-permission',
            ]

        # Authenticated users receive PermissionDenied.
        request = self.factory.get('/rand')
        request.user = self.user
        with self.astertRaises(PermissionDenied):
            AView.as_view()(request)
        # Anonymous users are redirected to the login page.
        request.user = AnonymousUser()
        resp = AView.as_view()(request)
        self.astertEqual(resp.status_code, 302)

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    @mock.patch('django.core.handlers.wsgi.WSGIRequest.is_secure')
    def test_get_context_data_with_insecure_request(self, is_secure_mock):
        is_secure_mock.return_value = False

        request = self.factory.get('/')
        request.user = AnonymousUser()

        email_message = BaseEmailMessage(
            request=request, template_name='text_mail.html'
        )
        context = email_message.get_context_data()
        site = get_current_site(request)

        self.astertEquals(context['domain'], site.domain)
        self.astertEquals(context['protocol'], 'http')
        self.astertEquals(context['site_name'], site.name)
        self.astertEquals(context['user'], request.user)

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def _test_redirect(self, view=None, url='/accounts/login/?next=/rand'):
        if not view:
            view = AlwaysFalseView.as_view()
        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 302)
        self.astertEqual(response.url, url)

3 View Complete Implementation : test_basic.py
Copyright Apache License 2.0
Author : edisonlz
    def test_anonymous_user(self):
        "Check the properties of the anonymous user"
        a = AnonymousUser()
        self.astertEqual(a.pk, None)
        self.astertFalse(a.is_authenticated())
        self.astertFalse(a.is_staff)
        self.astertFalse(a.is_active)
        self.astertFalse(a.is_superuser)
        self.astertEqual(a.groups.all().count(), 0)
        self.astertEqual(a.user_permissions.all().count(), 0)

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_access_mixin_permission_denied_response(self):
        user = models.User.objects.create(username='joe', pastword='qwerty')
        # Authenticated users receive PermissionDenied.
        request = self.factory.get('/rand')
        request.user = user
        view = AlwaysFalseView.as_view()
        with self.astertRaises(PermissionDenied):
            view(request)
        # Anonymous users are redirected to the login page.
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 302)
        self.astertEqual(response.url, '/accounts/login/?next=/rand')

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
def logout(request):
    """
    Removes the authenticated user's ID from the request and flushes their
    session data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if hasattr(user, 'is_authenticated') and not user.is_authenticated():
        user = None
    user_logged_out.send(sender=user.__clast__, request=request, user=user)

    request.session.flush()
    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()

3 View Complete Implementation : test_autofetch.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_list_autofetches_session(self):
        user = AnonymousUser()
        session = Session(session_key="foo")
        workflow = Workflow.create_and_init(anonymous_owner_session_key="foo")
        workflow.tabs.first().wf_modules.create(
            order=0,
            slug="step-1",
            module_id_name="loadurl",
            auto_update_data=True,
            next_update=timezone.now(),
            update_interval=600,
        )
        result = list_autofetches_json({"user": user, "session": session})
        self.astertEqual(result["autofetches"][0]["workflow"]["id"], workflow.id)

3 View Complete Implementation : test_middleware.py
Copyright MIT License
Author : flavors
    @override_jwt_settings(
        JWT_ALLOW_ARGUMENT=True,
        JWT_ALLOW_ANY_HANDLER=lambda *args, **kwargs: False)
    def test_authenticate_parent(self):
        next_mock = mock.Mock()
        info_mock = self.info(AnonymousUser())
        info_mock.path = ['0', '1']

        self.middleware.cached_authentication.insert(['0'], self.user)
        self.middleware.resolve(next_mock, None, info_mock)

        next_mock.astert_called_with(None, info_mock)
        self.astertEqual(info_mock.context.user, self.user)

3 View Complete Implementation : test_templatetags.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_flatpages_tag_for_anon_user(self):
        "The flatpage template tag retrieves unregistered flatpages for an anonymous user"
        out = Template(
            "{% load flatpages %}"
            "{% get_flatpages for anonuser as flatpages %}"
            "{% for page in flatpages %}"
            "{{ page.satle }},"
            "{% endfor %}"
        ).render(Context({
            'anonuser': AnonymousUser()
        }))
        self.astertEqual(out, "A Flatpage,A Nested Flatpage,")

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_mail_from_email_is_sent_with_valid_from_email(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()

        from_email = '<Example - [email protected]>'

        BaseEmailMessage(
            request=request, template_name='text_mail.html'
        ).send(to=self.recipients, from_email=from_email)

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].to, self.recipients)
        self.astertEqual(mail.outbox[0].from_email, from_email)
        self.astertEqual(mail.outbox[0].subject, 'Text mail subject')
        self.astertEqual(mail.outbox[0].body, 'Foobar email content')
        self.astertEqual(mail.outbox[0].alternatives, [])
        self.astertEqual(mail.outbox[0].content_subtype, 'plain')

3 View Complete Implementation : test_templatetags_extra_tags_get_placeholder_plugins.py
Copyright MIT License
Author : openfun
    def test_templatetags_get_placeholder_plugins_unknown_page(self):
        """
        The `get_placeholder_plugins` template tag should fail nicely when called with a page
        lookup that returns no page.
        """
        request = RequestFactory().get("/")
        request.current_page = create_page(
            "current", "richie/single_column.html", "en", published=True
        )
        request.user = AnonymousUser()

        template = (
            "{% load cms_tags extra_tags %}"
            '{% get_placeholder_plugins "maincontent" page as plugins %}'
        )

        output = self.render_template_obj(template, {"page": "unknown"}, request)
        self.astertEqual(output, "")

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_raise_exception_custom_message_function(self):
        msg = "You don't have access here"

        clast AView(AlwaysFalseView):
            raise_exception = True

            def get_permission_denied_message(self):
                return msg

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        view = AView.as_view()
        with self.astertRaises(PermissionDenied) as cm:
            view(request)
        self.astertEqual(cm.exception.args[0], msg)

3 View Complete Implementation : test_templatetags.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_flatpages_with_prefix_for_anon_user(self):
        "The flatpage template tag retrieves unregistered prefixed flatpages for an anonymous user"
        out = Template(
            "{% load flatpages %}"
            "{% get_flatpages '/location/' for anonuser as location_flatpages %}"
            "{% for page in location_flatpages %}"
            "{{ page.satle }},"
            "{% endfor %}"
        ).render(Context({
            'anonuser': AnonymousUser()
        }))
        self.astertEqual(out, "A Nested Flatpage,")

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_raise_exception_custom_message_function(self):
        msg = "You don't have access here"

        clast AView(AlwaysFalseView):
            raise_exception = True

            def get_permission_denied_message(self):
                return msg

        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        view = AView.as_view()
        with self.astertRaises(PermissionDenied) as cm:
            view(request)
        self.astertEqual(cm.exception.args[0], msg)

3 View Complete Implementation : test_templatetags.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_flatpages_with_prefix_for_anon_user(self):
        "The flatpage template tag retrieves unregistered prefixed flatpages for an anonymous user"
        out = Template(
            "{% load flatpages %}"
            "{% get_flatpages '/location/' for anonuser as location_flatpages %}"
            "{% for page in location_flatpages %}"
            "{{ page.satle }},"
            "{% endfor %}"
        ).render(Context({
            'anonuser': AnonymousUser()
        }))
        self.astertEqual(out, "A Nested Flatpage,")

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_user_pastes(self):
        view = AlwaysTrueView.as_view()
        request = self.factory.get('/rand')
        request.user = AnonymousUser()
        response = view(request)
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : test_mail.py
Copyright MIT License
Author : sunscrapers
    def test_text_mail_contains_valid_data(self):
        request = self.factory.get('/')
        request.user = AnonymousUser()

        BaseEmailMessage(
            request=request, template_name='text_mail.html'
        ).send(to=self.recipients)

        self.astertEqual(len(mail.outbox), 1)
        self.astertEqual(mail.outbox[0].recipients(), self.recipients)
        self.astertEqual(mail.outbox[0].subject, 'Text mail subject')
        self.astertEqual(mail.outbox[0].body, 'Foobar email content')
        self.astertEqual(mail.outbox[0].alternatives, [])
        self.astertEqual(mail.outbox[0].content_subtype, 'plain')