Django testing stored session data in tests

夙愿已清 提交于 2019-12-03 16:06:46

问题


I have a view as such:

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:
        ...

And in my tests:

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.

So, where the last comment is in my test, I want to test if a specific value is in the session dict and that the key:value pairing is correct. How do I go about this? Can I use request.session?

Any help much appreciated.


回答1:


According to the docs:

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")


来源:https://stackoverflow.com/questions/13128443/django-testing-stored-session-data-in-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!