From 756a70b48de73daccf2a4581996830900239a4b7 Mon Sep 17 00:00:00 2001 From: Preston Timmons Date: Tue, 2 Apr 2013 23:37:40 +0000 Subject: Modified formtools to work with unittest2 discovery. --- django/contrib/formtools/tests/__init__.py | 188 +-------------- django/contrib/formtools/tests/tests.py | 187 +++++++++++++++ django/contrib/formtools/tests/wizard/__init__.py | 8 +- .../formtools/tests/wizard/cookiestorage.py | 49 ---- django/contrib/formtools/tests/wizard/forms.py | 251 --------------------- .../contrib/formtools/tests/wizard/loadstorage.py | 18 -- .../tests/wizard/namedwizardtests/tests.py | 2 +- .../formtools/tests/wizard/sessionstorage.py | 11 - .../formtools/tests/wizard/test_cookiestorage.py | 49 ++++ .../contrib/formtools/tests/wizard/test_forms.py | 251 +++++++++++++++++++++ .../formtools/tests/wizard/test_loadstorage.py | 18 ++ .../formtools/tests/wizard/test_sessionstorage.py | 11 + 12 files changed, 522 insertions(+), 521 deletions(-) create mode 100644 django/contrib/formtools/tests/tests.py delete mode 100644 django/contrib/formtools/tests/wizard/cookiestorage.py delete mode 100644 django/contrib/formtools/tests/wizard/forms.py delete mode 100644 django/contrib/formtools/tests/wizard/loadstorage.py delete mode 100644 django/contrib/formtools/tests/wizard/sessionstorage.py create mode 100644 django/contrib/formtools/tests/wizard/test_cookiestorage.py create mode 100644 django/contrib/formtools/tests/wizard/test_forms.py create mode 100644 django/contrib/formtools/tests/wizard/test_loadstorage.py create mode 100644 django/contrib/formtools/tests/wizard/test_sessionstorage.py diff --git a/django/contrib/formtools/tests/__init__.py b/django/contrib/formtools/tests/__init__.py index 8caefd0e67..2bbeea8c5a 100644 --- a/django/contrib/formtools/tests/__init__.py +++ b/django/contrib/formtools/tests/__init__.py @@ -1,188 +1,2 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - -import datetime -import os -import pickle -import re -import warnings - -from django import http -from django.conf import settings -from django.contrib.formtools import preview, utils -from django.test import TestCase -from django.test.html import parse_html -from django.test.utils import override_settings -from django.utils._os import upath -from django.utils import unittest - +from django.contrib.formtools.tests.tests import * from django.contrib.formtools.tests.wizard import * -from django.contrib.formtools.tests.forms import * - -success_string = "Done was called!" -success_string_encoded = success_string.encode() - -class TestFormPreview(preview.FormPreview): - def get_context(self, request, form): - context = super(TestFormPreview, self).get_context(request, form) - context.update({'custom_context': True}) - return context - - def get_initial(self, request): - return {'field1': 'Works!'} - - def done(self, request, cleaned_data): - return http.HttpResponse(success_string) - -@override_settings( - TEMPLATE_DIRS=( - os.path.join(os.path.dirname(upath(__file__)), 'templates'), - ), -) -class PreviewTests(TestCase): - urls = 'django.contrib.formtools.tests.urls' - - def setUp(self): - super(PreviewTests, self).setUp() - # Create a FormPreview instance to share between tests - self.preview = preview.FormPreview(TestForm) - input_template = '' - self.input = input_template % (self.preview.unused_name('stage'), "%d") - self.test_data = {'field1': 'foo', 'field1_': 'asdf'} - - def test_unused_name(self): - """ - Verifies name mangling to get uniue field name. - """ - self.assertEqual(self.preview.unused_name('field1'), 'field1__') - - def test_form_get(self): - """ - Test contrib.formtools.preview form retrieval. - - Use the client library to see if we can sucessfully retrieve - the form (mostly testing the setup ROOT_URLCONF - process). Verify that an additional hidden input field - is created to manage the stage. - - """ - response = self.client.get('/preview/') - stage = self.input % 1 - self.assertContains(response, stage, 1) - self.assertEqual(response.context['custom_context'], True) - self.assertEqual(response.context['form'].initial, {'field1': 'Works!'}) - - def test_form_preview(self): - """ - Test contrib.formtools.preview form preview rendering. - - Use the client library to POST to the form to see if a preview - is returned. If we do get a form back check that the hidden - value is correctly managing the state of the form. - - """ - # Pass strings for form submittal and add stage variable to - # show we previously saw first stage of the form. - self.test_data.update({'stage': 1, 'date1': datetime.date(2006, 10, 25)}) - response = self.client.post('/preview/', self.test_data) - # Check to confirm stage is set to 2 in output form. - stage = self.input % 2 - self.assertContains(response, stage, 1) - - def test_form_submit(self): - """ - Test contrib.formtools.preview form submittal. - - Use the client library to POST to the form with stage set to 3 - to see if our forms done() method is called. Check first - without the security hash, verify failure, retry with security - hash and verify sucess. - - """ - # Pass strings for form submittal and add stage variable to - # show we previously saw first stage of the form. - self.test_data.update({'stage': 2, 'date1': datetime.date(2006, 10, 25)}) - response = self.client.post('/preview/', self.test_data) - self.assertNotEqual(response.content, success_string_encoded) - hash = self.preview.security_hash(None, TestForm(self.test_data)) - self.test_data.update({'hash': hash}) - response = self.client.post('/preview/', self.test_data) - self.assertEqual(response.content, success_string_encoded) - - def test_bool_submit(self): - """ - Test contrib.formtools.preview form submittal when form contains: - BooleanField(required=False) - - Ticket: #6209 - When an unchecked BooleanField is previewed, the preview - form's hash would be computed with no value for ``bool1``. However, when - the preview form is rendered, the unchecked hidden BooleanField would be - rendered with the string value 'False'. So when the preview form is - resubmitted, the hash would be computed with the value 'False' for - ``bool1``. We need to make sure the hashes are the same in both cases. - - """ - self.test_data.update({'stage':2}) - hash = self.preview.security_hash(None, TestForm(self.test_data)) - self.test_data.update({'hash': hash, 'bool1': 'False'}) - with warnings.catch_warnings(record=True): - response = self.client.post('/preview/', self.test_data) - self.assertEqual(response.content, success_string_encoded) - - def test_form_submit_good_hash(self): - """ - Test contrib.formtools.preview form submittal, using a correct - hash - """ - # Pass strings for form submittal and add stage variable to - # show we previously saw first stage of the form. - self.test_data.update({'stage':2}) - response = self.client.post('/preview/', self.test_data) - self.assertNotEqual(response.content, success_string_encoded) - hash = utils.form_hmac(TestForm(self.test_data)) - self.test_data.update({'hash': hash}) - response = self.client.post('/preview/', self.test_data) - self.assertEqual(response.content, success_string_encoded) - - - def test_form_submit_bad_hash(self): - """ - Test contrib.formtools.preview form submittal does not proceed - if the hash is incorrect. - """ - # Pass strings for form submittal and add stage variable to - # show we previously saw first stage of the form. - self.test_data.update({'stage':2}) - response = self.client.post('/preview/', self.test_data) - self.assertEqual(response.status_code, 200) - self.assertNotEqual(response.content, success_string_encoded) - hash = utils.form_hmac(TestForm(self.test_data)) + "bad" - self.test_data.update({'hash': hash}) - response = self.client.post('/previewpreview/', self.test_data) - self.assertNotEqual(response.content, success_string_encoded) - - -class FormHmacTests(unittest.TestCase): - - def test_textfield_hash(self): - """ - Regression test for #10034: the hash generation function should ignore - leading/trailing whitespace so as to be friendly to broken browsers that - submit it (usually in textareas). - """ - f1 = HashTestForm({'name': 'joe', 'bio': 'Speaking español.'}) - f2 = HashTestForm({'name': ' joe', 'bio': 'Speaking español. '}) - hash1 = utils.form_hmac(f1) - hash2 = utils.form_hmac(f2) - self.assertEqual(hash1, hash2) - - def test_empty_permitted(self): - """ - Regression test for #10643: the security hash should allow forms with - empty_permitted = True, or forms where data has not changed. - """ - f1 = HashTestBlankForm({}) - f2 = HashTestForm({}, empty_permitted=True) - hash1 = utils.form_hmac(f1) - hash2 = utils.form_hmac(f2) - self.assertEqual(hash1, hash2) diff --git a/django/contrib/formtools/tests/tests.py b/django/contrib/formtools/tests/tests.py new file mode 100644 index 0000000000..56ef901127 --- /dev/null +++ b/django/contrib/formtools/tests/tests.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +import datetime +import os +import pickle +import re +import warnings + +from django import http +from django.conf import settings +from django.contrib.formtools import preview, utils +from django.test import TestCase +from django.test.html import parse_html +from django.test.utils import override_settings +from django.utils._os import upath +from django.utils import unittest + +from django.contrib.formtools.tests.forms import * + +success_string = "Done was called!" +success_string_encoded = success_string.encode() + +class TestFormPreview(preview.FormPreview): + def get_context(self, request, form): + context = super(TestFormPreview, self).get_context(request, form) + context.update({'custom_context': True}) + return context + + def get_initial(self, request): + return {'field1': 'Works!'} + + def done(self, request, cleaned_data): + return http.HttpResponse(success_string) + +@override_settings( + TEMPLATE_DIRS=( + os.path.join(os.path.dirname(upath(__file__)), 'templates'), + ), +) +class PreviewTests(TestCase): + urls = 'django.contrib.formtools.tests.urls' + + def setUp(self): + super(PreviewTests, self).setUp() + # Create a FormPreview instance to share between tests + self.preview = preview.FormPreview(TestForm) + input_template = '' + self.input = input_template % (self.preview.unused_name('stage'), "%d") + self.test_data = {'field1': 'foo', 'field1_': 'asdf'} + + def test_unused_name(self): + """ + Verifies name mangling to get uniue field name. + """ + self.assertEqual(self.preview.unused_name('field1'), 'field1__') + + def test_form_get(self): + """ + Test contrib.formtools.preview form retrieval. + + Use the client library to see if we can sucessfully retrieve + the form (mostly testing the setup ROOT_URLCONF + process). Verify that an additional hidden input field + is created to manage the stage. + + """ + response = self.client.get('/preview/') + stage = self.input % 1 + self.assertContains(response, stage, 1) + self.assertEqual(response.context['custom_context'], True) + self.assertEqual(response.context['form'].initial, {'field1': 'Works!'}) + + def test_form_preview(self): + """ + Test contrib.formtools.preview form preview rendering. + + Use the client library to POST to the form to see if a preview + is returned. If we do get a form back check that the hidden + value is correctly managing the state of the form. + + """ + # Pass strings for form submittal and add stage variable to + # show we previously saw first stage of the form. + self.test_data.update({'stage': 1, 'date1': datetime.date(2006, 10, 25)}) + response = self.client.post('/preview/', self.test_data) + # Check to confirm stage is set to 2 in output form. + stage = self.input % 2 + self.assertContains(response, stage, 1) + + def test_form_submit(self): + """ + Test contrib.formtools.preview form submittal. + + Use the client library to POST to the form with stage set to 3 + to see if our forms done() method is called. Check first + without the security hash, verify failure, retry with security + hash and verify sucess. + + """ + # Pass strings for form submittal and add stage variable to + # show we previously saw first stage of the form. + self.test_data.update({'stage': 2, 'date1': datetime.date(2006, 10, 25)}) + response = self.client.post('/preview/', self.test_data) + self.assertNotEqual(response.content, success_string_encoded) + hash = self.preview.security_hash(None, TestForm(self.test_data)) + self.test_data.update({'hash': hash}) + response = self.client.post('/preview/', self.test_data) + self.assertEqual(response.content, success_string_encoded) + + def test_bool_submit(self): + """ + Test contrib.formtools.preview form submittal when form contains: + BooleanField(required=False) + + Ticket: #6209 - When an unchecked BooleanField is previewed, the preview + form's hash would be computed with no value for ``bool1``. However, when + the preview form is rendered, the unchecked hidden BooleanField would be + rendered with the string value 'False'. So when the preview form is + resubmitted, the hash would be computed with the value 'False' for + ``bool1``. We need to make sure the hashes are the same in both cases. + + """ + self.test_data.update({'stage':2}) + hash = self.preview.security_hash(None, TestForm(self.test_data)) + self.test_data.update({'hash': hash, 'bool1': 'False'}) + with warnings.catch_warnings(record=True): + response = self.client.post('/preview/', self.test_data) + self.assertEqual(response.content, success_string_encoded) + + def test_form_submit_good_hash(self): + """ + Test contrib.formtools.preview form submittal, using a correct + hash + """ + # Pass strings for form submittal and add stage variable to + # show we previously saw first stage of the form. + self.test_data.update({'stage':2}) + response = self.client.post('/preview/', self.test_data) + self.assertNotEqual(response.content, success_string_encoded) + hash = utils.form_hmac(TestForm(self.test_data)) + self.test_data.update({'hash': hash}) + response = self.client.post('/preview/', self.test_data) + self.assertEqual(response.content, success_string_encoded) + + + def test_form_submit_bad_hash(self): + """ + Test contrib.formtools.preview form submittal does not proceed + if the hash is incorrect. + """ + # Pass strings for form submittal and add stage variable to + # show we previously saw first stage of the form. + self.test_data.update({'stage':2}) + response = self.client.post('/preview/', self.test_data) + self.assertEqual(response.status_code, 200) + self.assertNotEqual(response.content, success_string_encoded) + hash = utils.form_hmac(TestForm(self.test_data)) + "bad" + self.test_data.update({'hash': hash}) + response = self.client.post('/previewpreview/', self.test_data) + self.assertNotEqual(response.content, success_string_encoded) + + +class FormHmacTests(unittest.TestCase): + + def test_textfield_hash(self): + """ + Regression test for #10034: the hash generation function should ignore + leading/trailing whitespace so as to be friendly to broken browsers that + submit it (usually in textareas). + """ + f1 = HashTestForm({'name': 'joe', 'bio': 'Speaking español.'}) + f2 = HashTestForm({'name': ' joe', 'bio': 'Speaking español. '}) + hash1 = utils.form_hmac(f1) + hash2 = utils.form_hmac(f2) + self.assertEqual(hash1, hash2) + + def test_empty_permitted(self): + """ + Regression test for #10643: the security hash should allow forms with + empty_permitted = True, or forms where data has not changed. + """ + f1 = HashTestBlankForm({}) + f2 = HashTestForm({}, empty_permitted=True) + hash1 = utils.form_hmac(f1) + hash2 = utils.form_hmac(f2) + self.assertEqual(hash1, hash2) diff --git a/django/contrib/formtools/tests/wizard/__init__.py b/django/contrib/formtools/tests/wizard/__init__.py index a2a9692ac6..81de44e655 100644 --- a/django/contrib/formtools/tests/wizard/__init__.py +++ b/django/contrib/formtools/tests/wizard/__init__.py @@ -1,6 +1,6 @@ -from django.contrib.formtools.tests.wizard.cookiestorage import TestCookieStorage -from django.contrib.formtools.tests.wizard.forms import FormTests, SessionFormTests, CookieFormTests -from django.contrib.formtools.tests.wizard.loadstorage import TestLoadStorage +from django.contrib.formtools.tests.wizard.test_cookiestorage import TestCookieStorage +from django.contrib.formtools.tests.wizard.test_forms import FormTests, SessionFormTests, CookieFormTests +from django.contrib.formtools.tests.wizard.test_loadstorage import TestLoadStorage from django.contrib.formtools.tests.wizard.namedwizardtests.tests import ( NamedSessionWizardTests, NamedCookieWizardTests, @@ -9,7 +9,7 @@ from django.contrib.formtools.tests.wizard.namedwizardtests.tests import ( NamedSessionFormTests, NamedCookieFormTests, ) -from django.contrib.formtools.tests.wizard.sessionstorage import TestSessionStorage +from django.contrib.formtools.tests.wizard.test_sessionstorage import TestSessionStorage from django.contrib.formtools.tests.wizard.wizardtests.tests import ( SessionWizardTests, CookieWizardTests, diff --git a/django/contrib/formtools/tests/wizard/cookiestorage.py b/django/contrib/formtools/tests/wizard/cookiestorage.py deleted file mode 100644 index 060e8260b5..0000000000 --- a/django/contrib/formtools/tests/wizard/cookiestorage.py +++ /dev/null @@ -1,49 +0,0 @@ -import json - -from django.test import TestCase -from django.core import signing -from django.core.exceptions import SuspiciousOperation -from django.http import HttpResponse - -from django.contrib.auth.tests.utils import skipIfCustomUser -from django.contrib.formtools.wizard.storage.cookie import CookieStorage -from django.contrib.formtools.tests.wizard.storage import get_request, TestStorage - - -@skipIfCustomUser -class TestCookieStorage(TestStorage, TestCase): - def get_storage(self): - return CookieStorage - - def test_manipulated_cookie(self): - request = get_request() - storage = self.get_storage()('wizard1', request, None) - - cookie_signer = signing.get_cookie_signer(storage.prefix) - - storage.request.COOKIES[storage.prefix] = cookie_signer.sign( - storage.encoder.encode({'key1': 'value1'})) - - self.assertEqual(storage.load_data(), {'key1': 'value1'}) - - storage.request.COOKIES[storage.prefix] = 'i_am_manipulated' - self.assertRaises(SuspiciousOperation, storage.load_data) - - def test_reset_cookie(self): - request = get_request() - storage = self.get_storage()('wizard1', request, None) - - storage.data = {'key1': 'value1'} - - response = HttpResponse() - storage.update_response(response) - - cookie_signer = signing.get_cookie_signer(storage.prefix) - signed_cookie_data = cookie_signer.sign(storage.encoder.encode(storage.data)) - self.assertEqual(response.cookies[storage.prefix].value, signed_cookie_data) - - storage.init_data() - storage.update_response(response) - unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value) - self.assertJSONEqual(unsigned_cookie_data, - {"step_files": {}, "step": None, "extra_data": {}, "step_data": {}}) diff --git a/django/contrib/formtools/tests/wizard/forms.py b/django/contrib/formtools/tests/wizard/forms.py deleted file mode 100644 index 14c6e6a685..0000000000 --- a/django/contrib/formtools/tests/wizard/forms.py +++ /dev/null @@ -1,251 +0,0 @@ -from __future__ import unicode_literals - -from django import forms, http -from django.conf import settings -from django.db import models -from django.test import TestCase -from django.template.response import TemplateResponse -from django.utils.importlib import import_module - -from django.contrib.auth.models import User - -from django.contrib.formtools.wizard.views import (WizardView, - SessionWizardView, - CookieWizardView) - - -class DummyRequest(http.HttpRequest): - def __init__(self, POST=None): - super(DummyRequest, self).__init__() - self.method = POST and "POST" or "GET" - if POST is not None: - self.POST.update(POST) - self.session = {} - self._dont_enforce_csrf_checks = True - - -def get_request(*args, **kwargs): - request = DummyRequest(*args, **kwargs) - engine = import_module(settings.SESSION_ENGINE) - request.session = engine.SessionStore(None) - return request - - -class Step1(forms.Form): - name = forms.CharField() - - -class Step2(forms.Form): - name = forms.CharField() - - -class Step3(forms.Form): - data = forms.CharField() - - -class CustomKwargsStep1(Step1): - - def __init__(self, test=None, *args, **kwargs): - self.test = test - return super(CustomKwargsStep1, self).__init__(*args, **kwargs) - - -class TestModel(models.Model): - name = models.CharField(max_length=100) - - class Meta: - app_label = 'formtools' - - -class TestModelForm(forms.ModelForm): - class Meta: - model = TestModel - - -TestModelFormSet = forms.models.modelformset_factory(TestModel, form=TestModelForm, extra=2) - - -class TestWizard(WizardView): - storage_name = 'django.contrib.formtools.wizard.storage.session.SessionStorage' - - def dispatch(self, request, *args, **kwargs): - response = super(TestWizard, self).dispatch(request, *args, **kwargs) - return response, self - - def get_form_kwargs(self, step, *args, **kwargs): - kwargs = super(TestWizard, self).get_form_kwargs(step, *args, **kwargs) - if step == 'kwargs_test': - kwargs['test'] = True - return kwargs - -class TestWizardWithInitAttrs(TestWizard): - form_list = [Step1, Step2] - condition_dict = {'step2': True} - initial_dict = {'start': {'name': 'value1'}} - instance_dict = {'start': User()} - -class FormTests(TestCase): - def test_form_init(self): - testform = TestWizard.get_initkwargs([Step1, Step2]) - self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) - - testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)]) - self.assertEqual( - testform['form_list'], {'start': Step1, 'step2': Step2}) - - testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)]) - self.assertEqual( - testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3}) - - testform = TestWizardWithInitAttrs.get_initkwargs() - self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) - - def test_first_step(self): - request = get_request() - - testform = TestWizard.as_view([Step1, Step2]) - response, instance = testform(request) - self.assertEqual(instance.steps.current, '0') - - testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) - response, instance = testform(request) - - self.assertEqual(instance.steps.current, 'start') - - def test_persistence(self): - testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) - request = get_request({'test_wizard-current_step': 'start', - 'name': 'data1'}) - response, instance = testform(request) - self.assertEqual(instance.steps.current, 'start') - - instance.storage.current_step = 'step2' - - testform2 = TestWizard.as_view([('start', Step1), ('step2', Step2)]) - request.POST = {'test_wizard-current_step': 'step2'} - response, instance = testform2(request) - self.assertEqual(instance.steps.current, 'step2') - - def test_form_condition(self): - request = get_request() - - testform = TestWizard.as_view( - [('start', Step1), ('step2', Step2), ('step3', Step3)], - condition_dict={'step2': True}) - response, instance = testform(request) - self.assertEqual(instance.get_next_step(), 'step2') - - testform = TestWizard.as_view( - [('start', Step1), ('step2', Step2), ('step3', Step3)], - condition_dict={'step2': False}) - response, instance = testform(request) - self.assertEqual(instance.get_next_step(), 'step3') - - testform = TestWizardWithInitAttrs.as_view( - [('start', Step1), ('step2', Step2), ('step3', Step3)]) - response, instance = testform(request) - self.assertEqual(instance.get_next_step(), 'step2') - - def test_form_kwargs(self): - request = get_request() - - testform = TestWizard.as_view([('start', Step1), - ('kwargs_test', CustomKwargsStep1)]) - response, instance = testform(request) - - self.assertEqual(instance.get_form_kwargs('start'), {}) - self.assertEqual(instance.get_form_kwargs('kwargs_test'), {'test': True}) - self.assertEqual(instance.get_form('kwargs_test').test, True) - - def test_form_prefix(self): - request = get_request() - - testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) - response, instance = testform(request) - - self.assertEqual(instance.get_form_prefix(), 'start') - self.assertEqual(instance.get_form_prefix('another'), 'another') - - def test_form_initial(self): - request = get_request() - - testform = TestWizard.as_view([('start', Step1), ('step2', Step2)], - initial_dict={'start': {'name': 'value1'}}) - response, instance = testform(request) - - self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'}) - self.assertEqual(instance.get_form_initial('step2'), {}) - - testform = TestWizardWithInitAttrs.as_view( - [('start', Step1), ('step2', Step2)]) - response, instance = testform(request) - - self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'}) - self.assertEqual(instance.get_form_initial('step2'), {}) - - def test_form_instance(self): - request = get_request() - the_instance = TestModel() - testform = TestWizard.as_view([('start', TestModelForm), ('step2', Step2)], - instance_dict={'start': the_instance}) - response, instance = testform(request) - - self.assertEqual( - instance.get_form_instance('start'), - the_instance) - self.assertEqual( - instance.get_form_instance('non_exist_instance'), - None) - - testform = TestWizardWithInitAttrs.as_view( - [('start', TestModelForm), ('step2', Step2)]) - response, instance = testform(request) - - self.assertEqual( - instance.get_form_instance('start'), - TestWizardWithInitAttrs.instance_dict['start']) - - def test_formset_instance(self): - request = get_request() - the_instance1, created = TestModel.objects.get_or_create( - name='test object 1') - the_instance2, created = TestModel.objects.get_or_create( - name='test object 2') - testform = TestWizard.as_view([('start', TestModelFormSet), ('step2', Step2)], - instance_dict={'start': TestModel.objects.filter(name='test object 1')}) - response, instance = testform(request) - - self.assertEqual(list(instance.get_form_instance('start')), [the_instance1]) - self.assertEqual(instance.get_form_instance('non_exist_instance'), None) - - self.assertEqual(instance.get_form().initial_form_count(), 1) - - def test_done(self): - request = get_request() - - testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) - response, instance = testform(request) - - self.assertRaises(NotImplementedError, instance.done, None) - - def test_revalidation(self): - request = get_request() - - testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) - response, instance = testform(request) - instance.render_done(None) - self.assertEqual(instance.storage.current_step, 'start') - - -class SessionFormTests(TestCase): - def test_init(self): - request = get_request() - testform = SessionWizardView.as_view([('start', Step1)]) - self.assertTrue(isinstance(testform(request), TemplateResponse)) - - -class CookieFormTests(TestCase): - def test_init(self): - request = get_request() - testform = CookieWizardView.as_view([('start', Step1)]) - self.assertTrue(isinstance(testform(request), TemplateResponse)) diff --git a/django/contrib/formtools/tests/wizard/loadstorage.py b/django/contrib/formtools/tests/wizard/loadstorage.py deleted file mode 100644 index bb0b06eecf..0000000000 --- a/django/contrib/formtools/tests/wizard/loadstorage.py +++ /dev/null @@ -1,18 +0,0 @@ -from django.test import TestCase - -from django.contrib.formtools.wizard.storage import get_storage, MissingStorage -from django.contrib.formtools.wizard.storage.base import BaseStorage - - -class TestLoadStorage(TestCase): - def test_load_storage(self): - self.assertEqual( - type(get_storage('django.contrib.formtools.wizard.storage.base.BaseStorage', 'wizard1')), - BaseStorage) - - def test_missing_storage(self): - self.assertRaises(MissingStorage, get_storage, - 'django.contrib.formtools.wizard.storage.idontexist.IDontExistStorage', 'wizard1') - self.assertRaises(MissingStorage, get_storage, - 'django.contrib.formtools.wizard.storage.base.IDontExistStorage', 'wizard1') - diff --git a/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py b/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py index 824eb7e37e..b6125db5b9 100644 --- a/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py +++ b/django/contrib/formtools/tests/wizard/namedwizardtests/tests.py @@ -9,7 +9,7 @@ from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.formtools.wizard.views import (NamedUrlSessionWizardView, NamedUrlCookieWizardView) -from django.contrib.formtools.tests.wizard.forms import get_request, Step1, Step2 +from django.contrib.formtools.tests.wizard.test_forms import get_request, Step1, Step2 class NamedWizardTests(object): diff --git a/django/contrib/formtools/tests/wizard/sessionstorage.py b/django/contrib/formtools/tests/wizard/sessionstorage.py deleted file mode 100644 index 0bd9fd8ecd..0000000000 --- a/django/contrib/formtools/tests/wizard/sessionstorage.py +++ /dev/null @@ -1,11 +0,0 @@ -from django.test import TestCase - -from django.contrib.auth.tests.utils import skipIfCustomUser -from django.contrib.formtools.tests.wizard.storage import TestStorage -from django.contrib.formtools.wizard.storage.session import SessionStorage - - -@skipIfCustomUser -class TestSessionStorage(TestStorage, TestCase): - def get_storage(self): - return SessionStorage diff --git a/django/contrib/formtools/tests/wizard/test_cookiestorage.py b/django/contrib/formtools/tests/wizard/test_cookiestorage.py new file mode 100644 index 0000000000..060e8260b5 --- /dev/null +++ b/django/contrib/formtools/tests/wizard/test_cookiestorage.py @@ -0,0 +1,49 @@ +import json + +from django.test import TestCase +from django.core import signing +from django.core.exceptions import SuspiciousOperation +from django.http import HttpResponse + +from django.contrib.auth.tests.utils import skipIfCustomUser +from django.contrib.formtools.wizard.storage.cookie import CookieStorage +from django.contrib.formtools.tests.wizard.storage import get_request, TestStorage + + +@skipIfCustomUser +class TestCookieStorage(TestStorage, TestCase): + def get_storage(self): + return CookieStorage + + def test_manipulated_cookie(self): + request = get_request() + storage = self.get_storage()('wizard1', request, None) + + cookie_signer = signing.get_cookie_signer(storage.prefix) + + storage.request.COOKIES[storage.prefix] = cookie_signer.sign( + storage.encoder.encode({'key1': 'value1'})) + + self.assertEqual(storage.load_data(), {'key1': 'value1'}) + + storage.request.COOKIES[storage.prefix] = 'i_am_manipulated' + self.assertRaises(SuspiciousOperation, storage.load_data) + + def test_reset_cookie(self): + request = get_request() + storage = self.get_storage()('wizard1', request, None) + + storage.data = {'key1': 'value1'} + + response = HttpResponse() + storage.update_response(response) + + cookie_signer = signing.get_cookie_signer(storage.prefix) + signed_cookie_data = cookie_signer.sign(storage.encoder.encode(storage.data)) + self.assertEqual(response.cookies[storage.prefix].value, signed_cookie_data) + + storage.init_data() + storage.update_response(response) + unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value) + self.assertJSONEqual(unsigned_cookie_data, + {"step_files": {}, "step": None, "extra_data": {}, "step_data": {}}) diff --git a/django/contrib/formtools/tests/wizard/test_forms.py b/django/contrib/formtools/tests/wizard/test_forms.py new file mode 100644 index 0000000000..14c6e6a685 --- /dev/null +++ b/django/contrib/formtools/tests/wizard/test_forms.py @@ -0,0 +1,251 @@ +from __future__ import unicode_literals + +from django import forms, http +from django.conf import settings +from django.db import models +from django.test import TestCase +from django.template.response import TemplateResponse +from django.utils.importlib import import_module + +from django.contrib.auth.models import User + +from django.contrib.formtools.wizard.views import (WizardView, + SessionWizardView, + CookieWizardView) + + +class DummyRequest(http.HttpRequest): + def __init__(self, POST=None): + super(DummyRequest, self).__init__() + self.method = POST and "POST" or "GET" + if POST is not None: + self.POST.update(POST) + self.session = {} + self._dont_enforce_csrf_checks = True + + +def get_request(*args, **kwargs): + request = DummyRequest(*args, **kwargs) + engine = import_module(settings.SESSION_ENGINE) + request.session = engine.SessionStore(None) + return request + + +class Step1(forms.Form): + name = forms.CharField() + + +class Step2(forms.Form): + name = forms.CharField() + + +class Step3(forms.Form): + data = forms.CharField() + + +class CustomKwargsStep1(Step1): + + def __init__(self, test=None, *args, **kwargs): + self.test = test + return super(CustomKwargsStep1, self).__init__(*args, **kwargs) + + +class TestModel(models.Model): + name = models.CharField(max_length=100) + + class Meta: + app_label = 'formtools' + + +class TestModelForm(forms.ModelForm): + class Meta: + model = TestModel + + +TestModelFormSet = forms.models.modelformset_factory(TestModel, form=TestModelForm, extra=2) + + +class TestWizard(WizardView): + storage_name = 'django.contrib.formtools.wizard.storage.session.SessionStorage' + + def dispatch(self, request, *args, **kwargs): + response = super(TestWizard, self).dispatch(request, *args, **kwargs) + return response, self + + def get_form_kwargs(self, step, *args, **kwargs): + kwargs = super(TestWizard, self).get_form_kwargs(step, *args, **kwargs) + if step == 'kwargs_test': + kwargs['test'] = True + return kwargs + +class TestWizardWithInitAttrs(TestWizard): + form_list = [Step1, Step2] + condition_dict = {'step2': True} + initial_dict = {'start': {'name': 'value1'}} + instance_dict = {'start': User()} + +class FormTests(TestCase): + def test_form_init(self): + testform = TestWizard.get_initkwargs([Step1, Step2]) + self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) + + testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)]) + self.assertEqual( + testform['form_list'], {'start': Step1, 'step2': Step2}) + + testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)]) + self.assertEqual( + testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3}) + + testform = TestWizardWithInitAttrs.get_initkwargs() + self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) + + def test_first_step(self): + request = get_request() + + testform = TestWizard.as_view([Step1, Step2]) + response, instance = testform(request) + self.assertEqual(instance.steps.current, '0') + + testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) + response, instance = testform(request) + + self.assertEqual(instance.steps.current, 'start') + + def test_persistence(self): + testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) + request = get_request({'test_wizard-current_step': 'start', + 'name': 'data1'}) + response, instance = testform(request) + self.assertEqual(instance.steps.current, 'start') + + instance.storage.current_step = 'step2' + + testform2 = TestWizard.as_view([('start', Step1), ('step2', Step2)]) + request.POST = {'test_wizard-current_step': 'step2'} + response, instance = testform2(request) + self.assertEqual(instance.steps.current, 'step2') + + def test_form_condition(self): + request = get_request() + + testform = TestWizard.as_view( + [('start', Step1), ('step2', Step2), ('step3', Step3)], + condition_dict={'step2': True}) + response, instance = testform(request) + self.assertEqual(instance.get_next_step(), 'step2') + + testform = TestWizard.as_view( + [('start', Step1), ('step2', Step2), ('step3', Step3)], + condition_dict={'step2': False}) + response, instance = testform(request) + self.assertEqual(instance.get_next_step(), 'step3') + + testform = TestWizardWithInitAttrs.as_view( + [('start', Step1), ('step2', Step2), ('step3', Step3)]) + response, instance = testform(request) + self.assertEqual(instance.get_next_step(), 'step2') + + def test_form_kwargs(self): + request = get_request() + + testform = TestWizard.as_view([('start', Step1), + ('kwargs_test', CustomKwargsStep1)]) + response, instance = testform(request) + + self.assertEqual(instance.get_form_kwargs('start'), {}) + self.assertEqual(instance.get_form_kwargs('kwargs_test'), {'test': True}) + self.assertEqual(instance.get_form('kwargs_test').test, True) + + def test_form_prefix(self): + request = get_request() + + testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) + response, instance = testform(request) + + self.assertEqual(instance.get_form_prefix(), 'start') + self.assertEqual(instance.get_form_prefix('another'), 'another') + + def test_form_initial(self): + request = get_request() + + testform = TestWizard.as_view([('start', Step1), ('step2', Step2)], + initial_dict={'start': {'name': 'value1'}}) + response, instance = testform(request) + + self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'}) + self.assertEqual(instance.get_form_initial('step2'), {}) + + testform = TestWizardWithInitAttrs.as_view( + [('start', Step1), ('step2', Step2)]) + response, instance = testform(request) + + self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'}) + self.assertEqual(instance.get_form_initial('step2'), {}) + + def test_form_instance(self): + request = get_request() + the_instance = TestModel() + testform = TestWizard.as_view([('start', TestModelForm), ('step2', Step2)], + instance_dict={'start': the_instance}) + response, instance = testform(request) + + self.assertEqual( + instance.get_form_instance('start'), + the_instance) + self.assertEqual( + instance.get_form_instance('non_exist_instance'), + None) + + testform = TestWizardWithInitAttrs.as_view( + [('start', TestModelForm), ('step2', Step2)]) + response, instance = testform(request) + + self.assertEqual( + instance.get_form_instance('start'), + TestWizardWithInitAttrs.instance_dict['start']) + + def test_formset_instance(self): + request = get_request() + the_instance1, created = TestModel.objects.get_or_create( + name='test object 1') + the_instance2, created = TestModel.objects.get_or_create( + name='test object 2') + testform = TestWizard.as_view([('start', TestModelFormSet), ('step2', Step2)], + instance_dict={'start': TestModel.objects.filter(name='test object 1')}) + response, instance = testform(request) + + self.assertEqual(list(instance.get_form_instance('start')), [the_instance1]) + self.assertEqual(instance.get_form_instance('non_exist_instance'), None) + + self.assertEqual(instance.get_form().initial_form_count(), 1) + + def test_done(self): + request = get_request() + + testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) + response, instance = testform(request) + + self.assertRaises(NotImplementedError, instance.done, None) + + def test_revalidation(self): + request = get_request() + + testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) + response, instance = testform(request) + instance.render_done(None) + self.assertEqual(instance.storage.current_step, 'start') + + +class SessionFormTests(TestCase): + def test_init(self): + request = get_request() + testform = SessionWizardView.as_view([('start', Step1)]) + self.assertTrue(isinstance(testform(request), TemplateResponse)) + + +class CookieFormTests(TestCase): + def test_init(self): + request = get_request() + testform = CookieWizardView.as_view([('start', Step1)]) + self.assertTrue(isinstance(testform(request), TemplateResponse)) diff --git a/django/contrib/formtools/tests/wizard/test_loadstorage.py b/django/contrib/formtools/tests/wizard/test_loadstorage.py new file mode 100644 index 0000000000..bb0b06eecf --- /dev/null +++ b/django/contrib/formtools/tests/wizard/test_loadstorage.py @@ -0,0 +1,18 @@ +from django.test import TestCase + +from django.contrib.formtools.wizard.storage import get_storage, MissingStorage +from django.contrib.formtools.wizard.storage.base import BaseStorage + + +class TestLoadStorage(TestCase): + def test_load_storage(self): + self.assertEqual( + type(get_storage('django.contrib.formtools.wizard.storage.base.BaseStorage', 'wizard1')), + BaseStorage) + + def test_missing_storage(self): + self.assertRaises(MissingStorage, get_storage, + 'django.contrib.formtools.wizard.storage.idontexist.IDontExistStorage', 'wizard1') + self.assertRaises(MissingStorage, get_storage, + 'django.contrib.formtools.wizard.storage.base.IDontExistStorage', 'wizard1') + diff --git a/django/contrib/formtools/tests/wizard/test_sessionstorage.py b/django/contrib/formtools/tests/wizard/test_sessionstorage.py new file mode 100644 index 0000000000..0bd9fd8ecd --- /dev/null +++ b/django/contrib/formtools/tests/wizard/test_sessionstorage.py @@ -0,0 +1,11 @@ +from django.test import TestCase + +from django.contrib.auth.tests.utils import skipIfCustomUser +from django.contrib.formtools.tests.wizard.storage import TestStorage +from django.contrib.formtools.wizard.storage.session import SessionStorage + + +@skipIfCustomUser +class TestSessionStorage(TestStorage, TestCase): + def get_storage(self): + return SessionStorage -- cgit v1.3