簡體   English   中英

如何在 django 測試用例中設置 cookie?

[英]How to set a cookie in a django test case?

我正在努力解決這個問題,當我正常運行我的應用程序時會話工作,但我無法弄清楚如何在我的測試用例中設置 session 中的數據。

文檔說在測試用例中,您必須保存 session 以在發出請求之前應用更改。 https://docs.djangoproject.com/en/1.2/topics/testing/#persistent-state

例如

from django.test import TestCase

class TestLogin(TestCase):

    def test_processuser(self):
        redirect = '/processuser/'
        session = self.client.session
        session["id"] = '1234'
        session.save()
        response = self.client.get(redirect)

然而,從 self.client.session 返回的 session object 只是一個普通的 Z23EEEB4347BDD26BZDDdict6B7EE?9

深入研究 Client.session 調用的代碼是這樣的:

def _session(self):
    """
    Obtains the current session variables.
    """
    if 'django.contrib.sessions' in settings.INSTALLED_APPS:
        engine = import_module(settings.SESSION_ENGINE)
        cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
        if cookie:
            return engine.SessionStore(cookie.value)
    return {}
session = property(_session)

cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)返回None所以它只返回一個字典而不是 session 存儲。

在我保存 session 之前,看起來我必須在測試客戶端中做更多的准備工作? 在這方面並沒有太多經驗,任何幫助將不勝感激。

Django 1.2.5 Python 2.6.5

干杯,

阿西姆。

編輯:這個答案現在已經過時了; 至少從 Django 1.7 開始,您可以直接在測試客戶端上設置 cookie。

例如,請參閱this answer to this question對此答案對另一個類似問題的評論

舊的過時答案如下...


確實需要設置 cookie 的人添加此功能,例如因為他們需要做 Django 身份驗證機制未涵蓋的事情...

你不能直接在TestClient對象上設置 cookies 但是如果你使用RequestFactory class 你可以做到。 所以而不是(說):

response = Client().post('/foo')

你做:

request = RequestFactory().post('/foo')
request.COOKIES['blah'] = 'hello'
response = foo_view(request)

其中foo_view是對應於 '/foo' 路徑的視圖,即您要測試的視圖。

有人。

最簡單的事情是以某人身份登錄,因此測試客戶端會為您設置 cookie。

self.client.login(username,password)

應該做。 有關更多信息,請參閱文檔

對於遇到此問題的其他人,請注意Client.logout() function 將丟棄您的 cookies。 例如:

response = self.client.post(self.url, self.data)
print response.client.cookies.items()  # Displays the cookie you just set

self.client.logout()

response = self.client.post(reverse('loginpage'), {'username': 'username', 'password': 'password'}, follow=True)
print response.client.cookies.items()  # Does not display the cookie you set before since it got destroyed by logout()

為了確保您的 cookies 在測試期間保持活動狀態,請調用您的注銷頁面而不是使用Client.logout() function,如下所示:

response = self.client.post(self.url, self.data)
print response.client.cookies.items()  # Displays the cookie you just set

self.client.get(reverse('logoutpage'))

response = self.client.post(reverse('loginpage'), {'username': 'username', 'password': 'password'}, follow=True)
print response.client.cookies.items()  # Does display the cookie you set before since it did not get destroyed by client.logout()

與最受好評的答案相反,您可以直接在測試客戶端上設置cookies

記住一切都是 object,你只需要知道在哪里/什么補丁

所以它是這樣的:

client.cookies[key] = data

client.cookies是標准庫中http.cookies.SimpleCookie的一個實例,它的行為類似於dict 因此您可以使用.update批量更新 cookies 值。 如果您想更改其他 cookie 值(如max-agepath domain等),這將很有用。

最后,如果你想設置一個signed_cookie ,你可以像這樣重用 django 的助手:

from django.core.signing import get_cookie_signer

signed_cookie_value = get_cookie_signer(salt=key).sign(data)
client.cookies[key] = signed_cookie_value

注意鹽。 它必須在兩端匹配(簽名和檢索)。 用於簽名的不同鹽值會生成不同的 cookie,當您調用response.get_signed_cookie(key)時無法檢索該 cookie

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM