23

我有这样的看法:

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.

所以,在我的测试中最后一条评论的地方,我想测试一个特定的值是否在sessiondict 中,并且 key:value 配对是否正确。我该怎么做?我可以使用request.session吗?

非常感谢任何帮助。

4

1 回答 1

45

根据文档

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")
于 2012-10-29T20:16:51.807 回答