我在Django测试中使用RequestFactory
,我找不到正确的方法来访问会话变量,我在尝试时遇到以下错误
self.factory._session["zip_id"]
或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"] != ""
答案 0 :(得分:1)
您需要使用Client
代替RequestFactory
self.factory = Client()
答案 1 :(得分:0)
您可能需要使用SessionMiddleware
处理请求,然后将其保存以存储会话。您可以参考此article。我也不认为直接访问工厂的受保护属性(如self.factory._session["zip_id"]
)是个好主意,它只会使您陷入更多问题。祝你好运!
答案 2 :(得分:0)
保存会话信息以使用中间件进行请求
from django.contrib.sessions.middleware import SessionMiddleware
request = RequestFactory().get('/')
middleware = SessionMiddleware()
middleware.process_request(request)
request.session.save()