Problem: My testing client appears to log out once i attempt to set a cookie. I have workspace (project) object that i want my client to access. The access itself works fine, but as soon as i attempt to edit cookies in my session, the client gets logged out. My test is documented below.
Code
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
The line self.client.cookies = SimpleCookie()
wipes all cookies - including the 'sessionid' and 'csrftoken'. I changed it to self.client.cookies["cookie_key"] = "cookie_value"