问题:我尝试设置cookie时,我的测试客户端似乎已注销。我有希望客户端访问的工作区(项目)对象。访问本身可以正常工作,但是一旦我尝试在会话中编辑Cookie,客户端就会注销。我的测试记录在下面。
代码
import time
from http.cookies import SimpleCookie
from django.contrib.auth.models import User
from django.test import Client, TestCase
from django.urls import reverse
from myproject.models import DataSource, Workspace
class TestSomeStuff(TestCase):
def setUp(self):
datasource1, _ = DataSource.objects.update_or_create(id=1, defaults=dict(source_name="Source 1"))
workspace1, _ = Workspace.objects.get_or_create(id=1, defaults=dict(project_name="Project 1",
datasource=datasource1))
self.workspace_view_url = reverse("workspace", args=[workspace1.id])
self.client = Client()
print(self.client.get(self.workspace_view_url)) # 302 - redirect to login page as expected
self.client.force_login(User.objects.get_or_create(username='testuser')[0])
print(self.client.get(self.workspace_view_url)) # 200 - as expected
time.sleep(2)
print(self.client.get(self.workspace_view_url)) # 200 - as expected
time.sleep(2)
self.client.cookies = SimpleCookie()
print(self.client.get(self.workspace_view_url)) # 302 - why?
def test_my_test(self):
pass
[C0行]清除所有cookie-包括“ sessionid”和“ csrftoken”。我将其更改为self.client.cookies = SimpleCookie()