Django Testing - access session in RequestFactory

django requestfactory
django test use existing database
django test middleware
django test settings
django integration testing
django test views
django testing class-based views
django test verbose

I am using RequestFactory in a Django test, and I can't find the right way to access the session variable, and I'm getting the following error when I try self.factory._session["zip_id"] or self.factory.session["zip_id"].

======================================================================
ERROR: test_middleware (dj_geo.tests.IPToZipMiddleWareTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\dj_site_test\dj_geo\tests.py", line 36, in test_middleware
    assert self.factory._session["zip_id"] != None
AttributeError: 'RequestFactory' object has no attribute '_session'

----------------------------------------------------------------------



@override_settings(MIDDLEWARE_CLASSES=(
    'dj_geo.middleware.IPToZipMiddleWare'
))
class IPToZipMiddleWareTest(TestCase):

    def test_middleware(self):
        Zipcode.syncdb()
        assert Zipcode.objects.all().count() > 0

        self.factory = RequestFactory()
        self.request = self.factory.get('/', {}, **{'REMOTE_ADDR':'108.31.178.99'})
        assert self.factory._session["zip_id"] != None
        assert self.factory._session["zip_id"] != ""

save session information to request using your middleware

from django.contrib.sessions.middleware import SessionMiddleware

request = RequestFactory().get('/')
middleware = SessionMiddleware()
middleware.process_request(request)
request.session.save()

How to add session and messages in Django RequestFactory, If you are using RequestFactory while testing your Django views, you will probably need session data especially when you are testing Login  The following are code examples for showing how to use django.test.client.RequestFactory().They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You need to use Client for this instead of RequestFactory

self.factory = Client()

Advanced testing topics | Django documentation, Sample code for using RequestFactory to do Django Unit Testing - Get and Post from django.contrib.sessions.middleware import SessionMiddleware. The API for the RequestFactory is a slightly restricted subset of the test client API: It only has access to the HTTP methods get (), post (), put (), delete (), head (), options (), and trace (). These methods accept all the same arguments except for follow.

You may need to use the SessionMiddleware to process your request, then save it to store the session. You can refer to this article. I also don't think it's a good idea to access the protected attributes of the factory directly, like this self.factory._session["zip_id"], it will just get you into more problems. Goodluck!

Sample code for using RequestFactory to do Django Unit Testing , def test_step_two_raises_flow_exchange_error(self): factory = RequestFactory() request = factory.get('/') request.session = {} with mock.patch(  Sample code for using RequestFactory to do Django Unit Testing - Get and Post - django_request_factory_test.py

django.test.RequestFactory Python Example, This page provides Python code examples for django.test.client. "test@test.​com" self.request = RequestFactory().get('/') self.request.session = {} self.​basket_id  If you're testing views directly using APIRequestFactory, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access response.content, you'll first need to render the response.

django.test.client.RequestFactory Python Example, The Django RequestFactory is a useful tool for writing unit tests against Django views. I was using it to test some code that interacts with  Testing in Django¶ Automated testing is an extremely useful bug-killing tool for the modern Web developer. You can use a collection of tests – a test suite – to solve, or avoid, a number of problems: When you’re writing new code, you can use tests to validate your code works as expected.

Adding a session to a Django request generated by RequestFactory , Member "Django-2.2.13/tests/sessions_tests/tests.py" (3 Jun 2020, 33610 Bytes) of 32 from django.test import ( 33 RequestFactory, TestCase, ignore_warnings, assertIs(self.session.accessed, False) 59 60 def test_get_empty(self): 61 self. As a convenience, Django provides a way to test whether the user’s browser accepts cookies. Call the set_test_cookie () method of request.session in a view, and call test_cookie_worked () in a subsequent view – not in the same view call.

Comments
  • @user1187968 What custom request?