django.http.HttpRequest

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

432 Examples 7

3 Source : client.py
with GNU General Public License v3.0
from Aghoreshwar

    def logout(self):
        """Log out the user by removing the cookies and session object."""
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()

    def _parse_json(self, response, **extra):

3 Source : client.py
with MIT License
from Air-999

    def logout(self):
        """Log out the user by removing the cookies and session object."""
        from django.contrib.auth import get_user, logout
        request = HttpRequest()
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            engine = import_module(settings.SESSION_ENGINE)
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()

    def _parse_json(self, response, **extra):

3 Source : test_icatrestauth.py
with Apache License 2.0
from bcgov

    def setUp(self):
        self.mock_auth_user = Mock()
        self.mock_request = HttpRequest()
        self.mock_request.META = self.request_meta

        self.mock_auth_user = get_user_model().objects.create(
            username=self.mock_username, password=self.mock_password, is_active=True
        )

    def test_authenticate_no_creds(self):

3 Source : test_models.py
with MIT License
from betagouv

    def test_send(self, send_mock: Mock):
        email_confirmation = IssuerEmailConfirmation.for_issuer(
            IssuerFactory(email_verified=False)
        )
        request = HttpRequest()

        self.assertIs(email_confirmation.sent, None)
        email_confirmation.send(request)
        self.assertEqual(email_confirmation.sent, self.NOW)
        send_mock.assert_called_with(
            IssuerEmailConfirmation, request=request, confirmation=email_confirmation
        )

    @override_settings(

3 Source : test_models.py
with MIT License
from betagouv

    def test_signal_sends_mail(self, send_mail_mock: Mock):
        email_confirmation = IssuerEmailConfirmation.for_issuer(
            IssuerFactory(email_verified=False)
        )
        request = HttpRequest()
        request.META["SERVER_NAME"] = "localhost"
        request.META["SERVER_PORT"] = "3000"

        email_confirmation.send(request)
        send_mail_mock.assert_called_with(
            from_email=self.EMAIL_FROM,
            recipient_list=[email_confirmation.issuer.email],
            subject=self.EMAIL_SUBJECT,
            message=ANY,
            html_message=ANY,
        )

3 Source : test_models.py
with MIT License
from blockchainGuru1018

    def test_manager_apply_referrer_no_ref(self):
        user = UserFactory()
        request = HttpRequest()
        request.session = {}
        UserReferrer.objects.apply_referrer(user, request)
        with self.assertRaises(UserReferrer.DoesNotExist):
            user.user_referrer

    def test_manager_apply_referrer(self):

3 Source : test_models.py
with MIT License
from blockchainGuru1018

    def test_manager_apply_referrer(self):
        referrer = ReferrerFactory()
        user = UserFactory()
        request = HttpRequest()
        request.session = {settings.SESSION_KEY: referrer.pk}
        UserReferrer.objects.apply_referrer(user, request)
        self.assertEqual(user.user_referrer.referrer, referrer)

3 Source : test_conditions_conditions.py
with Creative Commons Zero v1.0 Universal
from cfpb

    def setUp(self):
        user = User.objects.create_user(username="testuser", email="test@user")
        self.request = HttpRequest()
        self.request.user = user

    def test_user_valid(self):

3 Source : test_decorators.py
with Creative Commons Zero v1.0 Universal
from cfpb

    def setUp(self):
        self.request = HttpRequest()
        self.request.META["SERVER_NAME"] = "localhost"
        self.request.META["SERVER_PORT"] = 8000

        self.mock_view = Mock(__name__="view")
        self.view = lambda request: self.mock_view(request)

    def test_decorated_no_flag_exists(self):

3 Source : test_sources.py
with Creative Commons Zero v1.0 Universal
from cfpb

    def test_caches_flags_on_request_if_provided(self):
        request = HttpRequest()
        self.assertFalse(hasattr(request, "flag_conditions"))
        get_flags(request=request)
        self.assertIsInstance(request.flag_conditions, dict)

    def test_uses_cached_flags_from_request(self):

3 Source : test_sources.py
with Creative Commons Zero v1.0 Universal
from cfpb

    def test_uses_cached_flags_from_request(self):
        request = HttpRequest()

        # The initial call looks up flag conditions from the database source.
        with self.assertNumQueries(1):
            get_flags(request=request)

        # Subsequent calls with a request object don't need to redo the lookup
        # because they have the cached flags.
        with self.assertNumQueries(0):
            get_flags(request=request)

        # But subsequent calls without a request object still redo the lookup.
        with self.assertNumQueries(1):
            get_flags()

3 Source : test_views.py
with Creative Commons Zero v1.0 Universal
from cfpb

    def request(self, path="/"):
        request = HttpRequest()

        request.method = "GET"
        request.path = path
        request.META["SERVER_NAME"] = "localhost"
        request.META["SERVER_PORT"] = 8000

        return request

    def test_no_flag_key_raises_improperly_configured(self):

3 Source : testutils.py
with GNU Affero General Public License v3.0
from chdsbd

    def logout(self) -> None:
        """Log out the user by removing the cookies and session object."""
        request = HttpRequest()
        engine = cast(Any, import_module(settings.SESSION_ENGINE))
        if self.session:
            request.session = self.session
            request.user = auth.get_user(request)  # type: ignore [assignment]
        else:
            request.session = engine.SessionStore()
        auth.logout(request)
        self.cookies = SimpleCookie()

3 Source : client.py
with MIT License
from chunky2808

    def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie()

    def _parse_json(self, response, **extra):

3 Source : event.py
with MIT License
from crosspower

    def _build_request(self) -> Request:
        request = Request(HttpRequest())
        request.user = self._get_executor()
        params = self._add_params()
        if params:
            request._full_data = params

        return request

    def _add_params(self):

3 Source : testing.py
with BSD 3-Clause "New" or "Revised" License
from dgilge

    async def logout(self):
        """Log out the user by removing the cookies and session object."""
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = await database_sync_to_async(get_user)(request)
        else:
            request.session = engine.SessionStore()
        await database_sync_to_async(logout)(request)
        self._session_cookie = b''

3 Source : snippet.py
with Apache License 2.0
from dockerizeme

def expire_page_cache(view, args=None):
    """
    Removes cache created by cache_page functionality. 
    Parameters are used as they are in reverse()
    """

    if args is None:
        path = reverse(view)
    else:
        path = reverse(view, args=args)

    request = HttpRequest()
    request.path = path
    key = get_cache_key(request)
    if cache.has_key(key):
        cache.delete(key)

3 Source : test_template.py
with MIT License
from etalab

    def test_rendered(self):
            request = HttpRequest()
            request.method = 'GET'
            needle = '  <  input type="password" name="password1" class=" input" required id="id_password1">'
            self.assertInHTML(needle, str(SignupView.as_view()(request, as_string=True).content))


@override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage')

3 Source : test_template.py
with MIT License
from etalab

    def test_signup_not_allowed(self):
            ALLOW_SIGNUP = settings.ALLOW_SIGNUP
            settings.ALLOW_SIGNUP = False
            request = HttpRequest()
            request.method = 'POST'
            response = SignupView.as_view()(request, as_string=True)
            settings.ALLOW_SIGNUP = ALLOW_SIGNUP
            self.assertEqual(response.status_code, 302)


@override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage')

3 Source : test_auth_backends.py
with Apache License 2.0
from gethue

    def test_does_not_shadow_exception(self):
        # Prepare a request object
        request = HttpRequest()
        request.session = self.client.session

        with self.assertRaises(ImproperlyConfigured):
            get_user(request)


class ImportedModelBackend(ModelBackend):

3 Source : test_auth_backends.py
with Apache License 2.0
from gethue

    def test_backend_path(self):
        username = 'username'
        password = 'password'
        User.objects.create_user(username, 'email', password)
        self.assertTrue(self.client.login(username=username, password=password))
        request = HttpRequest()
        request.session = self.client.session
        self.assertEqual(request.session[BACKEND_SESSION_KEY], self.backend)


class SelectingBackendTests(TestCase):

3 Source : test_auth_backends.py
with Apache License 2.0
from gethue

    def assertBackendInSession(self, backend):
        request = HttpRequest()
        request.session = self.client.session
        self.assertEqual(request.session[BACKEND_SESSION_KEY], backend)

    @override_settings(AUTHENTICATION_BACKENDS=[backend])

3 Source : test_auth_backends.py
with Apache License 2.0
from gethue

    def test_get_user(self):
        self.client.force_login(self.user)
        request = HttpRequest()
        request.session = self.client.session
        user = get_user(request)
        self.assertEqual(user, self.user)

3 Source : test_basic.py
with Apache License 2.0
from gethue

    def test_get_user_anonymous(self):
        request = HttpRequest()
        request.session = self.client.session
        user = get_user(request)
        self.assertIsInstance(user, AnonymousUser)

    def test_get_user(self):

3 Source : test_basic.py
with Apache License 2.0
from gethue

    def test_get_user(self):
        created_user = User.objects.create_user('testuser', '[email protected]', 'testpw')
        self.client.login(username='testuser', password='testpw')
        request = HttpRequest()
        request.session = self.client.session
        user = get_user(request)
        self.assertIsInstance(user, User)
        self.assertEqual(user.username, created_user.username)

3 Source : test_middleware.py
with Apache License 2.0
from gethue

    def setUp(self):
        self.user = User.objects.create_user('test_user', '[email protected]', 'test_password')
        self.middleware = AuthenticationMiddleware()
        self.client.force_login(self.user)
        self.request = HttpRequest()
        self.request.session = self.client.session

    def test_no_password_change_doesnt_invalidate_session(self):

3 Source : test_views.py
with Apache License 2.0
from gethue

    def test_default_logout_then_login(self):
        self.login()
        req = HttpRequest()
        req.method = 'GET'
        req.session = self.client.session
        response = logout_then_login(req)
        self.confirm_logged_out()
        self.assertRedirects(response, '/login/', fetch_redirect_response=False)

    def test_logout_then_login_with_custom_login(self):

3 Source : test_views.py
with Apache License 2.0
from gethue

    def test_logout_then_login_with_custom_login(self):
        self.login()
        req = HttpRequest()
        req.method = 'GET'
        req.session = self.client.session
        response = logout_then_login(req, login_url='/custom/')
        self.confirm_logged_out()
        self.assertRedirects(response, '/custom/', fetch_redirect_response=False)

    def test_deprecated_extra_context(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_get_cache_key_with_query(self):
        request = self.factory.get(self.path, {'test': 1})
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        # Expect None if no headers have been set yet.
        self.assertIsNone(get_cache_key(request))
        # Set headers to an empty list.
        learn_cache_key(request, response)
        # The querystring is taken into account.
        self.assertEqual(
            get_cache_key(request),
            'views.decorators.cache.cache_page.settingsprefix.GET.'
            '0f1c2d56633c943073c4569d9a9502fe.d41d8cd98f00b204e9800998ecf8427e'
        )

    @override_settings(USE_ETAGS=False)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_without_etag(self):
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        self.assertFalse(response.has_header('ETag'))
        patch_response_headers(response)
        self.assertFalse(response.has_header('ETag'))
        response = response.render()
        self.assertFalse(response.has_header('ETag'))

    @ignore_warnings(category=RemovedInDjango21Warning)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_with_etag(self):
        template = engines['django'].from_string("This is a test")
        response = TemplateResponse(HttpRequest(), template)
        self.assertFalse(response.has_header('ETag'))
        patch_response_headers(response)
        self.assertFalse(response.has_header('ETag'))
        response = response.render()
        self.assertTrue(response.has_header('ETag'))


class TestMakeTemplateFragmentKey(SimpleTestCase):

3 Source : test_models.py
with Apache License 2.0
from gethue

    def test_shortcut_view_without_get_absolute_url(self):
        """
        The shortcut view (used for the admin "view on site" functionality)
        returns 404 when get_absolute_url is not defined.
        """
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "Example.com",
            "SERVER_PORT": "80",
        }
        user_ct = ContentType.objects.get_for_model(FooWithoutUrl)
        obj = FooWithoutUrl.objects.create(name="john")

        with self.assertRaises(Http404):
            shortcut(request, user_ct.id, obj.id)

    def test_shortcut_view_with_broken_get_absolute_url(self):

3 Source : test_models.py
with Apache License 2.0
from gethue

    def test_shortcut_view_with_broken_get_absolute_url(self):
        """
        The shortcut view does not catch an AttributeError raised by
        the model's get_absolute_url() method (#8997).
        """
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "Example.com",
            "SERVER_PORT": "80",
        }
        user_ct = ContentType.objects.get_for_model(FooWithBrokenAbsoluteUrl)
        obj = FooWithBrokenAbsoluteUrl.objects.create(name="john")

        with self.assertRaises(AttributeError):
            shortcut(request, user_ct.id, obj.id)

    def test_missing_model(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_no_session_on_request(self):
        msg = (
            'CSRF_USE_SESSIONS is enabled, but request.session is not set. '
            'SessionMiddleware must appear before CsrfViewMiddleware in MIDDLEWARE.'
        )
        with self.assertRaisesMessage(ImproperlyConfigured, msg):
            self.mw.process_request(HttpRequest())

    def test_process_response_get_token_used(self):

3 Source : test_context_processor.py
with Apache License 2.0
from gethue

    def test_force_text_on_token(self):
        request = HttpRequest()
        test_token = '1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD'
        request.META['CSRF_COOKIE'] = test_token
        token = csrf(request).get('csrf_token')
        self.assertTrue(equivalent_tokens(force_text(token), test_token))

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_cache_page(self):
        def my_view(request):
            return "response"
        my_view_cached = cache_page(123)(my_view)
        self.assertEqual(my_view_cached(HttpRequest()), "response")
        my_view_cached2 = cache_page(123, key_prefix="test")(my_view)
        self.assertEqual(my_view_cached2(HttpRequest()), "response")

    def test_require_safe_accepts_only_safe_methods(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_deny_decorator(self):
        """
        Ensures @xframe_options_deny properly sets the X-Frame-Options header.
        """
        @xframe_options_deny
        def a_view(request):
            return HttpResponse()
        r = a_view(HttpRequest())
        self.assertEqual(r['X-Frame-Options'], 'DENY')

    def test_sameorigin_decorator(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_sameorigin_decorator(self):
        """
        Ensures @xframe_options_sameorigin properly sets the X-Frame-Options
        header.
        """
        @xframe_options_sameorigin
        def a_view(request):
            return HttpResponse()
        r = a_view(HttpRequest())
        self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

    def test_exempt_decorator(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_never_cache_decorator(self):
        @never_cache
        def a_view(request):
            return HttpResponse()
        r = a_view(HttpRequest())
        self.assertEqual(
            set(r['Cache-Control'].split(', ')),
            {'max-age=0', 'no-cache', 'no-store', 'must-revalidate'},
        )

3 Source : test_middleware.py
with Apache License 2.0
from gethue

    def test_response_without_messages(self):
        """
        MessageMiddleware is tolerant of messages not existing on request.
        """
        request = http.HttpRequest()
        response = http.HttpResponse()
        self.middleware.process_response(request, response)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_etag(self):
        req = HttpRequest()
        res = HttpResponse('content')
        self.assertTrue(CommonMiddleware().process_response(req, res).has_header('ETag'))

    @ignore_warnings(category=RemovedInDjango21Warning)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_etag_streaming_response(self):
        req = HttpRequest()
        res = StreamingHttpResponse(['content'])
        res['ETag'] = 'tomatoes'
        self.assertEqual(CommonMiddleware().process_response(req, res).get('ETag'), 'tomatoes')

    @ignore_warnings(category=RemovedInDjango21Warning)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_no_etag_streaming_response(self):
        req = HttpRequest()
        res = StreamingHttpResponse(['content'])
        self.assertFalse(CommonMiddleware().process_response(req, res).has_header('ETag'))

    @ignore_warnings(category=RemovedInDjango21Warning)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_no_etag_no_store_cache(self):
        req = HttpRequest()
        res = HttpResponse('content')
        res['Cache-Control'] = 'No-Cache, No-Store, Max-age=0'
        self.assertFalse(CommonMiddleware().process_response(req, res).has_header('ETag'))

    @ignore_warnings(category=RemovedInDjango21Warning)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_etag_extended_cache_control(self):
        req = HttpRequest()
        res = HttpResponse('content')
        res['Cache-Control'] = 'my-directive="my-no-store"'
        self.assertTrue(CommonMiddleware().process_response(req, res).has_header('ETag'))

    @ignore_warnings(category=RemovedInDjango21Warning)

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_if_none_match(self):
        first_req = HttpRequest()
        first_res = CommonMiddleware().process_response(first_req, HttpResponse('content'))
        second_req = HttpRequest()
        second_req.method = 'GET'
        second_req.META['HTTP_IF_NONE_MATCH'] = first_res['ETag']
        second_res = CommonMiddleware().process_response(second_req, HttpResponse('content'))
        self.assertEqual(second_res.status_code, 304)

    # Tests for the Content-Length header

    def test_content_length_header_added(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_content_length_header_added(self):
        response = HttpResponse('content')
        self.assertNotIn('Content-Length', response)
        response = CommonMiddleware().process_response(HttpRequest(), response)
        self.assertEqual(int(response['Content-Length']), len(response.content))

    def test_content_length_header_not_added_for_streaming_response(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_content_length_header_not_added_for_streaming_response(self):
        response = StreamingHttpResponse('content')
        self.assertNotIn('Content-Length', response)
        response = CommonMiddleware().process_response(HttpRequest(), response)
        self.assertNotIn('Content-Length', response)

    def test_content_length_header_not_changed(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_content_length_header_not_changed(self):
        response = HttpResponse()
        bad_content_length = len(response.content) + 10
        response['Content-Length'] = bad_content_length
        response = CommonMiddleware().process_response(HttpRequest(), response)
        self.assertEqual(int(response['Content-Length']), bad_content_length)

    # Other tests

    @override_settings(DISALLOWED_USER_AGENTS=[re.compile(r'foo')])

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_same_origin(self):
        """
        The X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the
        middleware use that value for the HTTP header.
        """
        with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
            r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
            self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

        with override_settings(X_FRAME_OPTIONS='sameorigin'):
            r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
            self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')

    def test_deny(self):

See More Examples