Python 尝试测试在dajngo中使用request.session[key]的视图
我尝试使用Python 尝试测试在dajngo中使用request.session[key]的视图,python,django,session,testing,Python,Django,Session,Testing,我尝试使用request.session['key']值在views.py上进行测试,其中文件只有一行 def updateaccout(request): username = request.session['username'] profile = Account.objects.get(username=username) return render(request, "user/profile .html",profile ) 在test.
request.session['key']
值在views.py上进行测试,其中文件只有一行
def updateaccout(request):
username = request.session['username']
profile = Account.objects.get(username=username)
return render(request, "user/profile .html",profile )
在test.py文件中,我尝试了两个集合
def test_updateaccout(self):
self.client.login(username='john', password='johnpassword')
session = self.client.session
session['username'] = 'john'
session.save()
c = Client()
data = {'username' : 'john'}
response = c.post('/account', data,follow=True)
self.assertEqual(response.status_code,200)
ERROR: test_updateaccout (user.tests.UsersTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/ubuntu/cn331project/user/tests.py", line 57, in test_updateaccout
response = c.post('/login/account', data,follow=True)
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 741, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 405, in post
secure=secure, **extra)
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 470, in generic
return self.request(**r)
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 709, in request
self.check_exception(response)
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/test/client.py", line 571, in check_exception
raise exc_value
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/cn331project/user/views.py", line 50, in updateaccout
username = request.session['username']
File "/home/ubuntu/.venv/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 65, in __getitem__
return self._session[key]
KeyError: 'username'
我尝试设置的另一个是添加self.\u session['username']='john'
,但它说AttributeError:'UsersTestCase'对象没有属性'\u session'
我如何测试这个?或者我应该分离测试URL和表单,但仍然没有测试视图
谢谢您不能在客户端设置会话变量。会话变量存储在服务器端,客户端只存储cookie。你是说self.\u Session['username',对吗?我不知道该怎么办。所以我决定试试。不,
self.\u session
肯定不起作用,因为TestCase
没有session属性,self.\u session[key]中的self
是会话后端。