在测试的Django测试存储的会话数据(Django testing stored session

2019-08-02 02:44发布

我有一个观点这样:

def ProjectInfo(request):
    if request.method == 'POST':
        form = ProjectInfoForm(request.POST)
        if form.is_valid():
            # if form is valid, iterate cleaned form data
            # and save data to session
            for k, v in form.cleaned_data.iteritems():
                request.session[k] = v
            return HttpResponseRedirect('/next/')
        else:
            ...
    else:
        ...

而在我的测试:

from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from tool.models import Module, Model
from django.contrib.sessions.models import Session

def test_project_info_form_post_submission(self):
    """
    Test if project info form can be submitted via post.
    """
    # set up our POST data
    post_data = {
        'zipcode': '90210',
        'module': self.module1.name,
        'model': self.model1.name,
        'orientation': 1,
        'tilt': 1,
        'rails_direction': 1,
    }
    ...
    self.assertEqual(response.status_code, 302)
    # test if 'zipcode' in session is equal to posted value.

因此,在最后的评论是在我的测试,我想测试一个特定的值在session字典,而且键:值对是正确的。 我怎么去呢? 我可以使用request.session

任何帮助非常赞赏。

Answer 1:

根据该文档 :

from django.test import TestCase

class SimpleTest(TestCase):
    def test_details(self):
        # Issue a GET request.
        self.client.get('/customer/details/')
        session = self.client.session
        self.assertEqual(session["somekey"], "test")


文章来源: Django testing stored session data in tests