Django 测试 - SimpleCookie 和 Session

Django Testing - SimpleCookie and Session

问题:我尝试设置 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

self.client.cookies = SimpleCookie() 擦除所有 cookie - 包括 'sessionid' 和 'csrftoken'。我改成了self.client.cookies["cookie_key"] = "cookie_value"