id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
1,900
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_permalink/models.py
from django.db import models class Guitarist(models.Model): name = models.CharField(max_length=50) slug = models.CharField(max_length=50) @models.permalink def url(self): "Returns the URL for this guitarist." return ('guitarist_detail', [self.slug])
284
Python
.py
8
30.25
48
0.70073
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,901
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_permalink/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'^guitarists/(\w{1,50})/$', 'unimplemented_view_placeholder', name='guitarist_detail'), )
167
Python
.py
4
39.5
96
0.716049
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,902
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_permalink/tests.py
from django.test import TestCase from regressiontests.model_permalink.models import Guitarist class PermalinkTests(TestCase): urls = 'regressiontests.model_permalink.urls' def test_permalink(self): g = Guitarist(name='Adrien Moignard', slug='adrienmoignard') self.assertEqual(g.url(), '/guitarists/adrienmoignard/') def test_wrapped_docstring(self): "Methods using the @permalink decorator retain their docstring." g = Guitarist(name='Adrien Moignard', slug='adrienmoignard') self.assertEqual(g.url.__doc__, "Returns the URL for this guitarist.")
602
Python
.py
11
48.727273
78
0.734694
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,903
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/dates/models.py
from django.db import models class Article(models.Model): title = models.CharField(max_length=100) pub_date = models.DateField() categories = models.ManyToManyField("Category", related_name="articles") def __unicode__(self): return self.title class Comment(models.Model): article = models.ForeignKey(Article, related_name="comments") text = models.TextField() pub_date = models.DateField() approval_date = models.DateField(null=True) def __unicode__(self): return 'Comment to %s (%s)' % (self.article.title, self.pub_date) class Category(models.Model): name = models.CharField(max_length=255)
656
Python
.py
16
36.0625
76
0.709321
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,904
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/dates/tests.py
from datetime import datetime from django.test import TestCase from models import Article, Comment, Category class DatesTests(TestCase): def test_related_model_traverse(self): a1 = Article.objects.create( title="First one", pub_date=datetime(2005, 7, 28), ) a2 = Article.objects.create( title="Another one", pub_date=datetime(2010, 7, 28), ) a3 = Article.objects.create( title="Third one, in the first day", pub_date=datetime(2005, 7, 28), ) a1.comments.create( text="Im the HULK!", pub_date=datetime(2005, 7, 28), ) a1.comments.create( text="HULK SMASH!", pub_date=datetime(2005, 7, 29), ) a2.comments.create( text="LMAO", pub_date=datetime(2010, 7, 28), ) a3.comments.create( text="+1", pub_date=datetime(2005, 8, 29), ) c = Category.objects.create(name="serious-news") c.articles.add(a1, a3) self.assertQuerysetEqual( Comment.objects.dates("article__pub_date", "year"), [ datetime(2005, 1, 1), datetime(2010, 1, 1), ], lambda d: d, ) self.assertQuerysetEqual( Comment.objects.dates("article__pub_date", "month"), [ datetime(2005, 7, 1), datetime(2010, 7, 1), ], lambda d: d ) self.assertQuerysetEqual( Comment.objects.dates("article__pub_date", "day"), [ datetime(2005, 7, 28), datetime(2010, 7, 28), ], lambda d: d ) self.assertQuerysetEqual( Article.objects.dates("comments__pub_date", "day"), [ datetime(2005, 7, 28), datetime(2005, 7, 29), datetime(2005, 8, 29), datetime(2010, 7, 28), ], lambda d: d ) self.assertQuerysetEqual( Article.objects.dates("comments__approval_date", "day"), [] ) self.assertQuerysetEqual( Category.objects.dates("articles__pub_date", "day"), [ datetime(2005, 7, 28), ], lambda d: d, )
2,391
Python
.py
74
20.891892
71
0.494805
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,905
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/models.py
# -*- coding: utf-8 -*- import datetime import tempfile from django.db import models from django.core.files.storage import FileSystemStorage temp_storage_location = tempfile.mkdtemp() temp_storage = FileSystemStorage(location=temp_storage_location) class BoundaryModel(models.Model): positive_integer = models.PositiveIntegerField(null=True, blank=True) callable_default_value = 0 def callable_default(): global callable_default_value callable_default_value = callable_default_value + 1 return callable_default_value class Defaults(models.Model): name = models.CharField(max_length=255, default='class default value') def_date = models.DateField(default = datetime.date(1980, 1, 1)) value = models.IntegerField(default=42) callable_default = models.IntegerField(default=callable_default) class ChoiceModel(models.Model): """For ModelChoiceField and ModelMultipleChoiceField tests.""" name = models.CharField(max_length=10) class ChoiceOptionModel(models.Model): """Destination for ChoiceFieldModel's ForeignKey. Can't reuse ChoiceModel because error_message tests require that it have no instances.""" name = models.CharField(max_length=10) class Meta: ordering = ('name',) def __unicode__(self): return u'ChoiceOption %d' % self.pk class ChoiceFieldModel(models.Model): """Model with ForeignKey to another model, for testing ModelForm generation with ModelChoiceField.""" choice = models.ForeignKey(ChoiceOptionModel, blank=False, default=lambda: ChoiceOptionModel.objects.get(name='default')) choice_int = models.ForeignKey(ChoiceOptionModel, blank=False, related_name='choice_int', default=lambda: 1) multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice', default=lambda: ChoiceOptionModel.objects.filter(name='default')) multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int', default=lambda: [1]) class FileModel(models.Model): file = models.FileField(storage=temp_storage, upload_to='tests') class Group(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return u'%s' % self.name class Cheese(models.Model): name = models.CharField(max_length=100)
2,477
Python
.py
49
43.387755
110
0.716604
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,906
localflavortests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavortests.py
from localflavor.ar import ARLocalFlavorTests from localflavor.at import ATLocalFlavorTests from localflavor.au import AULocalFlavorTests from localflavor.be import BELocalFlavorTests from localflavor.br import BRLocalFlavorTests from localflavor.ca import CALocalFlavorTests from localflavor.ch import CHLocalFlavorTests from localflavor.cl import CLLocalFlavorTests from localflavor.cz import CZLocalFlavorTests from localflavor.de import DELocalFlavorTests from localflavor.es import ESLocalFlavorTests from localflavor.fi import FILocalFlavorTests from localflavor.fr import FRLocalFlavorTests from localflavor.generic import GenericLocalFlavorTests from localflavor.id import IDLocalFlavorTests from localflavor.ie import IELocalFlavorTests from localflavor.il import ILLocalFlavorTests from localflavor.is_ import ISLocalFlavorTests from localflavor.it import ITLocalFlavorTests from localflavor.jp import JPLocalFlavorTests from localflavor.kw import KWLocalFlavorTests from localflavor.nl import NLLocalFlavorTests from localflavor.pl import PLLocalFlavorTests from localflavor.pt import PTLocalFlavorTests from localflavor.ro import ROLocalFlavorTests from localflavor.se import SELocalFlavorTests from localflavor.sk import SKLocalFlavorTests from localflavor.tr import TRLocalFlavorTests from localflavor.uk import UKLocalFlavorTests from localflavor.us import USLocalFlavorTests from localflavor.uy import UYLocalFlavorTests from localflavor.za import ZALocalFlavorTests
1,484
Python
.py
32
45.34375
55
0.911096
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,907
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/models.py
# -*- coding: utf-8 -*- import datetime from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import Form, ModelForm, FileField, ModelChoiceField from django.test import TestCase from regressiontests.forms.models import ChoiceModel, ChoiceOptionModel, ChoiceFieldModel, FileModel, Group, BoundaryModel, Defaults class ChoiceFieldForm(ModelForm): class Meta: model = ChoiceFieldModel class FileForm(Form): file1 = FileField() class TestTicket12510(TestCase): ''' It is not necessary to generate choices for ModelChoiceField (regression test for #12510). ''' def setUp(self): self.groups = [Group.objects.create(name=name) for name in 'abc'] def test_choices_not_fetched_when_not_rendering(self): def test(): field = ModelChoiceField(Group.objects.order_by('-name')) self.assertEqual('a', field.clean(self.groups[0].pk).name) # only one query is required to pull the model from DB self.assertNumQueries(1, test) class ModelFormCallableModelDefault(TestCase): def test_no_empty_option(self): "If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)." option = ChoiceOptionModel.objects.create(name='default') choices = list(ChoiceFieldForm().fields['choice'].choices) self.assertEqual(len(choices), 1) self.assertEqual(choices[0], (option.pk, unicode(option))) def test_callable_initial_value(self): "The initial value for a callable default returning a queryset is the pk (refs #13769)" obj1 = ChoiceOptionModel.objects.create(id=1, name='default') obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') self.assertEqual(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice"> <option value="1" selected="selected">ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice" value="1" id="initial-id_choice" /></p> <p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int"> <option value="1" selected="selected">ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int" /></p> <p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice"> <option value="1" selected="selected">ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p> <p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int"> <option value="1" selected="selected">ChoiceOption 1</option> <option value="2">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>""") def test_initial_instance_value(self): "Initial instances for model fields may also be instances (refs #7287)" obj1 = ChoiceOptionModel.objects.create(id=1, name='default') obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') self.assertEqual(ChoiceFieldForm(initial={ 'choice': obj2, 'choice_int': obj2, 'multi_choice': [obj2,obj3], 'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"), }).as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice"> <option value="1">ChoiceOption 1</option> <option value="2" selected="selected">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice" value="2" id="initial-id_choice" /></p> <p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int"> <option value="1">ChoiceOption 1</option> <option value="2" selected="selected">ChoiceOption 2</option> <option value="3">ChoiceOption 3</option> </select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int" /></p> <p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice"> <option value="1">ChoiceOption 1</option> <option value="2" selected="selected">ChoiceOption 2</option> <option value="3" selected="selected">ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0" /> <input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p> <p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int"> <option value="1">ChoiceOption 1</option> <option value="2" selected="selected">ChoiceOption 2</option> <option value="3" selected="selected">ChoiceOption 3</option> </select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0" /> <input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>""") class FormsModelTestCase(TestCase): def test_unicode_filename(self): # FileModel with unicode filename and data ######################### f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) self.assertTrue(f.is_valid()) self.assertTrue('file1' in f.cleaned_data) m = FileModel.objects.create(file=f.cleaned_data['file1']) self.assertEqual(m.file.name, u'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt') m.delete() def test_boundary_conditions(self): # Boundary conditions on a PostitiveIntegerField ######################### class BoundaryForm(ModelForm): class Meta: model = BoundaryModel f = BoundaryForm({'positive_integer': 100}) self.assertTrue(f.is_valid()) f = BoundaryForm({'positive_integer': 0}) self.assertTrue(f.is_valid()) f = BoundaryForm({'positive_integer': -100}) self.assertFalse(f.is_valid()) def test_formfield_initial(self): # Formfield initial values ######## # If the model has default values for some fields, they are used as the formfield # initial values. class DefaultsForm(ModelForm): class Meta: model = Defaults self.assertEqual(DefaultsForm().fields['name'].initial, u'class default value') self.assertEqual(DefaultsForm().fields['def_date'].initial, datetime.date(1980, 1, 1)) self.assertEqual(DefaultsForm().fields['value'].initial, 42) r1 = DefaultsForm()['callable_default'].as_widget() r2 = DefaultsForm()['callable_default'].as_widget() self.assertNotEqual(r1, r2) # In a ModelForm that is passed an instance, the initial values come from the # instance's values, not the model's defaults. foo_instance = Defaults(name=u'instance value', def_date=datetime.date(1969, 4, 4), value=12) instance_form = DefaultsForm(instance=foo_instance) self.assertEqual(instance_form.initial['name'], u'instance value') self.assertEqual(instance_form.initial['def_date'], datetime.date(1969, 4, 4)) self.assertEqual(instance_form.initial['value'], 12) from django.forms import CharField class ExcludingForm(ModelForm): name = CharField(max_length=255) class Meta: model = Defaults exclude = ['name', 'callable_default'] f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['name'], u'Hello') obj = f.save() self.assertEqual(obj.name, u'class default value') self.assertEqual(obj.value, 99) self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
9,010
Python
.py
138
58.123188
217
0.684655
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,908
util.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/util.py
# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.forms.util import * from django.utils.translation import ugettext_lazy from django.utils.unittest import TestCase class FormsUtilTestCase(TestCase): # Tests for forms/util.py module. def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({'id': "header"}), u' id="header"') self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), u' class="news" title="Read this"') self.assertEqual(flatatt({}), u'') def test_validation_error(self): ################### # ValidationError # ################### # Can take a string. self.assertEqual(str(ErrorList(ValidationError("There was an error.").messages)), '<ul class="errorlist"><li>There was an error.</li></ul>') # Can take a unicode string. self.assertEqual(str(ErrorList(ValidationError(u"Not \u03C0.").messages)), '<ul class="errorlist"><li>Not π.</li></ul>') # Can take a lazy string. self.assertEqual(str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)), '<ul class="errorlist"><li>Error.</li></ul>') # Can take a list. self.assertEqual(str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>') # Can take a mixture in a list. self.assertEqual(str(ErrorList(ValidationError(["First error.", u"Not \u03C0.", ugettext_lazy("Error.")]).messages)), '<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul>') class VeryBadError: def __unicode__(self): return u"A very bad error." # Can take a non-string. self.assertEqual(str(ErrorList(ValidationError(VeryBadError()).messages)), '<ul class="errorlist"><li>A very bad error.</li></ul>') # Escapes non-safe input but not input marked safe. example = 'Example of link: <a href="http://www.example.com/">example</a>' self.assertEqual(str(ErrorList([example])), '<ul class="errorlist"><li>Example of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>') self.assertEqual(str(ErrorList([mark_safe(example)])), '<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>')
2,630
Python
.py
44
48.522727
148
0.583042
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,909
input_formats.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/input_formats.py
from datetime import time, date, datetime from django import forms from django.conf import settings from django.utils.translation import activate, deactivate from django.utils.unittest import TestCase class LocalizedTimeTests(TestCase): def setUp(self): self.old_TIME_INPUT_FORMATS = settings.TIME_INPUT_FORMATS self.old_USE_L10N = settings.USE_L10N settings.TIME_INPUT_FORMATS = ["%I:%M:%S %p", "%I:%M %p"] settings.USE_L10N = True activate('de') def tearDown(self): settings.TIME_INPUT_FORMATS = self.old_TIME_INPUT_FORMATS settings.USE_L10N = self.old_USE_L10N deactivate() def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip text = f.widget._format_value(result) self.assertEqual(text, '13:30:05') # Parse a time in a valid, but non-default format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField(self): "Localized TimeFields act as unlocalized widgets" f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField_with_inputformat(self): "Localized TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13,30,5)) # # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") class CustomTimeInputFormatsTests(TestCase): def setUp(self): self.old_TIME_INPUT_FORMATS = settings.TIME_INPUT_FORMATS settings.TIME_INPUT_FORMATS = ["%I:%M:%S %p", "%I:%M %p"] def tearDown(self): settings.TIME_INPUT_FORMATS = self.old_TIME_INPUT_FORMATS def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM') # Parse a time in a valid, but non-default format, get a parsed result result = f.clean('1:30 PM') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM") def test_localized_timeField(self): "Localized TimeFields act as unlocalized widgets" f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('01:30 PM') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM") def test_localized_timeField_with_inputformat(self): "Localized TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('13.30.05') self.assertEqual(result, time(13,30,5)) # # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean('13.30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM") class SimpleTimeFormatTests(TestCase): def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid, but non-default format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField(self): "Localized TimeFields in a non-localized environment act as unlocalized widgets" f = forms.TimeField() # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') # Parse a time in a valid format, get a parsed result result = f.clean('13:30:05') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('13:30') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"]) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('1:30 PM') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField_with_inputformat(self): "Localized TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True) # Parse a time in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05') # Parse a time in a valid format, get a parsed result result = f.clean('1:30:05 PM') self.assertEqual(result, time(13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean('1:30 PM') self.assertEqual(result, time(13,30,0)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "13:30:00") class LocalizedDateTests(TestCase): def setUp(self): self.old_DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS self.old_USE_L10N = settings.USE_L10N settings.DATE_INPUT_FORMATS = ["%d/%m/%Y", "%d-%m-%Y"] settings.USE_L10N = True activate('de') def tearDown(self): settings.DATE_INPUT_FORMATS = self.old_DATE_INPUT_FORMATS settings.USE_L10N = self.old_USE_L10N deactivate() def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip text = f.widget._format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('21.12.10') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField(self): "Localized DateFields act as unlocalized widgets" f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.10') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField_with_inputformat(self): "Localized DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010,12,21)) # # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") class CustomDateInputFormatsTests(TestCase): def setUp(self): self.old_DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS settings.DATE_INPUT_FORMATS = ["%d.%m.%Y", "%d-%m-%Y"] def tearDown(self): settings.DATE_INPUT_FORMATS = self.old_DATE_INPUT_FORMATS def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip text = f.widget._format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField(self): "Localized DateFields act as unlocalized widgets" f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField_with_inputformat(self): "Localized DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010') self.assertEqual(result, date(2010,12,21)) # # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") class SimpleDateFormatTests(TestCase): def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('12/21/2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") def test_localized_dateField(self): "Localized DateFields in a non-localized environment act as unlocalized widgets" f = forms.DateField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean('12/21/2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"]) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") def test_localized_dateField_with_inputformat(self): "Localized DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean('21-12-2010') self.assertEqual(result, date(2010,12,21)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21") class LocalizedDateTimeTests(TestCase): def setUp(self): self.old_DATETIME_INPUT_FORMATS = settings.DATETIME_INPUT_FORMATS self.old_USE_L10N = settings.USE_L10N settings.DATETIME_INPUT_FORMATS = ["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"] settings.USE_L10N = True activate('de') def tearDown(self): settings.DATETIME_INPUT_FORMATS = self.old_DATETIME_INPUT_FORMATS settings.USE_L10N = self.old_USE_L10N deactivate() def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip text = f.widget._format_value(result) self.assertEqual(text, '21.12.2010 13:30:05') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('21.12.2010 13:30') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_localized_dateTimeField(self): "Localized DateTimeFields act as unlocalized widgets" f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, '21.12.2010 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('21.12.2010 13:30') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_dateTimeField_with_inputformat(self): "DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"]) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05 13:30:05') self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('13.30.05 12.21.2010') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('13.30 12-21-2010') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_localized_dateTimeField_with_inputformat(self): "Localized DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('13.30.05 12.21.2010') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('13.30 12-21-2010') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") class CustomDateTimeInputFormatsTests(TestCase): def setUp(self): self.old_DATETIME_INPUT_FORMATS = settings.DATETIME_INPUT_FORMATS settings.DATETIME_INPUT_FORMATS = ["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"] def tearDown(self): settings.DATETIME_INPUT_FORMATS = self.old_DATETIME_INPUT_FORMATS def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21/12/2010') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM 21/12/2010') # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_localized_dateTimeField(self): "Localized DateTimeFields act as unlocalized widgets" f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21/12/2010') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM 21/12/2010') # Parse a date in a valid format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_dateTimeField_with_inputformat(self): "DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"]) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010 13:30') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_localized_dateTimeField_with_inputformat(self): "Localized DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('12.21.2010 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean('12-21-2010 13:30') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") class SimpleDateTimeFormatTests(TestCase): def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean('12/21/2010 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") def test_localized_dateTimeField(self): "Localized DateTimeFields in a non-localized environment act as unlocalized widgets" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') # Parse a date in a valid format, get a parsed result result = f.clean('2010-12-21 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('12/21/2010 13:30:05') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") def test_dateTimeField_with_inputformat(self): "DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"]) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21.12.2010') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:00") def test_localized_dateTimeField_with_inputformat(self): "Localized DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True) # Parse a date in an unaccepted format; get an error self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') # Parse a date in a valid format, get a parsed result result = f.clean('1:30:05 PM 21.12.2010') self.assertEqual(result, datetime(2010,12,21,13,30,5)) # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean('1:30 PM 21-12-2010') self.assertEqual(result, datetime(2010,12,21,13,30)) # Check that the parsed result does a round trip to default format text = f.widget._format_value(result) self.assertEqual(text, "2010-12-21 13:30:00")
38,975
Python
.py
687
47.873362
107
0.660172
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,910
error_messages.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/error_messages.py
# -*- coding: utf-8 -*- from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import * from django.test import TestCase from django.utils.safestring import mark_safe from django.utils import unittest class AssertFormErrorsMixin(object): def assertFormErrors(self, expected, the_callable, *args, **kwargs): try: the_callable(*args, **kwargs) self.fail("Testing the 'clean' method on %s failed to raise a ValidationError.") except ValidationError, e: self.assertEqual(e.messages, expected) class FormsErrorMessagesTestCase(unittest.TestCase, AssertFormErrorsMixin): def test_charfield(self): e = { 'required': 'REQUIRED', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = CharField(min_length=5, max_length=10, error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'LENGTH 4, MIN LENGTH 5'], f.clean, '1234') self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_integerfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', } f = IntegerField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc') self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') def test_floatfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', } f = FloatField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc') self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') def test_decimalfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_value': 'MIN VALUE IS %(limit_value)s', 'max_value': 'MAX VALUE IS %(limit_value)s', 'max_digits': 'MAX DIGITS IS %s', 'max_decimal_places': 'MAX DP IS %s', 'max_whole_digits': 'MAX DIGITS BEFORE DP IS %s', } f = DecimalField(min_value=5, max_value=10, error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc') self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e) self.assertFormErrors([u'MAX DIGITS IS 4'], f2.clean, '123.45') self.assertFormErrors([u'MAX DP IS 2'], f2.clean, '1.234') self.assertFormErrors([u'MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4') def test_datefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = DateField(error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc') def test_timefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = TimeField(error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc') def test_datetimefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', } f = DateTimeField(error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc') def test_regexfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = RegexField(r'^\d+$', min_length=5, max_length=10, error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abcde') self.assertFormErrors([u'LENGTH 4, MIN LENGTH 5'], f.clean, '1234') self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') def test_emailfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', } f = EmailField(min_length=8, max_length=10, error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abcdefgh') self.assertFormErrors([u'LENGTH 7, MIN LENGTH 8'], f.clean, '[email protected]') self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, '[email protected]') def test_filefield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'missing': 'MISSING', 'empty': 'EMPTY FILE', } f = FileField(error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc') self.assertFormErrors([u'EMPTY FILE'], f.clean, SimpleUploadedFile('name', None)) self.assertFormErrors([u'EMPTY FILE'], f.clean, SimpleUploadedFile('name', '')) def test_urlfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID', 'invalid_link': 'INVALID LINK', } f = URLField(verify_exists=True, error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID'], f.clean, 'abc.c') self.assertFormErrors([u'INVALID LINK'], f.clean, 'http://www.broken.djangoproject.com') def test_booleanfield(self): e = { 'required': 'REQUIRED', } f = BooleanField(error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') def test_choicefield(self): e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', } f = ChoiceField(choices=[('a', 'aye')], error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'b IS INVALID CHOICE'], f.clean, 'b') def test_multiplechoicefield(self): e = { 'required': 'REQUIRED', 'invalid_choice': '%(value)s IS INVALID CHOICE', 'invalid_list': 'NOT A LIST', } f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'NOT A LIST'], f.clean, 'b') self.assertFormErrors([u'b IS INVALID CHOICE'], f.clean, ['b']) def test_splitdatetimefield(self): e = { 'required': 'REQUIRED', 'invalid_date': 'INVALID DATE', 'invalid_time': 'INVALID TIME', } f = SplitDateTimeField(error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID DATE', u'INVALID TIME'], f.clean, ['a', 'b']) def test_ipaddressfield(self): e = { 'required': 'REQUIRED', 'invalid': 'INVALID IP ADDRESS', } f = IPAddressField(error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID IP ADDRESS'], f.clean, '127.0.0') def test_subclassing_errorlist(self): class TestForm(Form): first_name = CharField() last_name = CharField() birthday = DateField() def clean(self): raise ValidationError("I like to be awkward.") class CustomErrorList(util.ErrorList): def __unicode__(self): return self.as_divs() def as_divs(self): if not self: return u'' return mark_safe(u'<div class="error">%s</div>' % ''.join([u'<p>%s</p>' % e for e in self])) # This form should print errors the default way. form1 = TestForm({'first_name': 'John'}) self.assertEqual(str(form1['last_name'].errors), '<ul class="errorlist"><li>This field is required.</li></ul>') self.assertEqual(str(form1.errors['__all__']), '<ul class="errorlist"><li>I like to be awkward.</li></ul>') # This one should wrap error groups in the customized way. form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList) self.assertEqual(str(form2['last_name'].errors), '<div class="error"><p>This field is required.</p></div>') self.assertEqual(str(form2.errors['__all__']), '<div class="error"><p>I like to be awkward.</p></div>') class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): def test_modelchoicefield(self): # Create choices for the model choice field tests below. from regressiontests.forms.models import ChoiceModel c1 = ChoiceModel.objects.create(pk=1, name='a') c2 = ChoiceModel.objects.create(pk=2, name='b') c3 = ChoiceModel.objects.create(pk=3, name='c') # ModelChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': 'INVALID CHOICE', } f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'INVALID CHOICE'], f.clean, '4') # ModelMultipleChoiceField e = { 'required': 'REQUIRED', 'invalid_choice': '%s IS INVALID CHOICE', 'list': 'NOT A LIST OF VALUES', } f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) self.assertFormErrors([u'REQUIRED'], f.clean, '') self.assertFormErrors([u'NOT A LIST OF VALUES'], f.clean, '3') self.assertFormErrors([u'4 IS INVALID CHOICE'], f.clean, ['4'])
10,684
Python
.py
224
37.941964
119
0.590356
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,911
regressions.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/regressions.py
# -*- coding: utf-8 -*- from django.forms import * from django.utils.unittest import TestCase from django.utils.translation import ugettext_lazy, activate, deactivate from regressiontests.forms.models import Cheese class FormsRegressionsTestCase(TestCase): def test_class(self): # Tests to prevent against recurrences of earlier bugs. extra_attrs = {'class': 'special'} class TestForm(Form): f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs)) f2 = CharField(widget=TextInput(attrs=extra_attrs)) self.assertEqual(TestForm(auto_id=False).as_p(), u'<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>') def test_regression_3600(self): # Tests for form i18n # # There were some problems with form translations in #3600 class SomeForm(Form): username = CharField(max_length=10, label=ugettext_lazy('Username')) f = SomeForm() self.assertEqual(f.as_p(), '<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') # Translations are done at rendering time, so multi-lingual apps can define forms) activate('de') self.assertEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') activate('pl') self.assertEqual(f.as_p(), u'<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') deactivate() def test_regression_5216(self): # There was some problems with form translations in #5216 class SomeForm(Form): field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) f = SomeForm() self.assertEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1</label>') self.assertEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2</label>') # Unicode decoding problems... GENDERS = ((u'\xc5', u'En tied\xe4'), (u'\xf8', u'Mies'), (u'\xdf', u'Nainen')) class SomeForm(Form): somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label=u'\xc5\xf8\xdf') f = SomeForm() self.assertEqual(f.as_p(), u'<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') # Testing choice validation with UTF-8 bytestrings as input (these are the # Russian abbreviations "мес." and "шт.". UNITS = (('\xd0\xbc\xd0\xb5\xd1\x81.', '\xd0\xbc\xd0\xb5\xd1\x81.'), ('\xd1\x88\xd1\x82.', '\xd1\x88\xd1\x82.')) f = ChoiceField(choices=UNITS) self.assertEqual(f.clean(u'\u0448\u0442.'), u'\u0448\u0442.') self.assertEqual(f.clean('\xd1\x88\xd1\x82.'), u'\u0448\u0442.') # Translated error messages used to be buggy. activate('ru') f = SomeForm({}) self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') deactivate() # Deep copying translated text shouldn't raise an error) from django.utils.translation import gettext_lazy class CopyForm(Form): degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) f = CopyForm() def test_misc(self): # There once was a problem with Form fields called "data". Let's make sure that # doesn't come back. class DataForm(Form): data = CharField(max_length=10) f = DataForm({'data': 'xyzzy'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {'data': u'xyzzy'}) # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul>\n<p> <input type="hidden" name="data" id="id_data" /></p>') self.assertEqual(f.as_table(), u'<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul><input type="hidden" name="data" id="id_data" /></td></tr>') def test_xss_error_messages(self): ################################################### # Tests for XSS vulnerabilities in error messages # ################################################### # The forms layer doesn't escape input values directly because error messages # might be presented in non-HTML contexts. Instead, the message is just marked # for escaping by the template engine. So we'll need to construct a little # silly template to trigger the escaping. from django.template import Template, Context t = Template('{{ form.errors }}') class SomeForm(Form): field = ChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': '<script>'}) self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>') class SomeForm(Form): field = MultipleChoiceField(choices=[('one', 'One')]) f = SomeForm({'field': ['<script>']}) self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>') from regressiontests.forms.models import ChoiceModel class SomeForm(Form): field = ModelMultipleChoiceField(ChoiceModel.objects.all()) f = SomeForm({'field': ['<script>']}) self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>') def test_regression_14234(self): """ Re-cleaning an instance that was added via a ModelForm should not raise a pk uniqueness error. """ class CheeseForm(ModelForm): class Meta: model = Cheese form = CheeseForm({ 'name': 'Brie', }) self.assertTrue(form.is_valid()) obj = form.save() obj.name = 'Camembert' obj.full_clean()
7,623
Python
.py
108
61.268519
634
0.626522
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,912
formsets.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/formsets.py
# -*- coding: utf-8 -*- from django.forms import Form, CharField, IntegerField, ValidationError, DateField from django.forms.formsets import formset_factory, BaseFormSet from django.utils.unittest import TestCase class Choice(Form): choice = CharField() votes = IntegerField() # FormSet allows us to use multiple instance of the same form on 1 page. For now, # the best way to create a FormSet is by using the formset_factory function. ChoiceFormSet = formset_factory(Choice) class FavoriteDrinkForm(Form): name = CharField() class BaseFavoriteDrinksFormSet(BaseFormSet): def clean(self): seen_drinks = [] for drink in self.cleaned_data: if drink['name'] in seen_drinks: raise ValidationError('You may only specify a drink once.') seen_drinks.append(drink['name']) class EmptyFsetWontValidate(BaseFormSet): def clean(self): raise ValidationError("Clean method called") # Let's define a FormSet that takes a list of favorite drinks, but raises an # error if there are any duplicates. Used in ``test_clean_hook``, # ``test_regression_6926`` & ``test_regression_12878``. FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3) class FormsFormsetTestCase(TestCase): def test_basic_formset(self): # A FormSet constructor takes the same arguments as Form. Let's create a FormSet # for adding data. By default, it displays 1 blank form. It can display more, # but we'll look at how to do so later. formset = ChoiceFormSet(auto_id=False, prefix='choices') self.assertEqual(str(formset), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" /> <tr><th>Choice:</th><td><input type="text" name="choices-0-choice" /></td></tr> <tr><th>Votes:</th><td><input type="text" name="choices-0-votes" /></td></tr>""") # On thing to note is that there needs to be a special value in the data. This # value tells the FormSet how many forms were displayed so it can tell how # many forms it needs to clean and validate. You could use javascript to create # new forms on the client side, but they won't get validated unless you increment # the TOTAL_FORMS field appropriately. data = { 'choices-TOTAL_FORMS': '1', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', } # We treat FormSet pretty much like we would treat a normal Form. FormSet has an # is_valid method, and a cleaned_data or errors attribute depending on whether all # the forms passed validation. However, unlike a Form instance, cleaned_data and # errors will be a list of dicts rather than just a single dict. formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}]) # If a FormSet was not passed any data, its is_valid method should return False. formset = ChoiceFormSet() self.assertFalse(formset.is_valid()) def test_formset_validation(self): # FormSet instances can also have an error attribute if validation failed for # any of the forms. data = { 'choices-TOTAL_FORMS': '1', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'votes': [u'This field is required.']}]) def test_formset_initial_data(self): # We can also prefill a FormSet with existing data by providing an ``initial`` # argument to the constructor. ``initial`` should be a list of dicts. By default, # an extra blank form is included. initial = [{'choice': u'Calexico', 'votes': 100}] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="text" name="choices-1-votes" /></li>""") # Let's simulate what would happen if we submitted this form. data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '1', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': '', 'choices-1-votes': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}]) def test_second_form_partially_filled(self): # But the second form was blank! Shouldn't we get some errors? No. If we display # a form as blank, it's ok for it to be submitted as blank. If we fill out even # one of the fields of a blank form though, it will be validated. We may want to # required that at least x number of forms are completed, but we'll show how to # handle that later. data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '1', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': 'The Decemberists', 'choices-1-votes': '', # missing value } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}]) def test_delete_prefilled_data(self): # If we delete data that was pre-filled, we should get an error. Simply removing # data from form fields isn't the proper way to delete it. We'll see how to # handle that case later. data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '1', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': '', # deleted value 'choices-0-votes': '', # deleted value 'choices-1-choice': '', 'choices-1-votes': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'votes': [u'This field is required.'], 'choice': [u'This field is required.']}, {}]) def test_displaying_more_than_one_blank_form(self): # Displaying more than 1 blank form ########################################### # We can also display more than 1 empty form at a time. To do so, pass a # extra argument to formset_factory. ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li> <li>Votes: <input type="text" name="choices-0-votes" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="text" name="choices-1-votes" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="text" name="choices-2-votes" /></li>""") # Since we displayed every form as blank, we will also accept them back as blank. # This may seem a little strange, but later we will show how to require a minimum # number of forms to be completed. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': '', 'choices-0-votes': '', 'choices-1-choice': '', 'choices-1-votes': '', 'choices-2-choice': '', 'choices-2-votes': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}]) def test_single_form_completed(self): # We can just fill out one of the forms. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': '', 'choices-1-votes': '', 'choices-2-choice': '', 'choices-2-votes': '', } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}, {}]) def test_second_form_partially_filled_2(self): # And once again, if we try to partially complete a form, validation will fail. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': 'The Decemberists', 'choices-1-votes': '', # missing value 'choices-2-choice': '', 'choices-2-votes': '', } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}, {}]) def test_more_initial_data(self): # The extra argument also works when the formset is pre-filled with initial # data. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': '', 'choices-1-votes': '', # missing value 'choices-2-choice': '', 'choices-2-votes': '', } initial = [{'choice': u'Calexico', 'votes': 100}] ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> <li>Choice: <input type="text" name="choices-1-choice" /></li> <li>Votes: <input type="text" name="choices-1-votes" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="text" name="choices-2-votes" /></li> <li>Choice: <input type="text" name="choices-3-choice" /></li> <li>Votes: <input type="text" name="choices-3-votes" /></li>""") # Make sure retrieving an empty form works, and it shows up in the form list self.assertTrue(formset.empty_form.empty_permitted) self.assertEqual(formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li> <li>Votes: <input type="text" name="choices-__prefix__-votes" /></li>""") def test_formset_with_deletion(self): # FormSets with deletion ###################################################### # We can easily add deletion ability to a FormSet with an argument to # formset_factory. This will add a boolean field to each form instance. When # that boolean field is True, the form will be in formset.deleted_forms ChoiceFormSet = formset_factory(Choice, can_delete=True) initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> <li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> <li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> <li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="text" name="choices-2-votes" /></li> <li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li>""") # To delete something, we just need to set that form's special delete field to # 'on'. Let's go ahead and delete Fergie. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '2', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-DELETE': '', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-DELETE': 'on', 'choices-2-choice': '', 'choices-2-votes': '', 'choices-2-DELETE': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': u'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': u'Fergie'}, {}]) self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': u'Fergie'}]) # If we fill a form with something and then we check the can_delete checkbox for # that form, that form's errors should not make the entire formset invalid since # it's going to be deleted. class CheckForm(Form): field = IntegerField(min_value=100) data = { 'check-TOTAL_FORMS': '3', # the number of forms rendered 'check-INITIAL_FORMS': '2', # the number of forms with initial data 'check-MAX_NUM_FORMS': '0', # max number of forms 'check-0-field': '200', 'check-0-DELETE': '', 'check-1-field': '50', 'check-1-DELETE': 'on', 'check-2-field': '', 'check-2-DELETE': '', } CheckFormSet = formset_factory(CheckForm, can_delete=True) formset = CheckFormSet(data, prefix='check') self.assertTrue(formset.is_valid()) # If we remove the deletion flag now we will have our validation back. data['check-1-DELETE'] = '' formset = CheckFormSet(data, prefix='check') self.assertFalse(formset.is_valid()) # Should be able to get deleted_forms from a valid formset even if a # deleted form would have been invalid. class Person(Form): name = CharField() PeopleForm = formset_factory( form=Person, can_delete=True) p = PeopleForm( {'form-0-name': u'', 'form-0-DELETE': u'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MAX_NUM_FORMS': 1}) self.assertTrue(p.is_valid()) self.assertEqual(len(p.deleted_forms), 1) def test_formsets_with_ordering(self): # FormSets with ordering ###################################################### # We can also add ordering ability to a FormSet with an argument to # formset_factory. This will add a integer field to each form instance. When # form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct # order specified by the ordering fields. If a number is duplicated in the set # of ordering fields, for instance form 0 and form 3 are both marked as 1, then # the form index used as a secondary ordering criteria. In order to put # something at the front of the list, you'd need to set it's order to 0. ChoiceFormSet = formset_factory(Choice, can_order=True) initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> <li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> <li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> <li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li> <li>Choice: <input type="text" name="choices-2-choice" /></li> <li>Votes: <input type="text" name="choices-2-votes" /></li> <li>Order: <input type="text" name="choices-2-ORDER" /></li>""") data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '2', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-ORDER': '2', 'choices-2-choice': 'The Decemberists', 'choices-2-votes': '500', 'choices-2-ORDER': '0', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, [ {'votes': 500, 'ORDER': 0, 'choice': u'The Decemberists'}, {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'}, {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'}, ]) def test_empty_ordered_fields(self): # Ordering fields are allowed to be left blank, and if they *are* left blank, # they will be sorted below everything else. data = { 'choices-TOTAL_FORMS': '4', # the number of forms rendered 'choices-INITIAL_FORMS': '3', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-ORDER': '2', 'choices-2-choice': 'The Decemberists', 'choices-2-votes': '500', 'choices-2-ORDER': '', 'choices-3-choice': 'Basia Bulat', 'choices-3-votes': '50', 'choices-3-ORDER': '', } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, [ {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'}, {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'}, {'votes': 500, 'ORDER': None, 'choice': u'The Decemberists'}, {'votes': 50, 'ORDER': None, 'choice': u'Basia Bulat'}, ]) def test_ordering_blank_fieldsets(self): # Ordering should work with blank fieldsets. data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, []) def test_formset_with_ordering_and_deletion(self): # FormSets with ordering + deletion ########################################### # Let's try throwing ordering and deletion into the same form. ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) initial = [ {'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}, {'choice': u'The Decemberists', 'votes': 500}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') form_output = [] for form in formset.forms: form_output.append(form.as_ul()) self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> <li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li> <li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> <li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> <li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li> <li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> <li>Choice: <input type="text" name="choices-2-choice" value="The Decemberists" /></li> <li>Votes: <input type="text" name="choices-2-votes" value="500" /></li> <li>Order: <input type="text" name="choices-2-ORDER" value="3" /></li> <li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li> <li>Choice: <input type="text" name="choices-3-choice" /></li> <li>Votes: <input type="text" name="choices-3-votes" /></li> <li>Order: <input type="text" name="choices-3-ORDER" /></li> <li>Delete: <input type="checkbox" name="choices-3-DELETE" /></li>""") # Let's delete Fergie, and put The Decemberists ahead of Calexico. data = { 'choices-TOTAL_FORMS': '4', # the number of forms rendered 'choices-INITIAL_FORMS': '3', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', 'choices-0-DELETE': '', 'choices-1-choice': 'Fergie', 'choices-1-votes': '900', 'choices-1-ORDER': '2', 'choices-1-DELETE': 'on', 'choices-2-choice': 'The Decemberists', 'choices-2-votes': '500', 'choices-2-ORDER': '0', 'choices-2-DELETE': '', 'choices-3-choice': '', 'choices-3-votes': '', 'choices-3-ORDER': '', 'choices-3-DELETE': '', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) form_output = [] for form in formset.ordered_forms: form_output.append(form.cleaned_data) self.assertEqual(form_output, [ {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': u'The Decemberists'}, {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': u'Calexico'}, ]) self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': u'Fergie'}]) def test_invalid_deleted_form_with_ordering(self): # Should be able to get ordered forms from a valid formset even if a # deleted form would have been invalid. class Person(Form): name = CharField() PeopleForm = formset_factory(form=Person, can_delete=True, can_order=True) p = PeopleForm({ 'form-0-name': u'', 'form-0-DELETE': u'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MAX_NUM_FORMS': 1 }) self.assertTrue(p.is_valid()) self.assertEqual(p.ordered_forms, []) def test_clean_hook(self): # FormSet clean hook ########################################################## # FormSets have a hook for doing extra validation that shouldn't be tied to any # particular form. It follows the same pattern as the clean hook on Forms. # We start out with a some duplicate data. data = { 'drinks-TOTAL_FORMS': '2', # the number of forms rendered 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Gin and Tonic', } formset = FavoriteDrinksFormSet(data, prefix='drinks') self.assertFalse(formset.is_valid()) # Any errors raised by formset.clean() are available via the # formset.non_form_errors() method. for error in formset.non_form_errors(): self.assertEqual(str(error), 'You may only specify a drink once.') # Make sure we didn't break the valid case. data = { 'drinks-TOTAL_FORMS': '2', # the number of forms rendered 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Bloody Mary', } formset = FavoriteDrinksFormSet(data, prefix='drinks') self.assertTrue(formset.is_valid()) self.assertEqual(formset.non_form_errors(), []) def test_limiting_max_forms(self): # Limiting the maximum number of forms ######################################## # Base case for max_num. # When not passed, max_num will take its default value of None, i.e. unlimited # number of forms, only controlled by the value of the extra parameter. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr> <tr><th><label for="id_form-2-name">Name:</label></th><td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr>""") # If max_num is 0 then no form is rendered at all. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), "") LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""") # Ensure that max_num has no effect when extra is less than max_num. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) formset = LimitedFavoriteDrinkFormSet() form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>""") def test_max_num_with_initial_data(self): # max_num with initial data # When not passed, max_num will take its default value of None, i.e. unlimited # number of forms, only controlled by the values of the initial and extra # parameters. initial = [ {'name': 'Fernet and Coke'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""") def test_max_num_zero(self): # If max_num is 0 then no form is rendered at all, even if extra and initial # are specified. initial = [ {'name': 'Fernet and Coke'}, {'name': 'Bloody Mary'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), "") def test_more_initial_than_max_num(self): # More initial forms than max_num will result in only the first max_num of # them to be displayed with no extra forms. initial = [ {'name': 'Gin Tonic'}, {'name': 'Bloody Mary'}, {'name': 'Jack and Coke'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" value="Bloody Mary" id="id_form-1-name" /></td></tr>""") # One form from initial and extra=3 with max_num=2 should result in the one # initial form and one extra. initial = [ {'name': 'Gin Tonic'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2) formset = LimitedFavoriteDrinkFormSet(initial=initial) form_output = [] for form in formset.forms: form_output.append(str(form)) self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""") def test_regression_6926(self): # Regression test for #6926 ################################################## # Make sure the management form has the correct prefix. formset = FavoriteDrinksFormSet() self.assertEqual(formset.management_form.prefix, 'form') data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '0', } formset = FavoriteDrinksFormSet(data=data) self.assertEqual(formset.management_form.prefix, 'form') formset = FavoriteDrinksFormSet(initial={}) self.assertEqual(formset.management_form.prefix, 'form') def test_regression_12878(self): # Regression test for #12878 ################################################# data = { 'drinks-TOTAL_FORMS': '2', # the number of forms rendered 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Gin and Tonic', } formset = FavoriteDrinksFormSet(data, prefix='drinks') self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), [u'You may only specify a drink once.']) def test_formset_iteration(self): # Regression tests for #16455 -- formset instances are iterable ChoiceFormset = formset_factory(Choice, extra=3) formset = ChoiceFormset() # confirm iterated formset yields formset.forms forms = list(formset) self.assertEqual(forms, formset.forms) self.assertEqual(len(formset), len(forms)) # confirm indexing of formset self.assertEqual(formset[0], forms[0]) try: formset[3] self.fail('Requesting an invalid formset index should raise an exception') except IndexError: pass # Formets can override the default iteration order class BaseReverseFormSet(BaseFormSet): def __iter__(self): for form in reversed(self.forms): yield form ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() # confirm that __iter__ modifies rendering order # compare forms from "reverse" formset with forms from original formset self.assertEqual(str(reverse_formset[0]), str(forms[-1])) self.assertEqual(str(reverse_formset[1]), str(forms[-2])) self.assertEqual(len(reverse_formset), len(forms)) data = { 'choices-TOTAL_FORMS': '1', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', } class Choice(Form): choice = CharField() votes = IntegerField() ChoiceFormSet = formset_factory(Choice) class FormsetAsFooTests(TestCase): def test_as_table(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertEqual(formset.as_table(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> <tr><th>Choice:</th><td><input type="text" name="choices-0-choice" value="Calexico" /></td></tr> <tr><th>Votes:</th><td><input type="text" name="choices-0-votes" value="100" /></td></tr>""") def test_as_p(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertEqual(formset.as_p(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> <p>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></p> <p>Votes: <input type="text" name="choices-0-votes" value="100" /></p>""") def test_as_ul(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertEqual(formset.as_ul(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> <li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Votes: <input type="text" name="choices-0-votes" value="100" /></li>""") # Regression test for #11418 ################################################# class ArticleForm(Form): title = CharField() pub_date = DateField() ArticleFormSet = formset_factory(ArticleForm) class TestIsBoundBehavior(TestCase): def test_no_data_raises_validation_error(self): self.assertRaises(ValidationError, ArticleFormSet, {}) def test_with_management_data_attrs_work_fine(self): data = { 'form-TOTAL_FORMS': u'1', 'form-INITIAL_FORMS': u'0', } formset = ArticleFormSet(data) self.assertEqual(0, formset.initial_form_count()) self.assertEqual(1, formset.total_form_count()) self.assertTrue(formset.is_bound) self.assertTrue(formset.forms[0].is_bound) self.assertTrue(formset.is_valid()) self.assertTrue(formset.forms[0].is_valid()) self.assertEqual([{}], formset.cleaned_data) def test_form_errors_are_cought_by_formset(self): data = { 'form-TOTAL_FORMS': u'2', 'form-INITIAL_FORMS': u'0', 'form-0-title': u'Test', 'form-0-pub_date': u'1904-06-16', 'form-1-title': u'Test', 'form-1-pub_date': u'', # <-- this date is missing but required } formset = ArticleFormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual([{}, {'pub_date': [u'This field is required.']}], formset.errors) def test_empty_forms_are_unbound(self): data = { 'form-TOTAL_FORMS': u'1', 'form-INITIAL_FORMS': u'0', 'form-0-title': u'Test', 'form-0-pub_date': u'1904-06-16', } unbound_formset = ArticleFormSet() bound_formset = ArticleFormSet(data) empty_forms = [] empty_forms.append(unbound_formset.empty_form) empty_forms.append(bound_formset.empty_form) # Empty forms should be unbound self.assertFalse(empty_forms[0].is_bound) self.assertFalse(empty_forms[1].is_bound) # The empty forms should be equal. self.assertEqual(empty_forms[0].as_p(), empty_forms[1].as_p()) class TestEmptyFormSet(TestCase): "Test that an empty formset still calls clean()" def test_empty_formset_is_valid(self): EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate) formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'0'},prefix="form") formset2 = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'1', 'form-0-name':'bah' },prefix="form") self.assertFalse(formset.is_valid()) self.assertFalse(formset2.is_valid())
41,032
Python
.py
731
46.819425
231
0.610852
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,913
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/__init__.py
from error_messages import * from extra import * from fields import FieldsTests from forms import * from formsets import * from input_formats import * from media import * from models import * from regressions import * from util import * from validators import TestFieldWithValidators from widgets import * from regressiontests.forms.localflavortests import ( ARLocalFlavorTests, ATLocalFlavorTests, AULocalFlavorTests, BELocalFlavorTests, BRLocalFlavorTests, CALocalFlavorTests, CHLocalFlavorTests, CLLocalFlavorTests, CZLocalFlavorTests, DELocalFlavorTests, ESLocalFlavorTests, FILocalFlavorTests, FRLocalFlavorTests, GenericLocalFlavorTests, IDLocalFlavorTests, IELocalFlavorTests, ILLocalFlavorTests, ISLocalFlavorTests, ITLocalFlavorTests, JPLocalFlavorTests, KWLocalFlavorTests, NLLocalFlavorTests, PLLocalFlavorTests, PTLocalFlavorTests, ROLocalFlavorTests, SELocalFlavorTests, SKLocalFlavorTests, TRLocalFlavorTests, UKLocalFlavorTests, USLocalFlavorTests, UYLocalFlavorTests, ZALocalFlavorTests )
1,050
Python
.py
25
39.2
68
0.852539
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,914
validators.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/validators.py
from django import forms from django.core import validators from django.core.exceptions import ValidationError from django.utils.unittest import TestCase class TestFieldWithValidators(TestCase): def test_all_errors_get_reported(self): field = forms.CharField( validators=[validators.validate_integer, validators.validate_email] ) self.assertRaises(ValidationError, field.clean, 'not int nor mail') try: field.clean('not int nor mail') except ValidationError, e: self.assertEqual(2, len(e.messages))
581
Python
.py
14
34.642857
79
0.720354
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,915
media.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/media.py
# -*- coding: utf-8 -*- from django.conf import settings from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget from django.utils.unittest import TestCase class FormsMediaTestCase(TestCase): # Tests for the media handling on widgets and forms def setUp(self): super(FormsMediaTestCase, self).setUp() self.original_media_url = settings.MEDIA_URL settings.MEDIA_URL = 'http://media.example.com/media/' def tearDown(self): settings.MEDIA_URL = self.original_media_url super(FormsMediaTestCase, self).tearDown() def test_construction(self): # Check construction of media objects m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')) self.assertEqual(str(m), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") class Foo: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') m3 = Media(Foo) self.assertEqual(str(m3), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # A widget can exist without a media definition class MyWidget(TextInput): pass w = MyWidget() self.assertEqual(str(w.media), '') def test_media_dsl(self): ############################################################### # DSL Class-based media definitions ############################################################### # A widget can define media if it needs to. # Any absolute path will be preserved; relative paths are combined # with the value of settings.MEDIA_URL class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') w1 = MyWidget1() self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Media objects can be interrogated by media type self.assertEqual(str(w1.media['css']), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />""") self.assertEqual(str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only # once. Duplicated media definitions are ignored. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2','/path/to/css3') } js = ('/path/to/js1','/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() self.assertEqual(str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Check that media addition hasn't affected the original objects self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file # only being included once. class MyWidget4(TextInput): class Media: css = {'all': ('/path/to/css1', '/path/to/css1')} js = ('/path/to/js1', '/path/to/js1') w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script>""") def test_media_property(self): ############################################################### # Property-based media definitions ############################################################### # Widget media can be defined as a property class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js = ('/some/js',)) media = property(_media) w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script>""") # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) media = property(_media) w5 = MyWidget5() self.assertEqual(str(w5.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_property_parent_references(self): # Media properties can reference the media of their parents, # even if the parent media was defined using a class class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget6(MyWidget1): def _media(self): return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) media = property(_media) w6 = MyWidget6() self.assertEqual(str(w6.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_inheritance(self): ############################################################### # Inheritance of media ############################################################### # If a widget extends another but provides no media definition, it inherits the parent widget's media class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget7(MyWidget1): pass w7 = MyWidget7() self.assertEqual(str(w7.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w8 = MyWidget8() self.assertEqual(str(w8.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents widget's media, # even if the parent defined media using a property. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js = ('/some/js',)) media = property(_media) class MyWidget9(MyWidget4): class Media: css = { 'all': ('/other/path',) } js = ('/other/js',) w9 = MyWidget9() self.assertEqual(str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): class Media: extend = False css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w10 = MyWidget10() self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_extends(self): # A widget can explicitly enable full media inheritance by specifying 'extend=True' class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget11(MyWidget1): class Media: extend = True css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w11 = MyWidget11() self.assertEqual(str(w11.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget12(MyWidget1): class Media: extend = ('css',) css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w12 = MyWidget12() self.assertEqual(str(w12.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_media(self): ############################################################### # Multi-media handling for CSS ############################################################### # A widget can define CSS media for multiple output media types class MultimediaWidget(TextInput): class Media: css = { 'screen, print': ('/file1','/file2'), 'screen': ('/file3',), 'print': ('/file4',) } js = ('/path/to/js1','/path/to/js4') multimedia = MultimediaWidget() self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" /> <link href="/file3" type="text/css" media="screen" rel="stylesheet" /> <link href="/file1" type="text/css" media="screen, print" rel="stylesheet" /> <link href="/file2" type="text/css" media="screen, print" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_widget(self): ############################################################### # Multiwidget media handling ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2','/path/to/css3') } js = ('/path/to/js1','/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') # MultiWidgets have a default media definition that gets all the # media from the component widgets class MyMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = [MyWidget1, MyWidget2, MyWidget3] super(MyMultiWidget, self).__init__(widgets, attrs) mymulti = MyMultiWidget() self.assertEqual(str(mymulti.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_form_media(self): ############################################################### # Media processing for forms ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2','/path/to/css3') } js = ('/path/to/js1','/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') # You can ask a form for the media required by its widgets. class MyForm(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() self.assertEqual(str(f1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() self.assertEqual(str(f1.media + f2.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } f3 = FormWithMedia() self.assertEqual(str(f3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script>""") # Media works in templates from django.template import Template, Context self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""") class StaticFormsMediaTestCase(TestCase): # Tests for the media handling on widgets and forms def setUp(self): super(StaticFormsMediaTestCase, self).setUp() self.original_media_url = settings.MEDIA_URL self.original_static_url = settings.STATIC_URL settings.MEDIA_URL = 'http://media.example.com/static/' settings.STATIC_URL = 'http://media.example.com/static/' def tearDown(self): settings.MEDIA_URL = self.original_media_url settings.STATIC_URL = self.original_static_url super(StaticFormsMediaTestCase, self).tearDown() def test_construction(self): # Check construction of media objects m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')) self.assertEqual(str(m), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") class Foo: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') m3 = Media(Foo) self.assertEqual(str(m3), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # A widget can exist without a media definition class MyWidget(TextInput): pass w = MyWidget() self.assertEqual(str(w.media), '') def test_media_dsl(self): ############################################################### # DSL Class-based media definitions ############################################################### # A widget can define media if it needs to. # Any absolute path will be preserved; relative paths are combined # with the value of settings.MEDIA_URL class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') w1 = MyWidget1() self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Media objects can be interrogated by media type self.assertEqual(str(w1.media['css']), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />""") self.assertEqual(str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only # once. Duplicated media definitions are ignored. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2','/path/to/css3') } js = ('/path/to/js1','/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() self.assertEqual(str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Check that media addition hasn't affected the original objects self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file # only being included once. class MyWidget4(TextInput): class Media: css = {'all': ('/path/to/css1', '/path/to/css1')} js = ('/path/to/js1', '/path/to/js1') w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script>""") def test_media_property(self): ############################################################### # Property-based media definitions ############################################################### # Widget media can be defined as a property class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js = ('/some/js',)) media = property(_media) w4 = MyWidget4() self.assertEqual(str(w4.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script>""") # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) media = property(_media) w5 = MyWidget5() self.assertEqual(str(w5.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_property_parent_references(self): # Media properties can reference the media of their parents, # even if the parent media was defined using a class class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget6(MyWidget1): def _media(self): return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) media = property(_media) w6 = MyWidget6() self.assertEqual(str(w6.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/other/js"></script>""") def test_media_inheritance(self): ############################################################### # Inheritance of media ############################################################### # If a widget extends another but provides no media definition, it inherits the parent widget's media class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget7(MyWidget1): pass w7 = MyWidget7() self.assertEqual(str(w7.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w8 = MyWidget8() self.assertEqual(str(w8.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents widget's media, # even if the parent defined media using a property. class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget4(TextInput): def _media(self): return Media(css={'all': ('/some/path',)}, js = ('/some/js',)) media = property(_media) class MyWidget9(MyWidget4): class Media: css = { 'all': ('/other/path',) } js = ('/other/js',) w9 = MyWidget9() self.assertEqual(str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> <link href="/other/path" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/some/js"></script> <script type="text/javascript" src="/other/js"></script>""") # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): class Media: extend = False css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w10 = MyWidget10() self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_extends(self): # A widget can explicitly enable full media inheritance by specifying 'extend=True' class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget11(MyWidget1): class Media: extend = True css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w11 = MyWidget11() self.assertEqual(str(w11.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget12(MyWidget1): class Media: extend = ('css',) css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') w12 = MyWidget12() self.assertEqual(str(w12.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_media(self): ############################################################### # Multi-media handling for CSS ############################################################### # A widget can define CSS media for multiple output media types class MultimediaWidget(TextInput): class Media: css = { 'screen, print': ('/file1','/file2'), 'screen': ('/file3',), 'print': ('/file4',) } js = ('/path/to/js1','/path/to/js4') multimedia = MultimediaWidget() self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" /> <link href="/file3" type="text/css" media="screen" rel="stylesheet" /> <link href="/file1" type="text/css" media="screen, print" rel="stylesheet" /> <link href="/file2" type="text/css" media="screen, print" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_multi_widget(self): ############################################################### # Multiwidget media handling ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2','/path/to/css3') } js = ('/path/to/js1','/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') # MultiWidgets have a default media definition that gets all the # media from the component widgets class MyMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = [MyWidget1, MyWidget2, MyWidget3] super(MyMultiWidget, self).__init__(widgets, attrs) mymulti = MyMultiWidget() self.assertEqual(str(mymulti.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") def test_form_media(self): ############################################################### # Media processing for forms ############################################################### class MyWidget1(TextInput): class Media: css = { 'all': ('path/to/css1','/path/to/css2') } js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') class MyWidget2(TextInput): class Media: css = { 'all': ('/path/to/css2','/path/to/css3') } js = ('/path/to/js1','/path/to/js4') class MyWidget3(TextInput): class Media: css = { 'all': ('/path/to/css3','path/to/css1') } js = ('/path/to/js1','/path/to/js4') # You can ask a form for the media required by its widgets. class MyForm(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() self.assertEqual(str(f1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() self.assertEqual(str(f1.media + f2.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script>""") # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } f3 = FormWithMedia() self.assertEqual(str(f3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script>""") # Media works in templates from django.template import Template, Context self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
46,165
Python
.py
793
48.619168
173
0.582186
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,916
widgets.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/widgets.py
# -*- coding: utf-8 -*- import datetime from decimal import Decimal import re import time from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import * from django.forms.widgets import RadioFieldRenderer from django.utils import copycompat as copy from django.utils import formats from django.utils.safestring import mark_safe from django.utils.translation import activate, deactivate from django.utils.unittest import TestCase class FormsWidgetTestCase(TestCase): # Each Widget class corresponds to an HTML form widget. A Widget knows how to # render itself, given a field name and some data. Widgets don't perform # validation. def test_textinput(self): w = TextInput() self.assertEqual(w.render('email', ''), u'<input type="text" name="email" />') self.assertEqual(w.render('email', None), u'<input type="text" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="text" name="email" value="[email protected]" />') self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="text" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />') self.assertEqual(w.render('email', '[email protected]', attrs={'class': 'fun'}), u'<input type="text" name="email" value="[email protected]" class="fun" />') # Note that doctest in Python 2.4 (and maybe 2.5?) doesn't support non-ascii # characters in output, so we're displaying the repr() here. self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="text" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun" />') # You can also pass 'attrs' to the constructor: w = TextInput(attrs={'class': 'fun'}) self.assertEqual(w.render('email', ''), u'<input type="text" class="fun" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="text" class="fun" value="[email protected]" name="email" />') # 'attrs' passed to render() get precedence over those passed to the constructor: w = TextInput(attrs={'class': 'pretty'}) self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="text" class="special" name="email" />') # 'attrs' can be safe-strings if needed) w = TextInput(attrs={'onBlur': mark_safe("function('foo')")}) self.assertEqual(w.render('email', ''), u'<input onBlur="function(\'foo\')" type="text" name="email" />') def test_passwordinput(self): w = PasswordInput() self.assertEqual(w.render('email', ''), u'<input type="password" name="email" />') self.assertEqual(w.render('email', None), u'<input type="password" name="email" />') self.assertEqual(w.render('email', 'secret'), u'<input type="password" name="email" />') # The render_value argument lets you specify whether the widget should render # its value. For security reasons, this is off by default. w = PasswordInput(render_value=True) self.assertEqual(w.render('email', ''), u'<input type="password" name="email" />') self.assertEqual(w.render('email', None), u'<input type="password" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="password" name="email" value="[email protected]" />') self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="password" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />') self.assertEqual(w.render('email', '[email protected]', attrs={'class': 'fun'}), u'<input type="password" name="email" value="[email protected]" class="fun" />') # You can also pass 'attrs' to the constructor: w = PasswordInput(attrs={'class': 'fun'}, render_value=True) self.assertEqual(w.render('email', ''), u'<input type="password" class="fun" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="password" class="fun" value="[email protected]" name="email" />') # 'attrs' passed to render() get precedence over those passed to the constructor: w = PasswordInput(attrs={'class': 'pretty'}, render_value=True) self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="password" class="special" name="email" />') self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="password" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />') def test_hiddeninput(self): w = HiddenInput() self.assertEqual(w.render('email', ''), u'<input type="hidden" name="email" />') self.assertEqual(w.render('email', None), u'<input type="hidden" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="hidden" name="email" value="[email protected]" />') self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />') self.assertEqual(w.render('email', '[email protected]', attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="[email protected]" class="fun" />') # You can also pass 'attrs' to the constructor: w = HiddenInput(attrs={'class': 'fun'}) self.assertEqual(w.render('email', ''), u'<input type="hidden" class="fun" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="hidden" class="fun" value="[email protected]" name="email" />') # 'attrs' passed to render() get precedence over those passed to the constructor: w = HiddenInput(attrs={'class': 'pretty'}) self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="hidden" class="special" name="email" />') self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />') # 'attrs' passed to render() get precedence over those passed to the constructor: w = HiddenInput(attrs={'class': 'pretty'}) self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="hidden" class="special" name="email" />') # Boolean values are rendered to their string forms ("True" and "False"). w = HiddenInput() self.assertEqual(w.render('get_spam', False), u'<input type="hidden" name="get_spam" value="False" />') self.assertEqual(w.render('get_spam', True), u'<input type="hidden" name="get_spam" value="True" />') def test_multiplehiddeninput(self): w = MultipleHiddenInput() self.assertEqual(w.render('email', []), u'') self.assertEqual(w.render('email', None), u'') self.assertEqual(w.render('email', ['[email protected]']), u'<input type="hidden" name="email" value="[email protected]" />') self.assertEqual(w.render('email', ['some "quoted" & ampersanded value']), u'<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />') self.assertEqual(w.render('email', ['[email protected]', '[email protected]']), u'<input type="hidden" name="email" value="[email protected]" />\n<input type="hidden" name="email" value="[email protected]" />') self.assertEqual(w.render('email', ['[email protected]'], attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="[email protected]" class="fun" />') self.assertEqual(w.render('email', ['[email protected]', '[email protected]'], attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="[email protected]" class="fun" />\n<input type="hidden" name="email" value="[email protected]" class="fun" />') # You can also pass 'attrs' to the constructor: w = MultipleHiddenInput(attrs={'class': 'fun'}) self.assertEqual(w.render('email', []), u'') self.assertEqual(w.render('email', ['[email protected]']), u'<input type="hidden" class="fun" value="[email protected]" name="email" />') self.assertEqual(w.render('email', ['[email protected]', '[email protected]']), u'<input type="hidden" class="fun" value="[email protected]" name="email" />\n<input type="hidden" class="fun" value="[email protected]" name="email" />') # 'attrs' passed to render() get precedence over those passed to the constructor: w = MultipleHiddenInput(attrs={'class': 'pretty'}) self.assertEqual(w.render('email', ['[email protected]'], attrs={'class': 'special'}), u'<input type="hidden" class="special" value="[email protected]" name="email" />') self.assertEqual(w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'}), u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />') # 'attrs' passed to render() get precedence over those passed to the constructor: w = MultipleHiddenInput(attrs={'class': 'pretty'}) self.assertEqual(w.render('email', ['[email protected]'], attrs={'class': 'special'}), u'<input type="hidden" class="special" value="[email protected]" name="email" />') # Each input gets a separate ID. w = MultipleHiddenInput() self.assertEqual(w.render('letters', list('abc'), attrs={'id': 'hideme'}), u'<input type="hidden" name="letters" value="a" id="hideme_0" />\n<input type="hidden" name="letters" value="b" id="hideme_1" />\n<input type="hidden" name="letters" value="c" id="hideme_2" />') def test_fileinput(self): # FileInput widgets don't ever show the value, because the old value is of no use # if you are updating the form or if the provided file generated an error. w = FileInput() self.assertEqual(w.render('email', ''), u'<input type="file" name="email" />') self.assertEqual(w.render('email', None), u'<input type="file" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="file" name="email" />') self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="file" name="email" />') self.assertEqual(w.render('email', '[email protected]', attrs={'class': 'fun'}), u'<input type="file" name="email" class="fun" />') # You can also pass 'attrs' to the constructor: w = FileInput(attrs={'class': 'fun'}) self.assertEqual(w.render('email', ''), u'<input type="file" class="fun" name="email" />') self.assertEqual(w.render('email', '[email protected]'), u'<input type="file" class="fun" name="email" />') self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="file" class="fun" name="email" />') # Test for the behavior of _has_changed for FileInput. The value of data will # more than likely come from request.FILES. The value of initial data will # likely be a filename stored in the database. Since its value is of no use to # a FileInput it is ignored. w = FileInput() # No file was uploaded and no initial data. self.assertFalse(w._has_changed(u'', None)) # A file was uploaded and no initial data. self.assertTrue(w._has_changed(u'', {'filename': 'resume.txt', 'content': 'My resume'})) # A file was not uploaded, but there is initial data self.assertFalse(w._has_changed(u'resume.txt', None)) # A file was uploaded and there is initial data (file identity is not dealt # with here) self.assertTrue(w._has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'})) def test_textarea(self): w = Textarea() self.assertEqual(w.render('msg', ''), u'<textarea rows="10" cols="40" name="msg"></textarea>') self.assertEqual(w.render('msg', None), u'<textarea rows="10" cols="40" name="msg"></textarea>') self.assertEqual(w.render('msg', 'value'), u'<textarea rows="10" cols="40" name="msg">value</textarea>') self.assertEqual(w.render('msg', 'some "quoted" & ampersanded value'), u'<textarea rows="10" cols="40" name="msg">some &quot;quoted&quot; &amp; ampersanded value</textarea>') self.assertEqual(w.render('msg', mark_safe('pre &quot;quoted&quot; value')), u'<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value</textarea>') self.assertEqual(w.render('msg', 'value', attrs={'class': 'pretty', 'rows': 20}), u'<textarea class="pretty" rows="20" cols="40" name="msg">value</textarea>') # You can also pass 'attrs' to the constructor: w = Textarea(attrs={'class': 'pretty'}) self.assertEqual(w.render('msg', ''), u'<textarea rows="10" cols="40" name="msg" class="pretty"></textarea>') self.assertEqual(w.render('msg', 'example'), u'<textarea rows="10" cols="40" name="msg" class="pretty">example</textarea>') # 'attrs' passed to render() get precedence over those passed to the constructor: w = Textarea(attrs={'class': 'pretty'}) self.assertEqual(w.render('msg', '', attrs={'class': 'special'}), u'<textarea rows="10" cols="40" name="msg" class="special"></textarea>') self.assertEqual(w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<textarea rows="10" cols="40" name="msg" class="fun">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</textarea>') def test_checkboxinput(self): w = CheckboxInput() self.assertEqual(w.render('is_cool', ''), u'<input type="checkbox" name="is_cool" />') self.assertEqual(w.render('is_cool', None), u'<input type="checkbox" name="is_cool" />') self.assertEqual(w.render('is_cool', False), u'<input type="checkbox" name="is_cool" />') self.assertEqual(w.render('is_cool', True), u'<input checked="checked" type="checkbox" name="is_cool" />') # Using any value that's not in ('', None, False, True) will check the checkbox # and set the 'value' attribute. self.assertEqual(w.render('is_cool', 'foo'), u'<input checked="checked" type="checkbox" name="is_cool" value="foo" />') self.assertEqual(w.render('is_cool', False, attrs={'class': 'pretty'}), u'<input type="checkbox" name="is_cool" class="pretty" />') # You can also pass 'attrs' to the constructor: w = CheckboxInput(attrs={'class': 'pretty'}) self.assertEqual(w.render('is_cool', ''), u'<input type="checkbox" class="pretty" name="is_cool" />') # 'attrs' passed to render() get precedence over those passed to the constructor: w = CheckboxInput(attrs={'class': 'pretty'}) self.assertEqual(w.render('is_cool', '', attrs={'class': 'special'}), u'<input type="checkbox" class="special" name="is_cool" />') # You can pass 'check_test' to the constructor. This is a callable that takes the # value and returns True if the box should be checked. w = CheckboxInput(check_test=lambda value: value.startswith('hello')) self.assertEqual(w.render('greeting', ''), u'<input type="checkbox" name="greeting" />') self.assertEqual(w.render('greeting', 'hello'), u'<input checked="checked" type="checkbox" name="greeting" value="hello" />') self.assertEqual(w.render('greeting', 'hello there'), u'<input checked="checked" type="checkbox" name="greeting" value="hello there" />') self.assertEqual(w.render('greeting', 'hello & goodbye'), u'<input checked="checked" type="checkbox" name="greeting" value="hello &amp; goodbye" />') # A subtlety: If the 'check_test' argument cannot handle a value and raises any # exception during its __call__, then the exception will be swallowed and the box # will not be checked. In this example, the 'check_test' assumes the value has a # startswith() method, which fails for the values True, False and None. self.assertEqual(w.render('greeting', True), u'<input type="checkbox" name="greeting" />') self.assertEqual(w.render('greeting', False), u'<input type="checkbox" name="greeting" />') self.assertEqual(w.render('greeting', None), u'<input type="checkbox" name="greeting" />') # The CheckboxInput widget will return False if the key is not found in the data # dictionary (because HTML form submission doesn't send any result for unchecked # checkboxes). self.assertFalse(w.value_from_datadict({}, {}, 'testing')) self.assertFalse(w._has_changed(None, None)) self.assertFalse(w._has_changed(None, u'')) self.assertFalse(w._has_changed(u'', None)) self.assertFalse(w._has_changed(u'', u'')) self.assertTrue(w._has_changed(False, u'on')) self.assertFalse(w._has_changed(True, u'on')) self.assertTrue(w._has_changed(True, u'')) def test_select(self): w = Select() self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select name="beatle"> <option value="J" selected="selected">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""") # If the value is None, none of the options are selected: self.assertEqual(w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""") # If the value corresponds to a label (but not to an option value), none of the options are selected: self.assertEqual(w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select name="beatle"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""") # The value is compared to its str(): self.assertEqual(w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<select name="num"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") self.assertEqual(w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]), """<select name="num"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") self.assertEqual(w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]), """<select name="num"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") # The 'choices' argument can be any iterable: from itertools import chain def get_choices(): for i in range(5): yield (i, i) self.assertEqual(w.render('num', 2, choices=get_choices()), """<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <option value="4">4</option> </select>""") things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'}) class SomeForm(Form): somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things])) f = SomeForm() self.assertEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>') self.assertEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>') f = SomeForm({'somechoice': 2}) self.assertEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="">---------</option>\n<option value="1">And Boom</option>\n<option value="2" selected="selected">One More Thing!</option>\n</select></td></tr>') # You can also pass 'choices' to the constructor: w = Select(choices=[(1, 1), (2, 2), (3, 3)]) self.assertEqual(w.render('num', 2), """<select name="num"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: self.assertEqual(w.render('num', 2, choices=[(4, 4), (5, 5)]), """<select name="num"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select>""") # Choices are escaped correctly self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; me')))), """<select name="escape"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="bad">you &amp; me</option> <option value="good">you &gt; me</option> </select>""") # Unicode choices are correctly rendered as HTML self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<select name="email">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>') # If choices is passed to the constructor and is a generator, it can be iterated # over multiple times without getting consumed: w = Select(choices=get_choices()) self.assertEqual(w.render('num', 2), """<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <option value="4">4</option> </select>""") self.assertEqual(w.render('num', 3), """<select name="num"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3" selected="selected">3</option> <option value="4">4</option> </select>""") # Choices can be nested one level in order to create HTML optgroups: w.choices=(('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2')))) self.assertEqual(w.render('nestchoice', None), """<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""") self.assertEqual(w.render('nestchoice', 'outer1'), """<select name="nestchoice"> <option value="outer1" selected="selected">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""") self.assertEqual(w.render('nestchoice', 'inner1'), """<select name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1" selected="selected">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""") def test_nullbooleanselect(self): w = NullBooleanSelect() self.assertTrue(w.render('is_cool', True), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected="selected">Yes</option> <option value="3">No</option> </select>""") self.assertEqual(w.render('is_cool', False), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2">Yes</option> <option value="3" selected="selected">No</option> </select>""") self.assertEqual(w.render('is_cool', None), """<select name="is_cool"> <option value="1" selected="selected">Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select>""") self.assertEqual(w.render('is_cool', '2'), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected="selected">Yes</option> <option value="3">No</option> </select>""") self.assertEqual(w.render('is_cool', '3'), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2">Yes</option> <option value="3" selected="selected">No</option> </select>""") self.assertTrue(w._has_changed(False, None)) self.assertTrue(w._has_changed(None, False)) self.assertFalse(w._has_changed(None, None)) self.assertFalse(w._has_changed(False, False)) self.assertTrue(w._has_changed(True, False)) self.assertTrue(w._has_changed(True, None)) self.assertTrue(w._has_changed(True, False)) def test_selectmultiple(self): w = SelectMultiple() self.assertEqual(w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> <option value="J" selected="selected">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""") self.assertEqual(w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> <option value="J" selected="selected">John</option> <option value="P" selected="selected">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""") self.assertEqual(w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> <option value="J" selected="selected">John</option> <option value="P" selected="selected">Paul</option> <option value="G">George</option> <option value="R" selected="selected">Ringo</option> </select>""") # If the value is None, none of the options are selected: self.assertEqual(w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""") # If the value corresponds to a label (but not to an option value), none of the options are selected: self.assertEqual(w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select>""") # If multiple values are given, but some of them are not valid, the valid ones are selected: self.assertEqual(w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> <option value="J" selected="selected">John</option> <option value="P">Paul</option> <option value="G" selected="selected">George</option> <option value="R">Ringo</option> </select>""") # The value is compared to its str(): self.assertEqual(w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") self.assertEqual(w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]), """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") self.assertEqual(w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]), """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") # The 'choices' argument can be any iterable: def get_choices(): for i in range(5): yield (i, i) self.assertEqual(w.render('nums', [2], choices=get_choices()), """<select multiple="multiple" name="nums"> <option value="0">0</option> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <option value="4">4</option> </select>""") # You can also pass 'choices' to the constructor: w = SelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) self.assertEqual(w.render('nums', [2]), """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> </select>""") # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: self.assertEqual(w.render('nums', [2], choices=[(4, 4), (5, 5)]), """<select multiple="multiple" name="nums"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select>""") # Choices are escaped correctly self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; me')))), """<select multiple="multiple" name="escape"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="bad">you &amp; me</option> <option value="good">you &gt; me</option> </select>""") # Unicode choices are correctly rendered as HTML self.assertEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<select multiple="multiple" name="nums">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>') # Test the usage of _has_changed self.assertFalse(w._has_changed(None, None)) self.assertFalse(w._has_changed([], None)) self.assertTrue(w._has_changed(None, [u'1'])) self.assertFalse(w._has_changed([1, 2], [u'1', u'2'])) self.assertTrue(w._has_changed([1, 2], [u'1'])) self.assertTrue(w._has_changed([1, 2], [u'1', u'3'])) # Choices can be nested one level in order to create HTML optgroups: w.choices = (('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2')))) self.assertEqual(w.render('nestchoice', None), """<select multiple="multiple" name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""") self.assertEqual(w.render('nestchoice', ['outer1']), """<select multiple="multiple" name="nestchoice"> <option value="outer1" selected="selected">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""") self.assertEqual(w.render('nestchoice', ['inner1']), """<select multiple="multiple" name="nestchoice"> <option value="outer1">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1" selected="selected">Inner 1</option> <option value="inner2">Inner 2</option> </optgroup> </select>""") self.assertEqual(w.render('nestchoice', ['outer1', 'inner2']), """<select multiple="multiple" name="nestchoice"> <option value="outer1" selected="selected">Outer 1</option> <optgroup label="Group &quot;1&quot;"> <option value="inner1">Inner 1</option> <option value="inner2" selected="selected">Inner 2</option> </optgroup> </select>""") def test_radioselect(self): w = RadioSelect() self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input checked="checked" type="radio" name="beatle" value="J" /> John</label></li> <li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> <li><label><input type="radio" name="beatle" value="G" /> George</label></li> <li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> </ul>""") # If the value is None, none of the options are checked: self.assertEqual(w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input type="radio" name="beatle" value="J" /> John</label></li> <li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> <li><label><input type="radio" name="beatle" value="G" /> George</label></li> <li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> </ul>""") # If the value corresponds to a label (but not to an option value), none of the options are checked: self.assertEqual(w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input type="radio" name="beatle" value="J" /> John</label></li> <li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> <li><label><input type="radio" name="beatle" value="G" /> George</label></li> <li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> </ul>""") # The value is compared to its str(): self.assertEqual(w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<ul> <li><label><input type="radio" name="num" value="1" /> 1</label></li> <li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> <li><label><input type="radio" name="num" value="3" /> 3</label></li> </ul>""") self.assertEqual(w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]), """<ul> <li><label><input type="radio" name="num" value="1" /> 1</label></li> <li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> <li><label><input type="radio" name="num" value="3" /> 3</label></li> </ul>""") self.assertEqual(w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]), """<ul> <li><label><input type="radio" name="num" value="1" /> 1</label></li> <li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> <li><label><input type="radio" name="num" value="3" /> 3</label></li> </ul>""") # The 'choices' argument can be any iterable: def get_choices(): for i in range(5): yield (i, i) self.assertEqual(w.render('num', 2, choices=get_choices()), """<ul> <li><label><input type="radio" name="num" value="0" /> 0</label></li> <li><label><input type="radio" name="num" value="1" /> 1</label></li> <li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> <li><label><input type="radio" name="num" value="3" /> 3</label></li> <li><label><input type="radio" name="num" value="4" /> 4</label></li> </ul>""") # You can also pass 'choices' to the constructor: w = RadioSelect(choices=[(1, 1), (2, 2), (3, 3)]) self.assertEqual(w.render('num', 2), """<ul> <li><label><input type="radio" name="num" value="1" /> 1</label></li> <li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> <li><label><input type="radio" name="num" value="3" /> 3</label></li> </ul>""") # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: self.assertEqual(w.render('num', 2, choices=[(4, 4), (5, 5)]), """<ul> <li><label><input type="radio" name="num" value="1" /> 1</label></li> <li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> <li><label><input type="radio" name="num" value="3" /> 3</label></li> <li><label><input type="radio" name="num" value="4" /> 4</label></li> <li><label><input type="radio" name="num" value="5" /> 5</label></li> </ul>""") # RadioSelect uses a RadioFieldRenderer to render the individual radio inputs. # You can manipulate that object directly to customize the way the RadioSelect # is rendered. w = RadioSelect() r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) inp_set1 = [] inp_set2 = [] inp_set3 = [] inp_set4 = [] for inp in r: inp_set1.append(str(inp)) inp_set2.append('%s<br />' % inp) inp_set3.append('<p>%s %s</p>' % (inp.tag(), inp.choice_label)) inp_set4.append('%s %s %s %s %s' % (inp.name, inp.value, inp.choice_value, inp.choice_label, inp.is_checked())) self.assertEqual('\n'.join(inp_set1), """<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label> <label><input type="radio" name="beatle" value="P" /> Paul</label> <label><input type="radio" name="beatle" value="G" /> George</label> <label><input type="radio" name="beatle" value="R" /> Ringo</label>""") self.assertEqual('\n'.join(inp_set2), """<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label><br /> <label><input type="radio" name="beatle" value="P" /> Paul</label><br /> <label><input type="radio" name="beatle" value="G" /> George</label><br /> <label><input type="radio" name="beatle" value="R" /> Ringo</label><br />""") self.assertEqual('\n'.join(inp_set3), """<p><input checked="checked" type="radio" name="beatle" value="J" /> John</p> <p><input type="radio" name="beatle" value="P" /> Paul</p> <p><input type="radio" name="beatle" value="G" /> George</p> <p><input type="radio" name="beatle" value="R" /> Ringo</p>""") self.assertEqual('\n'.join(inp_set4), """beatle J J John True beatle J P Paul False beatle J G George False beatle J R Ringo False""") # You can create your own custom renderers for RadioSelect to use. class MyRenderer(RadioFieldRenderer): def render(self): return u'<br />\n'.join([unicode(choice) for choice in self]) w = RadioSelect(renderer=MyRenderer) self.assertEqual(w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br /> <label><input type="radio" name="beatle" value="P" /> Paul</label><br /> <label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> <label><input type="radio" name="beatle" value="R" /> Ringo</label>""") # Or you can use custom RadioSelect fields that use your custom renderer. class CustomRadioSelect(RadioSelect): renderer = MyRenderer w = CustomRadioSelect() self.assertEqual(w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br /> <label><input type="radio" name="beatle" value="P" /> Paul</label><br /> <label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> <label><input type="radio" name="beatle" value="R" /> Ringo</label>""") # A RadioFieldRenderer object also allows index access to individual RadioInput w = RadioSelect() r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) self.assertEqual(str(r[1]), '<label><input type="radio" name="beatle" value="P" /> Paul</label>') self.assertEqual(str(r[0]), '<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>') self.assertTrue(r[0].is_checked()) self.assertFalse(r[1].is_checked()) self.assertEqual((r[1].name, r[1].value, r[1].choice_value, r[1].choice_label), ('beatle', u'J', u'P', u'Paul')) try: r[10] self.fail("This offset should not exist.") except IndexError: pass # Choices are escaped correctly w = RadioSelect() self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; me')))), """<ul> <li><label><input type="radio" name="escape" value="bad" /> you &amp; me</label></li> <li><label><input type="radio" name="escape" value="good" /> you &gt; me</label></li> </ul>""") # Unicode choices are correctly rendered as HTML w = RadioSelect() self.assertEqual(unicode(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])), u'<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>') # Attributes provided at instantiation are passed to the constituent inputs w = RadioSelect(attrs={'id':'foo'}) self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label for="foo_0"><input checked="checked" type="radio" id="foo_0" value="J" name="beatle" /> John</label></li> <li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle" /> Paul</label></li> <li><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle" /> George</label></li> <li><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle" /> Ringo</label></li> </ul>""") # Attributes provided at render-time are passed to the constituent inputs w = RadioSelect() self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')), attrs={'id':'bar'}), """<ul> <li><label for="bar_0"><input checked="checked" type="radio" id="bar_0" value="J" name="beatle" /> John</label></li> <li><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></li> <li><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></li> <li><label for="bar_3"><input type="radio" id="bar_3" value="R" name="beatle" /> Ringo</label></li> </ul>""") def test_checkboxselectmultiple(self): w = CheckboxSelectMultiple() self.assertEqual(w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""") self.assertEqual(w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""") self.assertEqual(w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input checked="checked" type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""") # If the value is None, none of the options are selected: self.assertEqual(w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""") # If the value corresponds to a label (but not to an option value), none of the options are selected: self.assertEqual(w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""") # If multiple values are given, but some of them are not valid, the valid ones are selected: self.assertEqual(w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> <li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input checked="checked" type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""") # The value is compared to its str(): self.assertEqual(w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<ul> <li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> <li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> <li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> </ul>""") self.assertEqual(w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]), """<ul> <li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> <li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> <li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> </ul>""") self.assertEqual(w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]), """<ul> <li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> <li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> <li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> </ul>""") # The 'choices' argument can be any iterable: def get_choices(): for i in range(5): yield (i, i) self.assertEqual(w.render('nums', [2], choices=get_choices()), """<ul> <li><label><input type="checkbox" name="nums" value="0" /> 0</label></li> <li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> <li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> <li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> <li><label><input type="checkbox" name="nums" value="4" /> 4</label></li> </ul>""") # You can also pass 'choices' to the constructor: w = CheckboxSelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) self.assertEqual(w.render('nums', [2]), """<ul> <li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> <li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> <li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> </ul>""") # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: self.assertEqual(w.render('nums', [2], choices=[(4, 4), (5, 5)]), """<ul> <li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> <li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> <li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> <li><label><input type="checkbox" name="nums" value="4" /> 4</label></li> <li><label><input type="checkbox" name="nums" value="5" /> 5</label></li> </ul>""") # Choices are escaped correctly self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; me')))), """<ul> <li><label><input type="checkbox" name="escape" value="1" /> 1</label></li> <li><label><input type="checkbox" name="escape" value="2" /> 2</label></li> <li><label><input type="checkbox" name="escape" value="3" /> 3</label></li> <li><label><input type="checkbox" name="escape" value="bad" /> you &amp; me</label></li> <li><label><input type="checkbox" name="escape" value="good" /> you &gt; me</label></li> </ul>""") # Test the usage of _has_changed self.assertFalse(w._has_changed(None, None)) self.assertFalse(w._has_changed([], None)) self.assertTrue(w._has_changed(None, [u'1'])) self.assertFalse(w._has_changed([1, 2], [u'1', u'2'])) self.assertTrue(w._has_changed([1, 2], [u'1'])) self.assertTrue(w._has_changed([1, 2], [u'1', u'3'])) self.assertFalse(w._has_changed([2, 1], [u'1', u'2'])) # Unicode choices are correctly rendered as HTML self.assertEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<ul>\n<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>\n<li><label><input type="checkbox" name="nums" value="2" /> 2</label></li>\n<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>\n<li><label><input checked="checked" type="checkbox" name="nums" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="checkbox" name="nums" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>') # Each input gets a separate ID self.assertEqual(CheckboxSelectMultiple().render('letters', list('ac'), choices=zip(list('abc'), list('ABC')), attrs={'id': 'abc'}), """<ul> <li><label for="abc_0"><input checked="checked" type="checkbox" name="letters" value="a" id="abc_0" /> A</label></li> <li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1" /> B</label></li> <li><label for="abc_2"><input checked="checked" type="checkbox" name="letters" value="c" id="abc_2" /> C</label></li> </ul>""") def test_multi(self): class MyMultiWidget(MultiWidget): def decompress(self, value): if value: return value.split('__') return ['', ''] def format_output(self, rendered_widgets): return u'<br />'.join(rendered_widgets) w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'}))) self.assertEqual(w.render('name', ['john', 'lennon']), u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />') self.assertEqual(w.render('name', 'john__lennon'), u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />') self.assertEqual(w.render('name', 'john__lennon', attrs={'id':'foo'}), u'<input id="foo_0" type="text" class="big" value="john" name="name_0" /><br /><input id="foo_1" type="text" class="small" value="lennon" name="name_1" />') w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})), attrs={'id': 'bar'}) self.assertEqual(w.render('name', ['john', 'lennon']), u'<input id="bar_0" type="text" class="big" value="john" name="name_0" /><br /><input id="bar_1" type="text" class="small" value="lennon" name="name_1" />') w = MyMultiWidget(widgets=(TextInput(), TextInput())) # test with no initial data self.assertTrue(w._has_changed(None, [u'john', u'lennon'])) # test when the data is the same as initial self.assertFalse(w._has_changed(u'john__lennon', [u'john', u'lennon'])) # test when the first widget's data has changed self.assertTrue(w._has_changed(u'john__lennon', [u'alfred', u'lennon'])) # test when the last widget's data has changed. this ensures that it is not # short circuiting while testing the widgets. self.assertTrue(w._has_changed(u'john__lennon', [u'john', u'denver'])) def test_splitdatetime(self): w = SplitDateTimeWidget() self.assertEqual(w.render('date', ''), u'<input type="text" name="date_0" /><input type="text" name="date_1" />') self.assertEqual(w.render('date', None), u'<input type="text" name="date_0" /><input type="text" name="date_1" />') self.assertEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />') self.assertEqual(w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)]), u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />') # You can also pass 'attrs' to the constructor. In this case, the attrs will be w = SplitDateTimeWidget(attrs={'class': 'pretty'}) self.assertEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" class="pretty" value="2006-01-10" name="date_0" /><input type="text" class="pretty" value="07:30:00" name="date_1" />') # Use 'date_format' and 'time_format' to change the way a value is displayed. w = SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M') self.assertEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" name="date_0" value="10/01/2006" /><input type="text" name="date_1" value="07:30" />') self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'2008-05-06', u'12:40:00'])) self.assertFalse(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:40'])) self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:41'])) def test_datetimeinput(self): w = DateTimeInput() self.assertEqual(w.render('date', None), u'<input type="text" name="date" />') d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) self.assertEqual(str(d), '2007-09-17 12:51:34.482548') # The microseconds are trimmed on display, by default. self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="2007-09-17 12:51:34" />') self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), u'<input type="text" name="date" value="2007-09-17 12:51:34" />') self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="text" name="date" value="2007-09-17 12:51:00" />') # Use 'format' to change the way a value is displayed. w = DateTimeInput(format='%d/%m/%Y %H:%M') self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17/09/2007 12:51" />') self.assertFalse(w._has_changed(d, '17/09/2007 12:51')) # Make sure a custom format works with _has_changed. The hidden input will use data = datetime.datetime(2010, 3, 6, 12, 0, 0) custom_format = '%d.%m.%Y %H:%M' w = DateTimeInput(format=custom_format) self.assertFalse(w._has_changed(formats.localize_input(data), data.strftime(custom_format))) def test_dateinput(self): w = DateInput() self.assertEqual(w.render('date', None), u'<input type="text" name="date" />') d = datetime.date(2007, 9, 17) self.assertEqual(str(d), '2007-09-17') self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="2007-09-17" />') self.assertEqual(w.render('date', datetime.date(2007, 9, 17)), u'<input type="text" name="date" value="2007-09-17" />') # We should be able to initialize from a unicode value. self.assertEqual(w.render('date', u'2007-09-17'), u'<input type="text" name="date" value="2007-09-17" />') # Use 'format' to change the way a value is displayed. w = DateInput(format='%d/%m/%Y') self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17/09/2007" />') self.assertFalse(w._has_changed(d, '17/09/2007')) # Make sure a custom format works with _has_changed. The hidden input will use data = datetime.date(2010, 3, 6) custom_format = '%d.%m.%Y' w = DateInput(format=custom_format) self.assertFalse(w._has_changed(formats.localize_input(data), data.strftime(custom_format))) def test_timeinput(self): w = TimeInput() self.assertEqual(w.render('time', None), u'<input type="text" name="time" />') t = datetime.time(12, 51, 34, 482548) self.assertEqual(str(t), '12:51:34.482548') # The microseconds are trimmed on display, by default. self.assertEqual(w.render('time', t), u'<input type="text" name="time" value="12:51:34" />') self.assertEqual(w.render('time', datetime.time(12, 51, 34)), u'<input type="text" name="time" value="12:51:34" />') self.assertEqual(w.render('time', datetime.time(12, 51)), u'<input type="text" name="time" value="12:51:00" />') # We should be able to initialize from a unicode value. self.assertEqual(w.render('time', u'13:12:11'), u'<input type="text" name="time" value="13:12:11" />') # Use 'format' to change the way a value is displayed. w = TimeInput(format='%H:%M') self.assertEqual(w.render('time', t), u'<input type="text" name="time" value="12:51" />') self.assertFalse(w._has_changed(t, '12:51')) # Make sure a custom format works with _has_changed. The hidden input will use data = datetime.time(13, 0) custom_format = '%I:%M %p' w = TimeInput(format=custom_format) self.assertFalse(w._has_changed(formats.localize_input(data), data.strftime(custom_format))) def test_splithiddendatetime(self): from django.forms.widgets import SplitHiddenDateTimeWidget w = SplitHiddenDateTimeWidget() self.assertEqual(w.render('date', ''), u'<input type="hidden" name="date_0" /><input type="hidden" name="date_1" />') d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) self.assertEqual(str(d), '2007-09-17 12:51:34.482548') self.assertEqual(w.render('date', d), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />') self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />') self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:00" />') class FormsI18NWidgetsTestCase(TestCase): def setUp(self): super(FormsI18NWidgetsTestCase, self).setUp() self.old_use_l10n = getattr(settings, 'USE_L10N', False) settings.USE_L10N = True activate('de-at') def tearDown(self): deactivate() settings.USE_L10N = self.old_use_l10n super(FormsI18NWidgetsTestCase, self).tearDown() def test_splitdatetime(self): w = SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M') self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06.05.2008', u'12:41'])) def test_datetimeinput(self): w = DateTimeInput() d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) w.is_localized = True self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17.09.2007 12:51:34" />') def test_dateinput(self): w = DateInput() d = datetime.date(2007, 9, 17) w.is_localized = True self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17.09.2007" />') def test_timeinput(self): w = TimeInput() t = datetime.time(12, 51, 34, 482548) w.is_localized = True self.assertEqual(w.render('time', t), u'<input type="text" name="time" value="12:51:34" />') def test_splithiddendatetime(self): from django.forms.widgets import SplitHiddenDateTimeWidget w = SplitHiddenDateTimeWidget() w.is_localized = True self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" name="date_1" value="12:51:00" />') class SelectAndTextWidget(MultiWidget): """ MultiWidget subclass """ def __init__(self, choices=[]): widgets = [ RadioSelect(choices=choices), TextInput ] super(SelectAndTextWidget, self).__init__(widgets) def _set_choices(self, choices): """ When choices are set for this widget, we want to pass those along to the Select widget """ self.widgets[0].choices = choices def _get_choices(self): """ The choices for this widget are the Select widget's choices """ return self.widgets[0].choices choices = property(_get_choices, _set_choices) class WidgetTests(TestCase): def test_12048(self): # See ticket #12048. w1 = SelectAndTextWidget(choices=[1,2,3]) w2 = copy.deepcopy(w1) w2.choices = [4,5,6] # w2 ought to be independent of w1, since MultiWidget ought # to make a copy of its sub-widgets when it is copied. self.assertEqual(w1.choices, [1,2,3]) def test_13390(self): # See ticket #13390 class SplitDateForm(Form): field = DateTimeField(widget=SplitDateTimeWidget, required=False) form = SplitDateForm({'field': ''}) self.assertTrue(form.is_valid()) form = SplitDateForm({'field': ['', '']}) self.assertTrue(form.is_valid()) class SplitDateRequiredForm(Form): field = DateTimeField(widget=SplitDateTimeWidget, required=True) form = SplitDateRequiredForm({'field': ''}) self.assertFalse(form.is_valid()) form = SplitDateRequiredForm({'field': ['', '']}) self.assertFalse(form.is_valid()) class FakeFieldFile(object): """ Quacks like a FieldFile (has a .url and unicode representation), but doesn't require us to care about storages etc. """ url = 'something' def __unicode__(self): return self.url class ClearableFileInputTests(TestCase): def test_clear_input_renders(self): """ A ClearableFileInput with is_required False and rendered with an initial value that is a file renders a clear checkbox. """ widget = ClearableFileInput() widget.is_required = False self.assertEqual(widget.render('myfile', FakeFieldFile()), u'Currently: <a href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> <label for="myfile-clear_id">Clear</label><br />Change: <input type="file" name="myfile" />') def test_html_escaped(self): """ A ClearableFileInput should escape name, filename and URL when rendering HTML. Refs #15182. """ class StrangeFieldFile(object): url = "something?chapter=1&sect=2&copy=3&lang=en" def __unicode__(self): return u'''something<div onclick="alert('oops')">.jpg''' widget = ClearableFileInput() field = StrangeFieldFile() output = widget.render('my<div>file', field) self.assertFalse(field.url in output) self.assertTrue(u'href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"' in output) self.assertFalse(unicode(field) in output) self.assertTrue(u'something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg' in output) self.assertTrue(u'my&lt;div&gt;file' in output) self.assertFalse(u'my<div>file' in output) def test_clear_input_renders_only_if_not_required(self): """ A ClearableFileInput with is_required=False does not render a clear checkbox. """ widget = ClearableFileInput() widget.is_required = True self.assertEqual(widget.render('myfile', FakeFieldFile()), u'Currently: <a href="something">something</a> <br />Change: <input type="file" name="myfile" />') def test_clear_input_renders_only_if_initial(self): """ A ClearableFileInput instantiated with no initial value does not render a clear checkbox. """ widget = ClearableFileInput() widget.is_required = False self.assertEqual(widget.render('myfile', None), u'<input type="file" name="myfile" />') def test_clear_input_checked_returns_false(self): """ ClearableFileInput.value_from_datadict returns False if the clear checkbox is checked, if not required. """ widget = ClearableFileInput() widget.is_required = False self.assertEqual(widget.value_from_datadict( data={'myfile-clear': True}, files={}, name='myfile'), False) def test_clear_input_checked_returns_false_only_if_not_required(self): """ ClearableFileInput.value_from_datadict never returns False if the field is required. """ widget = ClearableFileInput() widget.is_required = True f = SimpleUploadedFile('something.txt', 'content') self.assertEqual(widget.value_from_datadict( data={'myfile-clear': True}, files={'myfile': f}, name='myfile'), f)
67,270
Python
.py
991
61.279516
671
0.628594
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,917
fields.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/fields.py
# -*- coding: utf-8 -*- """ ########## # Fields # ########## Each Field class does some sort of validation. Each Field has a clean() method, which either raises django.forms.ValidationError or returns the "clean" data -- usually a Unicode object, but, in some rare cases, a list. Each Field's __init__() takes at least these parameters: required -- Boolean that specifies whether the field is required. True by default. widget -- A Widget class, or instance of a Widget class, that should be used for this Field when displaying it. Each Field has a default Widget that it'll use if you don't specify this. In most cases, the default widget is TextInput. label -- A verbose name for this field, for use in displaying this field in a form. By default, Django will use a "pretty" version of the form field name, if the Field is part of a Form. initial -- A value to use in this Field's initial display. This value is *not* used as a fallback if data isn't given. Other than that, the Field subclasses have class-specific options for __init__(). For example, CharField has a max_length option. """ import datetime import time import re import os import urllib2 from decimal import Decimal from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import * from django.forms.widgets import RadioFieldRenderer from django.utils.unittest import TestCase def fix_os_paths(x): if isinstance(x, basestring): return x.replace('\\', '/') elif isinstance(x, tuple): return tuple(fix_os_paths(list(x))) elif isinstance(x, list): return [fix_os_paths(y) for y in x] else: return x class FieldsTests(TestCase): def assertRaisesErrorWithMessage(self, error, message, callable, *args, **kwargs): self.assertRaises(error, callable, *args, **kwargs) try: callable(*args, **kwargs) except error, e: self.assertEqual(message, str(e)) def test_field_sets_widget_is_required(self): self.assertTrue(Field(required=True).widget.is_required) self.assertFalse(Field(required=False).widget.is_required) # CharField ################################################################### def test_charfield_1(self): f = CharField() self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'hello', f.clean('hello')) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, None) def test_charfield_2(self): f = CharField(required=False) self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'hello', f.clean('hello')) self.assertEqual(u'', f.clean(None)) self.assertEqual(u'', f.clean('')) self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, None) def test_charfield_3(self): f = CharField(max_length=10, required=False) self.assertEqual(u'12345', f.clean('12345')) self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '1234567890a') self.assertEqual(f.max_length, 10) self.assertEqual(f.min_length, None) def test_charfield_4(self): f = CharField(min_length=10, required=False) self.assertEqual(u'', f.clean('')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertEqual(u'1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, 10) def test_charfield_5(self): f = CharField(min_length=10, required=True) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertEqual(u'1234567890a', f.clean('1234567890a')) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, 10) # IntegerField ################################################################ def test_integerfield_1(self): f = IntegerField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(1, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(23, f.clean('23')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a') self.assertEqual(42, f.clean(42)) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 3.14) self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_integerfield_2(self): f = IntegerField(required=False) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(1, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(23, f.clean('23')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a') self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_integerfield_3(self): f = IntegerField(max_value=10) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(1, f.clean(1)) self.assertEqual(10, f.clean(10)) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, 11) self.assertEqual(10, f.clean('10')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, '11') self.assertEqual(f.max_value, 10) self.assertEqual(f.min_value, None) def test_integerfield_4(self): f = IntegerField(min_value=10) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, 10) def test_integerfield_5(self): f = IntegerField(min_value=10, max_value=20) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertEqual(20, f.clean(20)) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 20.']", f.clean, 21) self.assertEqual(f.max_value, 20) self.assertEqual(f.min_value, 10) # FloatField ################################################################## def test_floatfield_1(self): f = FloatField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(1.0, f.clean('1')) self.assertEqual(True, isinstance(f.clean('1'), float)) self.assertEqual(23.0, f.clean('23')) self.assertEqual(3.1400000000000001, f.clean('3.14')) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a') self.assertEqual(1.0, f.clean('1.0 ')) self.assertEqual(1.0, f.clean(' 1.0')) self.assertEqual(1.0, f.clean(' 1.0 ')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_floatfield_2(self): f = FloatField(required=False) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean(None)) self.assertEqual(1.0, f.clean('1')) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) self.assertEqual(f.min_value, 0.5) # DecimalField ################################################################ def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(f.clean('1'), Decimal("1")) self.assertEqual(True, isinstance(f.clean('1'), Decimal)) self.assertEqual(f.clean('23'), Decimal("23")) self.assertEqual(f.clean('3.14'), Decimal("3.14")) self.assertEqual(f.clean(3.14), Decimal("3.14")) self.assertEqual(f.clean(Decimal('3.14')), Decimal("3.14")) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'NaN') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'Inf') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '-Inf') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, u'łąść') self.assertEqual(f.clean('1.0 '), Decimal("1.0")) self.assertEqual(f.clean(' 1.0'), Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), Decimal("1.0")) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '123.45') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '1.234') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 digits before the decimal point.']", f.clean, '123.4') self.assertEqual(f.clean('-12.34'), Decimal("-12.34")) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-123.45') self.assertEqual(f.clean('-.12'), Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), Decimal("-0.12")) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '-000.123') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-000.12345') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '--0.12') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_decimalfield_2(self): f = DecimalField(max_digits=4, decimal_places=2, required=False) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean(None)) self.assertEqual(f.clean('1'), Decimal("1")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_decimalfield_3(self): f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') self.assertEqual(f.clean('1.5'), Decimal("1.5")) self.assertEqual(f.clean('0.5'), Decimal("0.5")) self.assertEqual(f.clean('.5'), Decimal("0.5")) self.assertEqual(f.clean('00.50'), Decimal("0.50")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, Decimal('1.5')) self.assertEqual(f.min_value, Decimal('0.5')) def test_decimalfield_4(self): f = DecimalField(decimal_places=2) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '0.00000001') def test_decimalfield_5(self): f = DecimalField(max_digits=3) # Leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('0000000.10'), Decimal("0.1")) # But a leading 0 before the . doesn't count towards max_digits self.assertEqual(f.clean('0000000.100'), Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('000000.02'), Decimal('0.02')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 3 digits in total.']", f.clean, '000000.0002') self.assertEqual(f.clean('.002'), Decimal("0.002")) def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), Decimal(".01")) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 0 digits before the decimal point.']", f.clean, '1.1') # DateField ################################################################### def test_datefield_1(self): f = DateField() self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006-10-25')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('10/25/2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('10/25/06')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('Oct 25 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25, 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October, 2006')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-4-31') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '200a-10-25') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '25/10/06') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) def test_datefield_2(self): f = DateField(required=False) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) def test_datefield_3(self): f = DateField(input_formats=['%Y %m %d']) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006 10 25')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-10-25') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/2006') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/06') # TimeField ################################################################### def test_timefield_1(self): f = TimeField() self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14, 25), f.clean('14:25')) self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, 'hello') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '1:24 p.m.') def test_timefield_2(self): f = TimeField(input_formats=['%I:%M %p']) self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM')) self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '14:30:45') # DateTimeField ############################################################### def test_datetimefield_1(self): f = DateTimeField() self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('2006-10-25 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('2006-10-25')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/2006 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/2006')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/06 14:30:45')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, 'hello') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 4:30 p.m.') def test_datetimefield_2(self): f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 14:30:45') def test_datetimefield_3(self): f = DateTimeField(required=False) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) # RegexField ################################################################## def test_regexfield_1(self): f = RegexField('^\d[A-F]\d$') self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'3F3', f.clean('3F3')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') def test_regexfield_2(self): f = RegexField('^\d[A-F]\d$', required=False) self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'3F3', f.clean('3F3')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') self.assertEqual(u'', f.clean('')) def test_regexfield_3(self): f = RegexField(re.compile('^\d[A-F]\d$')) self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'3F3', f.clean('3F3')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') def test_regexfield_4(self): f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.') self.assertEqual(u'1234', f.clean('1234')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, '123') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, 'abcd') def test_regexfield_5(self): f = RegexField('^\d+$', min_length=5, max_length=10) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).']", f.clean, '123') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).', u'Enter a valid value.']", f.clean, 'abc') self.assertEqual(u'12345', f.clean('12345')) self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a') # EmailField ################################################################## def test_emailfield_1(self): f = EmailField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(u'[email protected]', f.clean('[email protected]')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, '[email protected]') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, '[email protected]') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, '[email protected]') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, '[email protected]') self.assertEqual(u'[email protected]', f.clean('[email protected]')) self.assertEqual(u'[email protected]', f.clean('[email protected]')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, '[email protected]') self.assertEqual(u'[email protected]\xe4\xf6\xfc\xdfabc.part.com', f.clean('[email protected]äöüßabc.part.com')) def test_email_regexp_for_performance(self): f = EmailField() # Check for runaway regex security problem. This will take for-freeking-ever # if the security fix isn't in place. self.assertRaisesErrorWithMessage( ValidationError, "[u'Enter a valid e-mail address.']", f.clean, '[email protected]' ) def test_emailfield_2(self): f = EmailField(required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(None)) self.assertEqual(u'[email protected]', f.clean('[email protected]')) self.assertEqual(u'[email protected]', f.clean(' [email protected] \t \t ')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar') def test_emailfield_3(self): f = EmailField(min_length=10, max_length=15) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 9).']", f.clean, '[email protected]') self.assertEqual(u'[email protected]', f.clean('[email protected]')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 15 characters (it has 20).']", f.clean, '[email protected]') # FileField ################################################################## def test_filefield_1(self): f = FileField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '', '') self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None, '') self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', '')) self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', ''), '') self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, 'some content that is not a file') self.assertRaisesErrorWithMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', None)) self.assertRaisesErrorWithMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', '')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content')))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf'))) def test_filefield_2(self): f = FileField(max_length = 5) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', 'hello world')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content')))) # URLField ################################################################## def test_urlfield_1(self): f = URLField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(u'http://localhost/', f.clean('http://localhost')) self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertEqual(u'http://example.com./', f.clean('http://example.com.')) self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com')) self.assertEqual(u'http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test')) self.assertEqual(u'http://valid-with-hyphens.com/', f.clean('valid-with-hyphens.com')) self.assertEqual(u'http://subdomain.domain.com/', f.clean('subdomain.domain.com')) self.assertEqual(u'http://200.8.9.10/', f.clean('http://200.8.9.10')) self.assertEqual(u'http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'com.') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, '.') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://invalid-.com') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://-invalid.com') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.alid-.com') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.-alid.com') self.assertEqual(u'http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com')) self.assertEqual(u'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) self.assertEqual(u'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')) def test_url_regex_ticket11198(self): f = URLField() # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*200,)) # a second test, to make sure the problem is really addressed, even on # domains that don't fail the domain label length check in the regex self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*60,)) def test_urlfield_2(self): f = URLField(required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(None)) self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com') def test_urlfield_3(self): f = URLField(verify_exists=True) self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com')) # This will fail if there's no Internet connection self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') self.assertRaises(ValidationError, f.clean, 'http://www.broken.djangoproject.com') # bad domain self.assertRaises(ValidationError, f.clean, 'http://qa-dev.w3.org/link-testsuite/http.php?code=405') # Method not allowed try: f.clean('http://www.broken.djangoproject.com') # bad domain except ValidationError, e: self.assertEqual("[u'This URL appears to be a broken link.']", str(e)) self.assertRaises(ValidationError, f.clean, 'http://google.com/we-love-microsoft.html') # good domain, bad page try: f.clean('http://google.com/we-love-microsoft.html') # good domain, bad page except ValidationError, e: self.assertEqual("[u'This URL appears to be a broken link.']", str(e)) def test_urlfield_4(self): f = URLField(verify_exists=True, required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com')) # This will fail if there's no Internet connection def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 15 characters (it has 13).']", f.clean, 'http://f.com') self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 38).']", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com') def test_urlfield_6(self): f = URLField(required=False) self.assertEqual(u'http://example.com/', f.clean('example.com')) self.assertEqual(u'', f.clean('')) self.assertEqual(u'https://example.com/', f.clean('https://example.com')) def test_urlfield_7(self): f = URLField() self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertEqual(u'http://example.com/test', f.clean('http://example.com/test')) def test_urlfield_8(self): # ticket #11826 f = URLField() self.assertEqual(u'http://example.com/?some_param=some_value', f.clean('http://example.com?some_param=some_value')) def test_urlfield_9(self): f = URLField(verify_exists=False) urls = ( u'http://עברית.idn.icann.org/', u'http://sãopaulo.com/', u'http://sãopaulo.com.br/', u'http://пример.испытание/', u'http://مثال.إختبار/', u'http://例子.测试/', u'http://例子.測試/', u'http://उदाहरण.परीक्षा/', u'http://例え.テスト/', u'http://مثال.آزمایشی/', u'http://실례.테스트/', u'http://العربية.idn.icann.org/', ) for url in urls: # Valid and existent IDN self.assertEqual(url, f.clean(url)) # Valid but non-existent IDN try: f.clean(u'http://broken.עברית.idn.icann.org/') except ValidationError, e: self.assertEqual("[u'This URL appears to be a broken link.']", str(e)) def test_urlfield_10(self): # UTF-8 char in path, enclosed by a monkey-patch to make sure # the encoding is passed to urllib2.urlopen f = URLField(verify_exists=True) try: _orig_urlopen = urllib2.urlopen urllib2.urlopen = lambda req: True url = u'http://t\xfcr.djangoproject.com/' self.assertEqual(url, f.clean(url)) finally: urllib2.urlopen = _orig_urlopen # BooleanField ################################################################ def test_booleanfield_1(self): f = BooleanField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(True, f.clean(True)) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, False) self.assertEqual(True, f.clean(1)) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, 0) self.assertEqual(True, f.clean('Django rocks')) self.assertEqual(True, f.clean('True')) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, 'False') def test_booleanfield_2(self): f = BooleanField(required=False) self.assertEqual(False, f.clean('')) self.assertEqual(False, f.clean(None)) self.assertEqual(True, f.clean(True)) self.assertEqual(False, f.clean(False)) self.assertEqual(True, f.clean(1)) self.assertEqual(False, f.clean(0)) self.assertEqual(True, f.clean('1')) self.assertEqual(False, f.clean('0')) self.assertEqual(True, f.clean('Django rocks')) self.assertEqual(False, f.clean('False')) # ChoiceField ################################################################# def test_choicefield_1(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'1', f.clean('1')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') def test_choicefield_2(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(None)) self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'1', f.clean('1')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') def test_choicefield_3(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) self.assertEqual(u'J', f.clean('J')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. John is not one of the available choices.']", f.clean, 'John') def test_choicefield_4(self): f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'1', f.clean('1')) self.assertEqual(u'3', f.clean(3)) self.assertEqual(u'3', f.clean('3')) self.assertEqual(u'5', f.clean(5)) self.assertEqual(u'5', f.clean('5')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, '6') # TypedChoiceField ############################################################ # TypedChoiceField is just like ChoiceField, except that coerced types will # be returned: def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, '2') def test_typedchoicefield_2(self): # Different coercion, same validation. f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual(1.0, f.clean('1')) def test_typedchoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertEqual(True, f.clean('-1')) def test_typedchoicefield_4(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, 'B') # Required fields require values self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') def test_typedchoicefield_5(self): # Non-required fields aren't required f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual('', f.clean('')) # If you want cleaning an empty value to return a different type, tell the field def test_typedchoicefield_6(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertEqual(None, f.clean('')) # NullBooleanField ############################################################ def test_nullbooleanfield_1(self): f = NullBooleanField() self.assertEqual(None, f.clean('')) self.assertEqual(True, f.clean(True)) self.assertEqual(False, f.clean(False)) self.assertEqual(None, f.clean(None)) self.assertEqual(False, f.clean('0')) self.assertEqual(True, f.clean('1')) self.assertEqual(None, f.clean('2')) self.assertEqual(None, f.clean('3')) self.assertEqual(None, f.clean('hello')) def test_nullbooleanfield_2(self): # Make sure that the internal value is preserved if using HiddenInput (#7753) class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) f = HiddenNullBooleanForm() self.assertEqual('<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" /><input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />', str(f)) def test_nullbooleanfield_3(self): class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) f = HiddenNullBooleanForm({ 'hidden_nullbool1': 'True', 'hidden_nullbool2': 'False' }) self.assertEqual(None, f.full_clean()) self.assertEqual(True, f.cleaned_data['hidden_nullbool1']) self.assertEqual(False, f.cleaned_data['hidden_nullbool2']) def test_nullbooleanfield_4(self): # Make sure we're compatible with MySQL, which uses 0 and 1 for its boolean # values. (#9609) NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown')) class MySQLNullBooleanForm(Form): nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool1 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) nullbool2 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES)) f = MySQLNullBooleanForm({ 'nullbool0': '1', 'nullbool1': '0', 'nullbool2': '' }) self.assertEqual(None, f.full_clean()) self.assertEqual(True, f.cleaned_data['nullbool0']) self.assertEqual(False, f.cleaned_data['nullbool1']) self.assertEqual(None, f.cleaned_data['nullbool2']) # MultipleChoiceField ######################################################### def test_multiplechoicefield_1(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual([u'1'], f.clean([1])) self.assertEqual([u'1'], f.clean(['1'])) self.assertEqual([u'1', u'2'], f.clean(['1', '2'])) self.assertEqual([u'1', u'2'], f.clean([1, '2'])) self.assertEqual([u'1', u'2'], f.clean((1, '2'))) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, []) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, ()) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) def test_multiplechoicefield_2(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual([], f.clean('')) self.assertEqual([], f.clean(None)) self.assertEqual([u'1'], f.clean([1])) self.assertEqual([u'1'], f.clean(['1'])) self.assertEqual([u'1', u'2'], f.clean(['1', '2'])) self.assertEqual([u'1', u'2'], f.clean([1, '2'])) self.assertEqual([u'1', u'2'], f.clean((1, '2'))) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertEqual([], f.clean([])) self.assertEqual([], f.clean(())) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) def test_multiplechoicefield_3(self): f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) self.assertEqual([u'1'], f.clean([1])) self.assertEqual([u'1'], f.clean(['1'])) self.assertEqual([u'1', u'5'], f.clean([1, 5])) self.assertEqual([u'1', u'5'], f.clean([1, '5'])) self.assertEqual([u'1', u'5'], f.clean(['1', 5])) self.assertEqual([u'1', u'5'], f.clean(['1', '5'])) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['6']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['1','6']) # TypedMultipleChoiceField ############################################################ # TypedMultipleChoiceField is just like MultipleChoiceField, except that coerced types # will be returned: def test_typedmultiplechoicefield_1(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1], f.clean(['1'])) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['2']) def test_typedmultiplechoicefield_2(self): # Different coercion, same validation. f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual([1.0], f.clean(['1'])) def test_typedmultiplechoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertEqual([True], f.clean(['-1'])) def test_typedmultiplechoicefield_4(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1, -1], f.clean(['1','-1'])) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['1','2']) def test_typedmultiplechoicefield_5(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, ['B']) # Required fields require values self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, []) def test_typedmultiplechoicefield_6(self): # Non-required fields aren't required f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual([], f.clean([])) def test_typedmultiplechoicefield_7(self): # If you want cleaning an empty value to return a different type, tell the field f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertEqual(None, f.clean([])) # ComboField ################################################################## def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) self.assertEqual(u'[email protected]', f.clean('[email protected]')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, '[email protected]') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) def test_combofield_2(self): f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) self.assertEqual(u'[email protected]', f.clean('[email protected]')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, '[email protected]') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail') self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(None)) # FilePathField ############################################################### def test_filepathfield_1(self): path = os.path.abspath(forms.__file__) path = os.path.dirname(path) + '/' self.assertTrue(fix_os_paths(path).endswith('/django/forms/')) def test_filepathfield_2(self): path = forms.__file__ path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path) f.choices = [p for p in f.choices if p[0].endswith('.py')] f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/util.py', 'util.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. fields.py is not one of the available choices.']", f.clean, 'fields.py') assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py') def test_filepathfield_3(self): path = forms.__file__ path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path, match='^.*?\.py$') f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/util.py', 'util.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) def test_filepathfield_4(self): path = os.path.abspath(forms.__file__) path = os.path.dirname(path) + '/' f = FilePathField(path=path, recursive=True, match='^.*?\.py$') f.choices.sort() expected = [ ('/django/forms/__init__.py', '__init__.py'), ('/django/forms/extras/__init__.py', 'extras/__init__.py'), ('/django/forms/extras/widgets.py', 'extras/widgets.py'), ('/django/forms/fields.py', 'fields.py'), ('/django/forms/forms.py', 'forms.py'), ('/django/forms/formsets.py', 'formsets.py'), ('/django/forms/models.py', 'models.py'), ('/django/forms/util.py', 'util.py'), ('/django/forms/widgets.py', 'widgets.py') ] for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) # SplitDateTimeField ########################################################## def test_splitdatetimefield_1(self): from django.forms.widgets import SplitDateTimeWidget f = SplitDateTimeField() assert isinstance(f.widget, SplitDateTimeWidget) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30']) def test_splitdatetimefield_2(self): f = SplitDateTimeField(required=False) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean(['2006-01-10', '07:30'])) self.assertEqual(None, f.clean(None)) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean([''])) self.assertEqual(None, f.clean(['', ''])) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', '']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['', '07:30'])
59,519
Python
.py
863
59.849363
207
0.640139
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,918
forms.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/forms.py
# -*- coding: utf-8 -*- import datetime from decimal import Decimal import re import time from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import * from django.http import QueryDict from django.template import Template, Context from django.utils.datastructures import MultiValueDict, MergeDict from django.utils.safestring import mark_safe from django.utils.unittest import TestCase class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class PersonNew(Form): first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'})) last_name = CharField() birthday = DateField() class FormsTestCase(TestCase): # A Form is a collection of Fields. It knows how to validate a set of data and it # knows how to render itself in a couple of default ways (e.g., an HTML table). # You can pass it data in __init__(), as a dictionary. def test_form(self): # Pass a dictionary to a Form's __init__(). p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'}) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.errors.as_ul(), u'') self.assertEqual(p.errors.as_text(), u'') self.assertEqual(p.cleaned_data["first_name"], u'John') self.assertEqual(p.cleaned_data["last_name"], u'Lennon') self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />') self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />') self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />') try: p['nonexistentfield'] self.fail('Attempts to access non-existent fields should fail.') except KeyError: pass form_output = [] for boundfield in p: form_output.append(str(boundfield)) self.assertEqual('\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" /> <input type="text" name="last_name" value="Lennon" id="id_last_name" /> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" />""") form_output = [] for boundfield in p: form_output.append([boundfield.label, boundfield.data]) self.assertEqual(form_output, [ ['First name', u'John'], ['Last name', u'Lennon'], ['Birthday', u'1940-10-9'] ]) self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>""") def test_empty_dict(self): # Empty dictionaries are valid, too. p = Person({}) self.assertTrue(p.is_bound) self.assertEqual(p.errors['first_name'], [u'This field is required.']) self.assertEqual(p.errors['last_name'], [u'This field is required.']) self.assertEqual(p.errors['birthday'], [u'This field is required.']) self.assertFalse(p.is_valid()) try: p.cleaned_data self.fail('Attempts to access cleaned_data when validation fails should fail.') except AttributeError: pass self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""") self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""") self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""") self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""") def test_unbound_form(self): # If you don't pass any values to the Form's __init__(), or if you pass None, # the Form will be considered unbound and won't do any validation. Form.errors # will be an empty dictionary *but* Form.is_valid() will return False. p = Person() self.assertFalse(p.is_bound) self.assertEqual(p.errors, {}) self.assertFalse(p.is_valid()) try: p.cleaned_data self.fail('Attempts to access cleaned_data when validation fails should fail.') except AttributeError: pass self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""") self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""") self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""") self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""") def test_unicode_values(self): # Unicode values are handled properly. p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'}) self.assertEqual(p.as_table(), u'<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>') self.assertEqual(p.as_ul(), u'<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>') self.assertEqual(p.as_p(), u'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>') p = Person({'last_name': u'Lennon'}) self.assertEqual(p.errors['first_name'], [u'This field is required.']) self.assertEqual(p.errors['birthday'], [u'This field is required.']) self.assertFalse(p.is_valid()) self.assertEqual(p.errors.as_ul(), u'<ul class="errorlist"><li>first_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>birthday<ul class="errorlist"><li>This field is required.</li></ul></li></ul>') self.assertEqual(p.errors.as_text(), """* first_name * This field is required. * birthday * This field is required.""") try: p.cleaned_data self.fail('Attempts to access cleaned_data when validation fails should fail.') except AttributeError: pass self.assertEqual(p['first_name'].errors, [u'This field is required.']) self.assertEqual(p['first_name'].errors.as_ul(), u'<ul class="errorlist"><li>This field is required.</li></ul>') self.assertEqual(p['first_name'].errors.as_text(), u'* This field is required.') p = Person() self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" />') self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" />') self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" />') def test_cleaned_data_only_fields(self): # cleaned_data will always *only* contain a key for fields defined in the # Form, even if you pass extra data when you define the Form. In this # example, we pass a bunch of extra fields to the form constructor, # but cleaned_data contains only the form's fields. data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'} p = Person(data) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], u'John') self.assertEqual(p.cleaned_data['last_name'], u'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) def test_optional_data(self): # cleaned_data will include a key and value for *all* fields defined in the Form, # even if the Form's data didn't include a value for fields that are not # required. In this example, the data dictionary doesn't include a value for the # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the # empty string. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() nick_name = CharField(required=False) data = {'first_name': u'John', 'last_name': u'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['nick_name'], u'') self.assertEqual(f.cleaned_data['first_name'], u'John') self.assertEqual(f.cleaned_data['last_name'], u'Lennon') # For DateFields, it's set to None. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() birth_date = DateField(required=False) data = {'first_name': u'John', 'last_name': u'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['birth_date'], None) self.assertEqual(f.cleaned_data['first_name'], u'John') self.assertEqual(f.cleaned_data['last_name'], u'Lennon') def test_auto_id(self): # "auto_id" tells the Form to add an "id" attribute to each form element. # If it's a string that contains '%s', Django will use that as a format string # into which the field's name will be inserted. It will also put a <label> around # the human-readable labels for a field. p = Person(auto_id='%s_id') self.assertEqual(p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td><input type="text" name="first_name" id="first_name_id" /></td></tr> <tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr> <tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>""") self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></li> <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li> <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>""") self.assertEqual(p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></p> <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p> <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>""") def test_auto_id_true(self): # If auto_id is any True value whose str() does not contain '%s', the "id" # attribute will be the name of the field. p = Person(auto_id=True) self.assertEqual(p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""") def test_auto_id_false(self): # If auto_id is any False value, an "id" attribute won't be output unless it # was manually entered. p = Person(auto_id=False) self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> <li>Last name: <input type="text" name="last_name" /></li> <li>Birthday: <input type="text" name="birthday" /></li>""") def test_id_on_field(self): # In this example, auto_id is False, but the "id" attribute for the "first_name" # field is given. Also note that field gets a <label>, while the others don't. p = PersonNew(auto_id=False) self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li> <li>Last name: <input type="text" name="last_name" /></li> <li>Birthday: <input type="text" name="birthday" /></li>""") def test_auto_id_on_form_and_field(self): # If the "id" attribute is specified in the Form and auto_id is True, the "id" # attribute in the Form gets precedence. p = PersonNew(auto_id=True) self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""") def test_various_boolean_values(self): class SignupForm(Form): email = EmailField() get_spam = BooleanField() f = SignupForm(auto_id=False) self.assertEqual(str(f['email']), '<input type="text" name="email" />') self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />') f = SignupForm({'email': '[email protected]', 'get_spam': True}, auto_id=False) self.assertEqual(str(f['email']), '<input type="text" name="email" value="[email protected]" />') self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />') # 'True' or 'true' should be rendered without a value attribute f = SignupForm({'email': '[email protected]', 'get_spam': 'True'}, auto_id=False) self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />') f = SignupForm({'email': '[email protected]', 'get_spam': 'true'}, auto_id=False) self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />') # A value of 'False' or 'false' should be rendered unchecked f = SignupForm({'email': '[email protected]', 'get_spam': 'False'}, auto_id=False) self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />') f = SignupForm({'email': '[email protected]', 'get_spam': 'false'}, auto_id=False) self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />') def test_widget_output(self): # Any Field can have a Widget class passed to its constructor: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea) f = ContactForm(auto_id=False) self.assertEqual(str(f['subject']), '<input type="text" name="subject" />') self.assertEqual(str(f['message']), '<textarea rows="10" cols="40" name="message"></textarea>') # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject"></textarea>') self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />') self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" />') # The 'widget' parameter to a Field can also be an instance: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20})) f = ContactForm(auto_id=False) self.assertEqual(str(f['message']), '<textarea rows="80" cols="20" name="message"></textarea>') # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />') f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False) self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject">Hello</textarea>') self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" value="I love you." />') self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" value="I love you." />') def test_forms_with_choices(self): # For a form with a <select>, use ChoiceField: class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) f = FrameworkForm(auto_id=False) self.assertEqual(str(f['language']), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) self.assertEqual(str(f['language']), """<select name="language"> <option value="P" selected="selected">Python</option> <option value="J">Java</option> </select>""") # A subtlety: If one of the choices' value is the empty string and the form is # unbound, then the <option> for the empty-string choice will get selected="selected". class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')]) f = FrameworkForm(auto_id=False) self.assertEqual(str(f['language']), """<select name="language"> <option value="" selected="selected">------</option> <option value="P">Python</option> <option value="J">Java</option> </select>""") # You can specify widget attributes in the Widget constructor. class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'})) f = FrameworkForm(auto_id=False) self.assertEqual(str(f['language']), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) self.assertEqual(str(f['language']), """<select class="foo" name="language"> <option value="P" selected="selected">Python</option> <option value="J">Java</option> </select>""") # When passing a custom widget instance to ChoiceField, note that setting # 'choices' on the widget is meaningless. The widget will use the choices # defined on the Field, not the ones defined on the Widget. class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'})) f = FrameworkForm(auto_id=False) self.assertEqual(str(f['language']), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) self.assertEqual(str(f['language']), """<select class="foo" name="language"> <option value="P" selected="selected">Python</option> <option value="J">Java</option> </select>""") # You can set a ChoiceField's choices after the fact. class FrameworkForm(Form): name = CharField() language = ChoiceField() f = FrameworkForm(auto_id=False) self.assertEqual(str(f['language']), """<select name="language"> </select>""") f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] self.assertEqual(str(f['language']), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""") def test_forms_with_radio(self): # Add widget=RadioSelect to use that widget with a ChoiceField. class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect) f = FrameworkForm(auto_id=False) self.assertEqual(str(f['language']), """<ul> <li><label><input type="radio" name="language" value="P" /> Python</label></li> <li><label><input type="radio" name="language" value="J" /> Java</label></li> </ul>""") self.assertEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" /></td></tr> <tr><th>Language:</th><td><ul> <li><label><input type="radio" name="language" value="P" /> Python</label></li> <li><label><input type="radio" name="language" value="J" /> Java</label></li> </ul></td></tr>""") self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" /></li> <li>Language: <ul> <li><label><input type="radio" name="language" value="P" /> Python</label></li> <li><label><input type="radio" name="language" value="J" /> Java</label></li> </ul></li>""") # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button # gets a distinct ID, formed by appending an underscore plus the button's # zero-based index. f = FrameworkForm(auto_id='id_%s') self.assertEqual(str(f['language']), """<ul> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> </ul>""") # When RadioSelect is used with auto_id, and the whole form is printed using # either as_table() or as_ul(), the label for the RadioSelect will point to the # ID of the *first* radio button. self.assertEqual(f.as_table(), """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr> <tr><th><label for="id_language_0">Language:</label></th><td><ul> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> </ul></td></tr>""") self.assertEqual(f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li> <li><label for="id_language_0">Language:</label> <ul> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> </ul></li>""") self.assertEqual(f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p> <p><label for="id_language_0">Language:</label> <ul> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> </ul></p>""") def test_forms_wit_hmultiple_choice(self): # MultipleChoiceField is a special case, as its data is required to be a list: class SongForm(Form): name = CharField() composers = MultipleChoiceField() f = SongForm(auto_id=False) self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers"> </select>""") class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) f = SongForm(auto_id=False) self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers"> <option value="J">John Lennon</option> <option value="P">Paul McCartney</option> </select>""") f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) self.assertEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" />') self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers"> <option value="J">John Lennon</option> <option value="P" selected="selected">Paul McCartney</option> </select>""") def test_hidden_data(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) # MultipleChoiceField rendered as_hidden() is a special case. Because it can # have multiple values, its as_hidden() renders multiple <input type="hidden"> # tags. f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) self.assertEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />') f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False) self.assertEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" /> <input type="hidden" name="composers" value="J" />""") # DateTimeField rendered as_hidden() is special too class MessageForm(Form): when = SplitDateTimeField() f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'}) self.assertTrue(f.is_valid()) self.assertEqual(str(f['when']), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" /><input type="text" name="when_1" value="01:01" id="id_when_1" />') self.assertEqual(f['when'].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" /><input type="hidden" name="when_1" value="01:01" id="id_when_1" />') def test_mulitple_choice_checkbox(self): # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) f = SongForm(auto_id=False) self.assertEqual(str(f['composers']), """<ul> <li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li> <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> </ul>""") f = SongForm({'composers': ['J']}, auto_id=False) self.assertEqual(str(f['composers']), """<ul> <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li> <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> </ul>""") f = SongForm({'composers': ['J', 'P']}, auto_id=False) self.assertEqual(str(f['composers']), """<ul> <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li> <li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> </ul>""") def test_checkbox_auto_id(self): # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox # gets a distinct ID, formed by appending an underscore plus the checkbox's # zero-based index. class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) f = SongForm(auto_id='%s_id') self.assertEqual(str(f['composers']), """<ul> <li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li> <li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li> </ul>""") def test_multiple_choice_list_data(self): # Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and # MergeDict (when created as a merge of MultiValueDicts) conveniently work with # this. class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) data = {'name': 'Yesterday', 'composers': ['J', 'P']} f = SongForm(data) self.assertEqual(f.errors, {}) data = QueryDict('name=Yesterday&composers=J&composers=P') f = SongForm(data) self.assertEqual(f.errors, {}) data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])) f = SongForm(data) self.assertEqual(f.errors, {}) data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))) f = SongForm(data) self.assertEqual(f.errors, {}) def test_multiple_hidden(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) # The MultipleHiddenInput widget renders multiple values as hidden fields. class SongFormHidden(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput) f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False) self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" /> <input type="hidden" name="composers" value="P" /></li>""") # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. f = SongForm({'name': 'Yesterday'}, auto_id=False) self.assertEqual(f.errors['composers'], [u'This field is required.']) f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], [u'J']) self.assertEqual(f.cleaned_data['name'], u'Yesterday') f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], [u'J', u'P']) self.assertEqual(f.cleaned_data['name'], u'Yesterday') def test_escaping(self): # Validation errors are HTML-escaped when output as HTML. class EscapingForm(Form): special_name = CharField(label="<em>Special</em> Field") special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) def clean_special_name(self): raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name']) def clean_special_safe_name(self): raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name'])) f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False) self.assertEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr> <tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="Nothing to escape" /></td></tr>""") f = EscapingForm({ 'special_name': "Should escape < & > and <script>alert('xss')</script>", 'special_safe_name': "<i>Do not escape</i>" }, auto_id=False) self.assertEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul><input type="text" name="special_name" value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" /></td></tr> <tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" /></td></tr>""") def test_validating_multiple_fields(self): # There are a couple of ways to do multiple-field validation. If you want the # validation message to be associated with a particular field, implement the # clean_XXX() method on the Form, where XXX is the field name. As in # Field.clean(), the clean_XXX() method should return the cleaned value. In the # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary # of all the data that has been cleaned *so far*, in order by the fields, # including the current field (e.g., the field XXX if you're in clean_XXX()). class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean_password2(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: raise ValidationError(u'Please make sure your passwords match.') return self.cleaned_data['password2'] f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertEqual(f.errors['username'], [u'This field is required.']) self.assertEqual(f.errors['password1'], [u'This field is required.']) self.assertEqual(f.errors['password2'], [u'This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['username'], u'adrian') self.assertEqual(f.cleaned_data['password1'], u'foo') self.assertEqual(f.cleaned_data['password2'], u'foo') # Another way of doing multiple-field validation is by implementing the # Form's clean() method. If you do this, any ValidationError raised by that # method will not be associated with a particular field; it will have a # special-case association with the field named '__all__'. # Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of # all the fields/values that have *not* raised a ValidationError. Also note # Form.clean() is required to return a dictionary of all clean data. class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: raise ValidationError(u'Please make sure your passwords match.') return self.cleaned_data f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertEqual(f.as_table(), """<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr> <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr> <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""") self.assertEqual(f.errors['username'], [u'This field is required.']) self.assertEqual(f.errors['password1'], [u'This field is required.']) self.assertEqual(f.errors['password2'], [u'This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.']) self.assertEqual(f.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>""") self.assertEqual(f.as_ul(), """<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li> <li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li> <li>Password1: <input type="password" name="password1" /></li> <li>Password2: <input type="password" name="password2" /></li>""") f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['username'], u'adrian') self.assertEqual(f.cleaned_data['password1'], u'foo') self.assertEqual(f.cleaned_data['password2'], u'foo') def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields # dictionary in __init__(). Don't forget to call Form.__init__() within the # subclass' __init__(). class Person(Form): first_name = CharField() last_name = CharField() def __init__(self, *args, **kwargs): super(Person, self).__init__(*args, **kwargs) self.fields['birthday'] = DateField() p = Person(auto_id=False) self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr> <tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>""") # Instances of a dynamic Form do not persist fields from one Form instance to # the next. class MyForm(Form): def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [('field1', CharField()), ('field2', CharField())] my_form = MyForm(field_list=field_list) self.assertEqual(my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""") field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) self.assertEqual(my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""") class MyForm(Form): default_field_1 = CharField() default_field_2 = CharField() def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [('field1', CharField()), ('field2', CharField())] my_form = MyForm(field_list=field_list) self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr> <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr> <tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""") field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr> <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""") # Similarly, changes to field attributes do not persist from one Form instance # to the next. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) def __init__(self, names_required=False, *args, **kwargs): super(Person, self).__init__(*args, **kwargs) if names_required: self.fields['first_name'].required = True self.fields['first_name'].widget.attrs['class'] = 'required' self.fields['last_name'].required = True self.fields['last_name'].widget.attrs['class'] = 'required' f = Person(names_required=False) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False)) self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) f = Person(names_required=True) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True)) self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'})) f = Person(names_required=False) self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False)) self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) class Person(Form): first_name = CharField(max_length=30) last_name = CharField(max_length=30) def __init__(self, name_max_length=None, *args, **kwargs): super(Person, self).__init__(*args, **kwargs) if name_max_length: self.fields['first_name'].max_length = name_max_length self.fields['last_name'].max_length = name_max_length f = Person(name_max_length=None) self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30)) f = Person(name_max_length=20) self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20)) f = Person(name_max_length=None) self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30)) def test_hidden_widget(self): # HiddenInput widgets are displayed differently in the as_table(), as_ul()) # and as_p() output of a Form -- their verbose names are not displayed, and a # separate row is not displayed. They're displayed in the last row of the # form, directly after that row's form element. class Person(Form): first_name = CharField() last_name = CharField() hidden_text = CharField(widget=HiddenInput) birthday = DateField() p = Person(auto_id=False) self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr> <tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>""") self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> <li>Last name: <input type="text" name="last_name" /></li> <li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>""") self.assertEqual(p.as_p(), """<p>First name: <input type="text" name="first_name" /></p> <p>Last name: <input type="text" name="last_name" /></p> <p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>""") # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. p = Person(auto_id='id_%s') self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>""") self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></li>""") self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></p>""") # If a field with a HiddenInput has errors, the as_table() and as_ul() output # will include the error message(s) with the text "(Hidden field [fieldname]) " # prepended. This message is displayed at the top of the output, regardless of # its field's order in the form. p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False) self.assertEqual(p.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr> <tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr> <tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr>""") self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></li> <li>First name: <input type="text" name="first_name" value="John" /></li> <li>Last name: <input type="text" name="last_name" value="Lennon" /></li> <li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li>""") self.assertEqual(p.as_p(), """<ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul> <p>First name: <input type="text" name="first_name" value="John" /></p> <p>Last name: <input type="text" name="last_name" value="Lennon" /></p> <p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p>""") # A corner case: It's possible for a form to have only HiddenInputs. class TestForm(Form): foo = CharField(widget=HiddenInput) bar = CharField(widget=HiddenInput) p = TestForm(auto_id=False) self.assertEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />') self.assertEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />') self.assertEqual(p.as_p(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />') def test_field_order(self): # A Form's fields are displayed in the same order in which they were defined. class TestForm(Form): field1 = CharField() field2 = CharField() field3 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field7 = CharField() field8 = CharField() field9 = CharField() field10 = CharField() field11 = CharField() field12 = CharField() field13 = CharField() field14 = CharField() p = TestForm(auto_id=False) self.assertEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr> <tr><th>Field5:</th><td><input type="text" name="field5" /></td></tr> <tr><th>Field6:</th><td><input type="text" name="field6" /></td></tr> <tr><th>Field7:</th><td><input type="text" name="field7" /></td></tr> <tr><th>Field8:</th><td><input type="text" name="field8" /></td></tr> <tr><th>Field9:</th><td><input type="text" name="field9" /></td></tr> <tr><th>Field10:</th><td><input type="text" name="field10" /></td></tr> <tr><th>Field11:</th><td><input type="text" name="field11" /></td></tr> <tr><th>Field12:</th><td><input type="text" name="field12" /></td></tr> <tr><th>Field13:</th><td><input type="text" name="field13" /></td></tr> <tr><th>Field14:</th><td><input type="text" name="field14" /></td></tr>""") def test_form_html_attributes(self): # Some Field classes have an effect on the HTML attributes of their associated # Widget. If you set max_length in a CharField and its associated widget is # either a TextInput or PasswordInput, then the widget's rendered HTML will # include the "maxlength" attribute. class UserRegistration(Form): username = CharField(max_length=10) # uses TextInput by default password = CharField(max_length=10, widget=PasswordInput) realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li> <li>Password: <input type="password" name="password" maxlength="10" /></li> <li>Realname: <input type="text" name="realname" maxlength="10" /></li> <li>Address: <input type="text" name="address" /></li>""") # If you specify a custom "attrs" that includes the "maxlength" attribute, # the Field's max_length attribute will override whatever "maxlength" you specify # in "attrs". class UserRegistration(Form): username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20})) password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li> <li>Password: <input type="password" name="password" maxlength="10" /></li>""") def test_specifying_labels(self): # You can specify the label for a field by using the 'label' argument to a Field # class. If you don't specify 'label', Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. class UserRegistration(Form): username = CharField(max_length=10, label='Your username') password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput, label='Password (again)') p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" /></li> <li>Password1: <input type="password" name="password1" /></li> <li>Password (again): <input type="password" name="password2" /></li>""") # Labels for as_* methods will only end in a colon if they don't end in other # punctuation already. class Questions(Form): q1 = CharField(label='The first question') q2 = CharField(label='What is your name?') q3 = CharField(label='The answer to life is:') q4 = CharField(label='Answer this question!') q5 = CharField(label='The last question. Period.') self.assertEqual(Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" /></p> <p>What is your name? <input type="text" name="q2" /></p> <p>The answer to life is: <input type="text" name="q3" /></p> <p>Answer this question! <input type="text" name="q4" /></p> <p>The last question. Period. <input type="text" name="q5" /></p>""") self.assertEqual(Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p> <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" /></p> <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" /></p> <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" /></p> <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p>""") # A label can be a Unicode object or a bytestring with special characters. class UserRegistration(Form): username = CharField(max_length=10, label='ŠĐĆŽćžšđ') password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), u'<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="text" name="username" maxlength="10" /></li>\n<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="password" name="password" /></li>') # If a label is set to the empty string for a field, that field won't get a label. class UserRegistration(Form): username = CharField(max_length=10, label='') password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li>""") p = UserRegistration(auto_id='id_%s') self.assertEqual(p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" /></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""") # If label is None, Django will auto-create the label from the field name. This # is default behavior. class UserRegistration(Form): username = CharField(max_length=10, label=None) password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li>""") p = UserRegistration(auto_id='id_%s') self.assertEqual(p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""") def test_label_suffix(self): # You can specify the 'label_suffix' argument to a Form class to modify the # punctuation symbol used at the end of a label. By default, the colon (:) is # used, and is only appended to the label if the label doesn't already end with a # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will # be appended regardless of the last character of the label. class FavoriteForm(Form): color = CharField(label='Favorite color?') animal = CharField(label='Favorite animal') f = FavoriteForm(auto_id=False) self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li> <li>Favorite animal: <input type="text" name="animal" /></li>""") f = FavoriteForm(auto_id=False, label_suffix='?') self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li> <li>Favorite animal? <input type="text" name="animal" /></li>""") f = FavoriteForm(auto_id=False, label_suffix='') self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li> <li>Favorite animal <input type="text" name="animal" /></li>""") f = FavoriteForm(auto_id=False, label_suffix=u'\u2192') self.assertEqual(f.as_ul(), u'<li>Favorite color? <input type="text" name="color" /></li>\n<li>Favorite animal\u2192 <input type="text" name="animal" /></li>') def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a # Field class. This initial data is displayed when a Form is rendered with *no* # data. It is not displayed when a Form is rendered with any data (including an # empty dictionary). Also, the initial value is *not* used if data for a # particular required field isn't provided. class UserRegistration(Form): username = CharField(max_length=10, initial='django') password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li>""") # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") p = UserRegistration({'username': u''}, auto_id=False) self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") p = UserRegistration({'username': u'foo'}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") # An 'initial' value is *not* used as a fallback if data is not provided. In this # example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}) self.assertEqual(p.errors['username'], [u'This field is required.']) self.assertFalse(p.is_valid()) def test_dynamic_initial_data(self): # The previous technique dealt with "hard-coded" initial data, but it's also # possible to specify initial data after you've already created the Form class # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This # should be a dictionary containing initial values for one or more fields in the # form, keyed by field name. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={'username': 'django'}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li>""") p = UserRegistration(initial={'username': 'stephane'}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li>""") # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={'username': 'django'}, auto_id=False) self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False) self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") # A dynamic 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}, initial={'username': 'django'}) self.assertEqual(p.errors['username'], [u'This field is required.']) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), # then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial='django') password = CharField(widget=PasswordInput) p = UserRegistration(initial={'username': 'babik'}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li>""") def test_callable_initial_data(self): # The previous technique dealt with raw values as initial data, but it's also # possible to specify callable data. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')]) # We need to define functions that get called later.) def initial_django(): return 'django' def initial_stephane(): return 'stephane' def initial_options(): return ['f','b'] def initial_other_options(): return ['b','w'] # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li> <li>Options: <select multiple="multiple" name="options"> <option value="f" selected="selected">foo</option> <option value="b" selected="selected">bar</option> <option value="w">whiz</option> </select></li>""") # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False) self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options"> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""") p = UserRegistration({'username': u''}, initial={'username': initial_django}, auto_id=False) self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options"> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""") p = UserRegistration({'username': u'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> <li>Options: <select multiple="multiple" name="options"> <option value="f" selected="selected">foo</option> <option value="b" selected="selected">bar</option> <option value="w">whiz</option> </select></li>""") # A callable 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the form raises a # validation error rather than using the initial value for 'username'. p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options}) self.assertEqual(p.errors['username'], [u'This field is required.']) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), # then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial=initial_django) password = CharField(widget=PasswordInput) options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options) p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li> <li>Options: <select multiple="multiple" name="options"> <option value="f">foo</option> <option value="b" selected="selected">bar</option> <option value="w" selected="selected">whiz</option> </select></li>""") p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li> <li>Password: <input type="password" name="password" /></li> <li>Options: <select multiple="multiple" name="options"> <option value="f" selected="selected">foo</option> <option value="b" selected="selected">bar</option> <option value="w">whiz</option> </select></li>""") def test_boundfield_values(self): # It's possible to get to the value which would be used for rendering # the widget for a field by using the BoundField's value method. class UserRegistration(Form): username = CharField(max_length=10, initial='djangonaut') password = CharField(widget=PasswordInput) unbound = UserRegistration() bound = UserRegistration({'password': 'foo'}) self.assertEqual(bound['username'].value(), None) self.assertEqual(unbound['username'].value(), 'djangonaut') self.assertEqual(bound['password'].value(), 'foo') self.assertEqual(unbound['password'].value(), None) def test_help_text(self): # You can specify descriptive text for a field by using the 'help_text' argument) class UserRegistration(Form): username = CharField(max_length=10, help_text='e.g., [email protected]') password = CharField(widget=PasswordInput, help_text='Choose wisely.') p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""") self.assertEqual(p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., [email protected]</span></p> <p>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></p>""") self.assertEqual(p.as_table(), """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /><br /><span class="helptext">e.g., [email protected]</span></td></tr> <tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Choose wisely.</span></td></tr>""") # The help text is displayed whether or not data is provided for the form. p = UserRegistration({'username': u'foo'}, auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /> <span class="helptext">e.g., [email protected]</span></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""") # help_text is not displayed for hidden fields. It can be used for documentation # purposes, though. class UserRegistration(Form): username = CharField(max_length=10, help_text='e.g., [email protected]') password = CharField(widget=PasswordInput) next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination') p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li>""") # Help text can include arbitrary Unicode characters. class UserRegistration(Form): username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ') p = UserRegistration(auto_id=False) self.assertEqual(p.as_ul(), u'<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</span></li>') def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have # all of the fields of the parent Form, plus whichever fields you define in the # subclass. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Musician(Person): instrument = CharField() p = Person(auto_id=False) self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> <li>Last name: <input type="text" name="last_name" /></li> <li>Birthday: <input type="text" name="birthday" /></li>""") m = Musician(auto_id=False) self.assertEqual(m.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> <li>Last name: <input type="text" name="last_name" /></li> <li>Birthday: <input type="text" name="birthday" /></li> <li>Instrument: <input type="text" name="instrument" /></li>""") # Yes, you can subclass multiple forms. The fields are added in the order in # which the parent classes are listed. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Instrument(Form): instrument = CharField() class Beatle(Person, Instrument): haircut_type = CharField() b = Beatle(auto_id=False) self.assertEqual(b.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> <li>Last name: <input type="text" name="last_name" /></li> <li>Birthday: <input type="text" name="birthday" /></li> <li>Instrument: <input type="text" name="instrument" /></li> <li>Haircut type: <input type="text" name="haircut_type" /></li>""") def test_forms_with_prefixes(self): # Sometimes it's necessary to have multiple forms display on the same HTML page, # or multiple copies of the same form. We can accomplish this with form prefixes. # Pass the keyword argument 'prefix' to the Form constructor to use this feature. # This value will be prepended to each HTML form field name. One way to think # about this is "namespaces for HTML forms". Notice that in the data argument, # each field's key has the prefix, in this case 'person1', prepended to the # actual field name. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() data = { 'person1-first_name': u'John', 'person1-last_name': u'Lennon', 'person1-birthday': u'1940-10-9' } p = Person(data, prefix='person1') self.assertEqual(p.as_ul(), """<li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /></li> <li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" /></li> <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>""") self.assertEqual(str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />') self.assertEqual(str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />') self.assertEqual(str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />') self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], u'John') self.assertEqual(p.cleaned_data['last_name'], u'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) # Let's try submitting some bad data to make sure form.errors and field.errors # work as expected. data = { 'person1-first_name': u'', 'person1-last_name': u'', 'person1-birthday': u'' } p = Person(data, prefix='person1') self.assertEqual(p.errors['first_name'], [u'This field is required.']) self.assertEqual(p.errors['last_name'], [u'This field is required.']) self.assertEqual(p.errors['birthday'], [u'This field is required.']) self.assertEqual(p['first_name'].errors, [u'This field is required.']) try: p['person1-first_name'].errors self.fail('Attempts to access non-existent fields should fail.') except KeyError: pass # In this example, the data doesn't have a prefix, but the form requires it, so # the form doesn't "see" the fields. data = { 'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9' } p = Person(data, prefix='person1') self.assertEqual(p.errors['first_name'], [u'This field is required.']) self.assertEqual(p.errors['last_name'], [u'This field is required.']) self.assertEqual(p.errors['birthday'], [u'This field is required.']) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { 'person1-first_name': u'John', 'person1-last_name': u'Lennon', 'person1-birthday': u'1940-10-9', 'person2-first_name': u'Jim', 'person2-last_name': u'Morrison', 'person2-birthday': u'1943-12-8' } p1 = Person(data, prefix='person1') self.assertTrue(p1.is_valid()) self.assertEqual(p1.cleaned_data['first_name'], u'John') self.assertEqual(p1.cleaned_data['last_name'], u'Lennon') self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9)) p2 = Person(data, prefix='person2') self.assertTrue(p2.is_valid()) self.assertEqual(p2.cleaned_data['first_name'], u'Jim') self.assertEqual(p2.cleaned_data['last_name'], u'Morrison') self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8)) # By default, forms append a hyphen between the prefix and the field name, but a # form can alter that behavior by implementing the add_prefix() method. This # method takes a field name and returns the prefixed field, according to # self.prefix. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() def add_prefix(self, field_name): return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name p = Person(prefix='foo') self.assertEqual(p.as_ul(), """<li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" /></li> <li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" /></li> <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>""") data = { 'foo-prefix-first_name': u'John', 'foo-prefix-last_name': u'Lennon', 'foo-prefix-birthday': u'1940-10-9' } p = Person(data, prefix='foo') self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], u'John') self.assertEqual(p.cleaned_data['last_name'], u'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) def test_forms_with_null_boolean(self): # NullBooleanField is a bit of a special case because its presentation (widget) # is different than its data. This is handled transparently, though. class Person(Form): name = CharField() is_cool = NullBooleanField() p = Person({'name': u'Joe'}, auto_id=False) self.assertEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1" selected="selected">Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select>""") p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False) self.assertEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1" selected="selected">Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select>""") p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False) self.assertEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected="selected">Yes</option> <option value="3">No</option> </select>""") p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False) self.assertEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2">Yes</option> <option value="3" selected="selected">No</option> </select>""") p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False) self.assertEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2" selected="selected">Yes</option> <option value="3">No</option> </select>""") p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False) self.assertEqual(str(p['is_cool']), """<select name="is_cool"> <option value="1">Unknown</option> <option value="2">Yes</option> <option value="3" selected="selected">No</option> </select>""") def test_forms_with_file_fields(self): # FileFields are a special case because they take their data from the request.FILES, # not request.POST. class FileForm(Form): file1 = FileField() f = FileForm(auto_id=False) self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>') f = FileForm(data={}, files={}, auto_id=False) self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="file1" /></td></tr>') f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False) self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>The submitted file is empty.</li></ul><input type="file" name="file1" /></td></tr>') f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False) self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul><input type="file" name="file1" /></td></tr>') f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False) self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>') self.assertTrue(f.is_valid()) f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>') def test_basic_processing_in_view(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: raise ValidationError(u'Please make sure your passwords match.') return self.cleaned_data def my_function(method, post_data): if method == 'POST': form = UserRegistration(post_data, auto_id=False) else: form = UserRegistration(auto_id=False) if form.is_valid(): return 'VALID: %r' % form.cleaned_data t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>') return t.render(Context({'form': form})) # Case 1: GET (an empty form, with no errors).) self.assertEqual(my_function('GET', {}), """<form action="" method="post"> <table> <tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr> </table> <input type="submit" /> </form>""") # Case 2: POST with erroneous data (a redisplayed form, with errors).) self.assertEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form action="" method="post"> <table> <tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td><ul class="errorlist"><li>Ensure this value has at most 10 characters (it has 23).</li></ul><input type="text" name="username" value="this-is-a-long-username" maxlength="10" /></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr> </table> <input type="submit" /> </form>""") # Case 3: POST with valid data (the success message).) self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}") def test_templates_with_forms(self): class UserRegistration(Form): username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.") password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: raise ValidationError(u'Please make sure your passwords match.') return self.cleaned_data # You have full flexibility in displaying form fields in a template. Just pass a # Form instance to the template, and use "dot" access to refer to individual # fields. Note, however, that this flexibility comes with the responsibility of # displaying all the errors, including any that might not be associated with a # particular field. t = Template('''<form action=""> {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> <input type="submit" /> </form>''') self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> <p><label>Your username: <input type="text" name="username" maxlength="10" /></label></p> <p><label>Password: <input type="password" name="password1" /></label></p> <p><label>Password (again): <input type="password" name="password2" /></label></p> <input type="submit" /> </form>""") self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form action=""> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> <ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p> <ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p> <input type="submit" /> </form>""") # Use form.[field].label to output a field's label. You can specify the label for # a field by using the 'label' argument to a Field class. If you don't specify # 'label', Django will use the field name with underscores converted to spaces, # and the initial letter capitalized. t = Template('''<form action=""> <p><label>{{ form.username.label }}: {{ form.username }}</label></p> <p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p> <p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p> <input type="submit" /> </form>''') self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> <p><label>Username: <input type="text" name="username" maxlength="10" /></label></p> <p><label>Password1: <input type="password" name="password1" /></label></p> <p><label>Password2: <input type="password" name="password2" /></label></p> <input type="submit" /> </form>""") # User form.[field].label_tag to output a field's label with a <label> tag # wrapped around it, but *only* if the given field has an "id" attribute. # Recall from above that passing the "auto_id" argument to a Form gives each # field an "id" attribute. t = Template('''<form action=""> <p>{{ form.username.label_tag }}: {{ form.username }}</p> <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p> <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p> <input type="submit" /> </form>''') self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> <p>Username: <input type="text" name="username" maxlength="10" /></p> <p>Password1: <input type="password" name="password1" /></p> <p>Password2: <input type="password" name="password2" /></p> <input type="submit" /> </form>""") self.assertEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form action=""> <p><label for="id_username">Username</label>: <input id="id_username" type="text" name="username" maxlength="10" /></p> <p><label for="id_password1">Password1</label>: <input type="password" name="password1" id="id_password1" /></p> <p><label for="id_password2">Password2</label>: <input type="password" name="password2" id="id_password2" /></p> <input type="submit" /> </form>""") # User form.[field].help_text to output a field's help text. If the given field # does not have help text, nothing will be output. t = Template('''<form action=""> <p>{{ form.username.label_tag }}: {{ form.username }}<br />{{ form.username.help_text }}</p> <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p> <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p> <input type="submit" /> </form>''') self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> <p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn&#39;t already exist.</p> <p>Password1: <input type="password" name="password1" /></p> <p>Password2: <input type="password" name="password2" /></p> <input type="submit" /> </form>""") self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), u'') # The label_tag() method takes an optional attrs argument: a dictionary of HTML # attributes to add to the <label> tag. f = UserRegistration(auto_id='id_%s') form_output = [] for bf in f: form_output.append(bf.label_tag(attrs={'class': 'pretty'})) self.assertEqual(form_output, [ '<label for="id_username" class="pretty">Username</label>', '<label for="id_password1" class="pretty">Password1</label>', '<label for="id_password2" class="pretty">Password2</label>', ]) # To display the errors that aren't associated with a particular field -- e.g., # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the # template. If used on its own, it is displayed as a <ul> (or an empty string, if # the list of errors is empty). You can also use it in {% if %} statements. t = Template('''<form action=""> {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> <input type="submit" /> </form>''') self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action=""> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> <p><label>Password: <input type="password" name="password1" /></label></p> <p><label>Password (again): <input type="password" name="password2" /></label></p> <input type="submit" /> </form>""") t = Template('''<form action=""> {{ form.non_field_errors }} {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> <input type="submit" /> </form>''') self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action=""> <ul class="errorlist"><li>Please make sure your passwords match.</li></ul> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> <p><label>Password: <input type="password" name="password1" /></label></p> <p><label>Password (again): <input type="password" name="password2" /></label></p> <input type="submit" /> </form>""") def test_empty_permitted(self): # Sometimes (pretty much in formsets) we want to allow a form to pass validation # if it is completely empty. We can accomplish this by using the empty_permitted # agrument to a form constructor. class SongForm(Form): artist = CharField() name = CharField() # First let's show what happens id empty_permitted=False (the default): data = {'artist': '', 'song': ''} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'name': [u'This field is required.'], 'artist': [u'This field is required.']}) try: form.cleaned_data self.fail('Attempts to access cleaned_data when validation fails should fail.') except AttributeError: pass # Now let's show what happens when empty_permitted=True and the form is empty. form = SongForm(data, empty_permitted=True) self.assertTrue(form.is_valid()) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {}) # But if we fill in data for one of the fields, the form is no longer empty and # the whole thing must pass validation. data = {'artist': 'The Doors', 'song': ''} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'name': [u'This field is required.']}) try: form.cleaned_data self.fail('Attempts to access cleaned_data when validation fails should fail.') except AttributeError: pass # If a field is not given in the data then None is returned for its data. Lets # make sure that when checking for empty_permitted that None is treated # accordingly. data = {'artist': None, 'song': ''} form = SongForm(data, empty_permitted=True) self.assertTrue(form.is_valid()) # However, we *really* need to be sure we are checking for None as any data in # initial that returns False on a boolean call needs to be treated literally. class PriceForm(Form): amount = FloatField() qty = IntegerField() data = {'amount': '0.0', 'qty': ''} form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True) self.assertTrue(form.is_valid()) def test_extracting_hidden_and_visible(self): class SongForm(Form): token = CharField(widget=HiddenInput) artist = CharField() name = CharField() form = SongForm() self.assertEqual([f.name for f in form.hidden_fields()], ['token']) self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name']) def test_hidden_initial_gets_id(self): class MyForm(Form): field1 = CharField(max_length=50, show_hidden_initial=True) self.assertEqual(MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td><input id="id_field1" type="text" name="field1" maxlength="50" /><input type="hidden" name="initial-field1" id="initial-id_field1" /></td></tr>') def test_error_html_required_html_classes(self): class Person(Form): name = CharField() is_cool = NullBooleanField() email = EmailField(required=False) age = IntegerField() p = Person({}) p.error_css_class = 'error' p.required_css_class = 'required' self.assertEqual(p.as_ul(), """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li> <li class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="1" selected="selected">Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select></li> <li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li> <li class="required error"><ul class="errorlist"><li>This field is required.</li></ul><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></li>""") self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p> <p class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="1" selected="selected">Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select></p> <p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p> <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>""") self.assertEqual(p.as_table(), """<tr class="required error"><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="name" id="id_name" /></td></tr> <tr class="required"><th><label for="id_is_cool">Is cool:</label></th><td><select name="is_cool" id="id_is_cool"> <option value="1" selected="selected">Unknown</option> <option value="2">Yes</option> <option value="3">No</option> </select></td></tr> <tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr> <tr class="required error"><th><label for="id_age">Age:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="age" id="id_age" /></td></tr>""") def test_label_split_datetime_not_displayed(self): class EventForm(Form): happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget) form = EventForm() self.assertEqual(form.as_ul(), u'<input type="hidden" name="happened_at_0" id="id_happened_at_0" /><input type="hidden" name="happened_at_1" id="id_happened_at_1" />')
104,530
Python
.py
1,503
61.7831
516
0.633796
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,919
extra.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/tests/extra.py
# -*- coding: utf-8 -*- import datetime import time from django.conf import settings from django.forms import * from django.forms.extras import SelectDateWidget from django.forms.util import ErrorList from django.utils import translation from django.utils import unittest from django.utils.encoding import force_unicode from django.utils.encoding import smart_unicode from error_messages import AssertFormErrorsMixin class GetDate(Form): mydate = DateField(widget=SelectDateWidget) class FormsExtraTestCase(unittest.TestCase, AssertFormErrorsMixin): ############### # Extra stuff # ############### # The forms library comes with some extra, higher-level Field and Widget def test_selectdate(self): w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016')) self.assertEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select>""") self.assertEqual(w.render('mydate', None), w.render('mydate', '')) self.assertEqual(w.render('mydate', '2010-04-15'), """<select name="mydate_month" id="id_mydate_month"> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4" selected="selected">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15" selected="selected">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected="selected">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select>""") # Accepts a datetime or a string: self.assertEqual(w.render('mydate', datetime.date(2010, 4, 15)), w.render('mydate', '2010-04-15')) # Invalid dates still render the failed date: self.assertEqual(w.render('mydate', '2010-02-31'), """<select name="mydate_month" id="id_mydate_month"> <option value="1">January</option> <option value="2" selected="selected">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31" selected="selected">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected="selected">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select>""") # Using a SelectDateWidget in a form: w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False) self.assertEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select>""") self.assertEqual(w.render('mydate', '2010-04-15'), """<select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4" selected="selected">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15" selected="selected">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected="selected">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select>""") a = GetDate({'mydate_month':'4', 'mydate_day':'1', 'mydate_year':'2008'}) self.assertTrue(a.is_valid()) self.assertEqual(a.cleaned_data['mydate'], datetime.date(2008, 4, 1)) # As with any widget that implements get_value_from_datadict, # we must be prepared to accept the input from the "as_hidden" # rendering as well. self.assertEqual(a['mydate'].as_hidden(), '<input type="hidden" name="mydate" value="2008-4-1" id="id_mydate" />') b = GetDate({'mydate':'2008-4-1'}) self.assertTrue(b.is_valid()) self.assertEqual(b.cleaned_data['mydate'], datetime.date(2008, 4, 1)) # Invalid dates shouldn't be allowed c = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'}) self.assertFalse(c.is_valid()) self.assertEqual(c.errors, {'mydate': [u'Enter a valid date.']}) # label tag is correctly associated with month dropdown d = GetDate({'mydate_month':'1', 'mydate_day':'1', 'mydate_year':'2010'}) self.assertTrue('<label for="id_mydate_month">' in d.as_p()) def test_multiwidget(self): # MultiWidget and MultiValueField ############################################# # MultiWidgets are widgets composed of other widgets. They are usually # combined with MultiValueFields - a field that is composed of other fields. # MulitWidgets can themselved be composed of other MultiWidgets. # SplitDateTimeWidget is one example of a MultiWidget. class ComplexMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = ( TextInput(), SelectMultiple(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), SplitDateTimeWidget(), ) super(ComplexMultiWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: data = value.split(',') return [data[0], data[1], datetime.datetime(*time.strptime(data[2], "%Y-%m-%d %H:%M:%S")[0:6])] return [None, None, None] def format_output(self, rendered_widgets): return u'\n'.join(rendered_widgets) w = ComplexMultiWidget() self.assertEqual(w.render('name', 'some text,JP,2007-04-25 06:24:00'), """<input type="text" name="name_0" value="some text" /> <select multiple="multiple" name="name_1"> <option value="J" selected="selected">John</option> <option value="P" selected="selected">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select> <input type="text" name="name_2_0" value="2007-04-25" /><input type="text" name="name_2_1" value="06:24:00" />""") class ComplexField(MultiValueField): def __init__(self, required=True, widget=None, label=None, initial=None): fields = ( CharField(), MultipleChoiceField(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), SplitDateTimeField() ) super(ComplexField, self).__init__(fields, required, widget, label, initial) def compress(self, data_list): if data_list: return '%s,%s,%s' % (data_list[0],''.join(data_list[1]),data_list[2]) return None f = ComplexField(widget=w) self.assertEqual(f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]), u'some text,JP,2007-04-25 06:24:00') self.assertFormErrors([u'Select a valid choice. X is not one of the available choices.'], f.clean, ['some text',['X'], ['2007-04-25','6:24:00']]) # If insufficient data is provided, None is substituted self.assertFormErrors([u'This field is required.'], f.clean, ['some text',['JP']]) class ComplexFieldForm(Form): field1 = ComplexField(widget=w) f = ComplexFieldForm() self.assertEqual(f.as_table(), """<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" id="id_field1_0" /> <select multiple="multiple" name="field1_1" id="id_field1_1"> <option value="J">John</option> <option value="P">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select> <input type="text" name="field1_2_0" id="id_field1_2_0" /><input type="text" name="field1_2_1" id="id_field1_2_1" /></td></tr>""") f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'}) self.assertEqual(f.as_table(), """<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" value="some text" id="id_field1_0" /> <select multiple="multiple" name="field1_1" id="id_field1_1"> <option value="J" selected="selected">John</option> <option value="P" selected="selected">Paul</option> <option value="G">George</option> <option value="R">Ringo</option> </select> <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" /><input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" /></td></tr>""") self.assertEqual(f.cleaned_data['field1'], u'some text,JP,2007-04-25 06:24:00') def test_ipaddress(self): f = IPAddressField() self.assertFormErrors([u'This field is required.'], f.clean, '') self.assertFormErrors([u'This field is required.'], f.clean, None) self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'foo') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '127.0.0.') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '256.125.1.5') f = IPAddressField(required=False) self.assertEqual(f.clean(''), u'') self.assertEqual(f.clean(None), u'') self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'foo') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '127.0.0.') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '256.125.1.5') def test_smart_unicode(self): class Test: def __str__(self): return 'ŠĐĆŽćžšđ' class TestU: def __str__(self): return 'Foo' def __unicode__(self): return u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' self.assertEqual(smart_unicode(Test()), u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') self.assertEqual(smart_unicode(TestU()), u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') self.assertEqual(smart_unicode(1), u'1') self.assertEqual(smart_unicode('foo'), u'foo') def test_accessing_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data if not self.errors: data['username'] = data['username'].lower() return data f = UserForm({'username': 'SirRobin', 'password': 'blue'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['username'], u'sirrobin') def test_overriding_errorlist(self): class DivErrorList(ErrorList): def __unicode__(self): return self.as_divs() def as_divs(self): if not self: return u'' return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % force_unicode(e) for e in self]) class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = dict(email='invalid') f = CommentForm(data, auto_id=False, error_class=DivErrorList) self.assertEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50" /></p> <div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div> <p>Email: <input type="text" name="email" value="invalid" /></p> <div class="errorlist"><div class="error">This field is required.</div></div> <p>Comment: <input type="text" name="comment" /></p>""") def test_multipart_encoded_form(self): class FormWithoutFile(Form): username = CharField() class FormWithFile(Form): username = CharField() file = FileField() class FormWithImage(Form): image = ImageField() self.assertFalse(FormWithoutFile().is_multipart()) self.assertTrue(FormWithFile().is_multipart()) self.assertTrue(FormWithImage().is_multipart()) class FormsExtraL10NTestCase(unittest.TestCase): def setUp(self): super(FormsExtraL10NTestCase, self).setUp() self.old_use_l10n = getattr(settings, 'USE_L10N', False) settings.USE_L10N = True translation.activate('nl') def tearDown(self): translation.deactivate() settings.USE_L10N = self.old_use_l10n super(FormsExtraL10NTestCase, self).tearDown() def test_l10n(self): w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False) self.assertEqual(w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-2010') self.assertEqual(w.render('date', '13-08-2010'), """<select name="date_day" id="id_date_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13" selected="selected">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="date_month" id="id_date_month"> <option value="0">---</option> <option value="1">januari</option> <option value="2">februari</option> <option value="3">maart</option> <option value="4">april</option> <option value="5">mei</option> <option value="6">juni</option> <option value="7">juli</option> <option value="8" selected="selected">augustus</option> <option value="9">september</option> <option value="10">oktober</option> <option value="11">november</option> <option value="12">december</option> </select> <select name="date_year" id="id_date_year"> <option value="0">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected="selected">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select>""") # Years before 1900 work w = SelectDateWidget(years=('1899',)) self.assertEqual(w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-1899') def test_l10n_invalid_date_in(self): # Invalid dates shouldn't be allowed a = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'}) self.assertFalse(a.is_valid()) # 'Geef een geldige datum op.' = 'Enter a valid date.' self.assertEqual(a.errors, {'mydate': [u'Geef een geldige datum op.']}) def test_form_label_association(self): # label tag is correctly associated with first rendered dropdown a = GetDate({'mydate_month':'1', 'mydate_day':'1', 'mydate_year':'2010'}) self.assertTrue('<label for="id_mydate_day">' in a.as_p())
24,191
Python
.py
575
38.022609
171
0.659662
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,920
uk.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/uk.py
from django.contrib.localflavor.uk.forms import UKPostcodeField from utils import LocalFlavorTestCase class UKLocalFlavorTests(LocalFlavorTestCase): def test_UKPostcodeField(self): error_invalid = [u'Enter a valid postcode.'] valid = { 'BT32 4PX': 'BT32 4PX', 'GIR 0AA': 'GIR 0AA', 'BT324PX': 'BT32 4PX', ' so11aa ': 'SO1 1AA', ' so1 1aa ': 'SO1 1AA', 'G2 3wt': 'G2 3WT', 'EC1A 1BB': 'EC1A 1BB', 'Ec1a1BB': 'EC1A 1BB', } invalid = { '1NV 4L1D': error_invalid, '1NV4L1D': error_invalid, ' b0gUS': error_invalid, } self.assertFieldOutput(UKPostcodeField, valid, invalid) valid = {} invalid = { '1NV 4L1D': [u'Enter a bloody postcode!'], } kwargs = {'error_messages': {'invalid': 'Enter a bloody postcode!'}} self.assertFieldOutput(UKPostcodeField, valid, invalid, field_kwargs=kwargs)
1,023
Python
.py
27
28.037037
84
0.561934
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,921
cz.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/cz.py
import warnings from django.contrib.localflavor.cz.forms import (CZPostalCodeField, CZRegionSelect, CZBirthNumberField, CZICNumberField) from django.core.exceptions import ValidationError from utils import LocalFlavorTestCase class CZLocalFlavorTests(LocalFlavorTestCase): def setUp(self): self.save_warnings_state() warnings.filterwarnings( "ignore", category=PendingDeprecationWarning, module='django.contrib.localflavor.cz.forms' ) def tearDown(self): self.restore_warnings_state() def test_CZRegionSelect(self): f = CZRegionSelect() out = u'''<select name="regions"> <option value="PR">Prague</option> <option value="CE">Central Bohemian Region</option> <option value="SO">South Bohemian Region</option> <option value="PI">Pilsen Region</option> <option value="CA">Carlsbad Region</option> <option value="US">Usti Region</option> <option value="LB">Liberec Region</option> <option value="HK">Hradec Region</option> <option value="PA">Pardubice Region</option> <option value="VY">Vysocina Region</option> <option value="SM">South Moravian Region</option> <option value="OL">Olomouc Region</option> <option value="ZL">Zlin Region</option> <option value="MS">Moravian-Silesian Region</option> </select>''' self.assertEqual(f.render('regions', 'TT'), out) def test_CZPostalCodeField(self): error_format = [u'Enter a postal code in the format XXXXX or XXX XX.'] valid = { '91909': '91909', '917 01': '91701', '12345': '12345', } invalid = { '84545x': error_format, '123456': error_format, '1234': error_format, '123 4': error_format, } self.assertFieldOutput(CZPostalCodeField, valid, invalid) def test_CZBirthNumberField(self): error_format = [u'Enter a birth number in the format XXXXXX/XXXX or XXXXXXXXXX.'] error_invalid = [u'Enter a valid birth number.'] valid = { '880523/1237': '880523/1237', '8805231237': '8805231237', '880523/000': '880523/000', '880523000': '880523000', '882101/0011': '882101/0011', } invalid = { '123456/12': error_format, '123456/12345': error_format, '12345612': error_format, '12345612345': error_format, '880523/1239': error_invalid, '8805231239': error_invalid, '990101/0011': error_invalid, } self.assertFieldOutput(CZBirthNumberField, valid, invalid) # These tests should go away in 1.4. # http://code.djangoproject.com/ticket/14593 f = CZBirthNumberField() self.assertEqual(f.clean('880523/1237', 'm'), '880523/1237'), self.assertEqual(f.clean('885523/1231', 'f'), '885523/1231') self.assertRaisesRegexp(ValidationError, unicode(error_invalid), f.clean, '881523/0000', 'm') self.assertRaisesRegexp(ValidationError, unicode(error_invalid), f.clean, '885223/0000', 'm') self.assertRaisesRegexp(ValidationError, unicode(error_invalid), f.clean, '881523/0000', 'f') self.assertRaisesRegexp(ValidationError, unicode(error_invalid), f.clean, '885223/0000', 'f') def test_CZICNumberField(self): error_invalid = [u'Enter a valid IC number.'] valid ={ '12345679': '12345679', '12345601': '12345601', '12345661': '12345661', '12345610': '12345610', } invalid = { '1234567': error_invalid, '12345660': error_invalid, '12345600': error_invalid, } self.assertFieldOutput(CZICNumberField, valid, invalid)
3,842
Python
.py
95
31.926316
89
0.626706
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,922
de.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/de.py
from django.contrib.localflavor.de.forms import (DEZipCodeField, DEStateSelect, DEIdentityCardNumberField) from utils import LocalFlavorTestCase class DELocalFlavorTests(LocalFlavorTestCase): def test_DEStateSelect(self): f = DEStateSelect() out = u'''<select name="states"> <option value="BW">Baden-Wuerttemberg</option> <option value="BY">Bavaria</option> <option value="BE">Berlin</option> <option value="BB">Brandenburg</option> <option value="HB">Bremen</option> <option value="HH">Hamburg</option> <option value="HE">Hessen</option> <option value="MV">Mecklenburg-Western Pomerania</option> <option value="NI">Lower Saxony</option> <option value="NW">North Rhine-Westphalia</option> <option value="RP">Rhineland-Palatinate</option> <option value="SL">Saarland</option> <option value="SN">Saxony</option> <option value="ST">Saxony-Anhalt</option> <option value="SH">Schleswig-Holstein</option> <option value="TH" selected="selected">Thuringia</option> </select>''' self.assertEqual(f.render('states', 'TH'), out) def test_DEZipCodeField(self): error_format = [u'Enter a zip code in the format XXXXX.'] valid = { '99423': '99423', } invalid = { ' 99423': error_format, } self.assertFieldOutput(DEZipCodeField, valid, invalid) def test_DEIdentityCardNumberField(self): error_format = [u'Enter a valid German identity card number in XXXXXXXXXXX-XXXXXXX-XXXXXXX-X format.'] valid = { '7549313035D-6004103-0903042-0': '7549313035D-6004103-0903042-0', '9786324830D 6104243 0910271 2': '9786324830D-6104243-0910271-2', } invalid = { '0434657485D-6407276-0508137-9': error_format, } self.assertFieldOutput(DEIdentityCardNumberField, valid, invalid)
1,847
Python
.py
44
36.409091
110
0.697442
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,923
ie.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/ie.py
from django.contrib.localflavor.ie.forms import IECountySelect from utils import LocalFlavorTestCase class IELocalFlavorTests(LocalFlavorTestCase): def test_IECountySelect(self): f = IECountySelect() out = u'''<select name="counties"> <option value="antrim">Antrim</option> <option value="armagh">Armagh</option> <option value="carlow">Carlow</option> <option value="cavan">Cavan</option> <option value="clare">Clare</option> <option value="cork">Cork</option> <option value="derry">Derry</option> <option value="donegal">Donegal</option> <option value="down">Down</option> <option value="dublin" selected="selected">Dublin</option> <option value="fermanagh">Fermanagh</option> <option value="galway">Galway</option> <option value="kerry">Kerry</option> <option value="kildare">Kildare</option> <option value="kilkenny">Kilkenny</option> <option value="laois">Laois</option> <option value="leitrim">Leitrim</option> <option value="limerick">Limerick</option> <option value="longford">Longford</option> <option value="louth">Louth</option> <option value="mayo">Mayo</option> <option value="meath">Meath</option> <option value="monaghan">Monaghan</option> <option value="offaly">Offaly</option> <option value="roscommon">Roscommon</option> <option value="sligo">Sligo</option> <option value="tipperary">Tipperary</option> <option value="tyrone">Tyrone</option> <option value="waterford">Waterford</option> <option value="westmeath">Westmeath</option> <option value="wexford">Wexford</option> <option value="wicklow">Wicklow</option> </select>''' self.assertEqual(f.render('counties', 'dublin'), out)
1,629
Python
.py
40
38.95
62
0.762926
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,924
fr.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/fr.py
from django.contrib.localflavor.fr.forms import (FRZipCodeField, FRPhoneNumberField, FRDepartmentSelect) from utils import LocalFlavorTestCase class FRLocalFlavorTests(LocalFlavorTestCase): def test_FRZipCodeField(self): error_format = [u'Enter a zip code in the format XXXXX.'] valid = { '75001': '75001', '93200': '93200', } invalid = { '2A200': error_format, '980001': error_format, } self.assertFieldOutput(FRZipCodeField, valid, invalid) def test_FRPhoneNumberField(self): error_format = [u'Phone numbers must be in 0X XX XX XX XX format.'] valid = { '01 55 44 58 64': '01 55 44 58 64', '0155445864': '01 55 44 58 64', '01 5544 5864': '01 55 44 58 64', '01 55.44.58.64': '01 55 44 58 64', '01.55.44.58.64': '01 55 44 58 64', } invalid = { '01,55,44,58,64': error_format, '555 015 544': error_format, } self.assertFieldOutput(FRPhoneNumberField, valid, invalid) def test_FRDepartmentSelect(self): f = FRDepartmentSelect() out = u'''<select name="dep"> <option value="01">01 - Ain</option> <option value="02">02 - Aisne</option> <option value="03">03 - Allier</option> <option value="04">04 - Alpes-de-Haute-Provence</option> <option value="05">05 - Hautes-Alpes</option> <option value="06">06 - Alpes-Maritimes</option> <option value="07">07 - Ardeche</option> <option value="08">08 - Ardennes</option> <option value="09">09 - Ariege</option> <option value="10">10 - Aube</option> <option value="11">11 - Aude</option> <option value="12">12 - Aveyron</option> <option value="13">13 - Bouches-du-Rhone</option> <option value="14">14 - Calvados</option> <option value="15">15 - Cantal</option> <option value="16">16 - Charente</option> <option value="17">17 - Charente-Maritime</option> <option value="18">18 - Cher</option> <option value="19">19 - Correze</option> <option value="21">21 - Cote-d&#39;Or</option> <option value="22">22 - Cotes-d&#39;Armor</option> <option value="23">23 - Creuse</option> <option value="24">24 - Dordogne</option> <option value="25">25 - Doubs</option> <option value="26">26 - Drome</option> <option value="27">27 - Eure</option> <option value="28">28 - Eure-et-Loire</option> <option value="29">29 - Finistere</option> <option value="2A">2A - Corse-du-Sud</option> <option value="2B">2B - Haute-Corse</option> <option value="30">30 - Gard</option> <option value="31">31 - Haute-Garonne</option> <option value="32">32 - Gers</option> <option value="33">33 - Gironde</option> <option value="34">34 - Herault</option> <option value="35">35 - Ille-et-Vilaine</option> <option value="36">36 - Indre</option> <option value="37">37 - Indre-et-Loire</option> <option value="38">38 - Isere</option> <option value="39">39 - Jura</option> <option value="40">40 - Landes</option> <option value="41">41 - Loir-et-Cher</option> <option value="42">42 - Loire</option> <option value="43">43 - Haute-Loire</option> <option value="44">44 - Loire-Atlantique</option> <option value="45">45 - Loiret</option> <option value="46">46 - Lot</option> <option value="47">47 - Lot-et-Garonne</option> <option value="48">48 - Lozere</option> <option value="49">49 - Maine-et-Loire</option> <option value="50">50 - Manche</option> <option value="51">51 - Marne</option> <option value="52">52 - Haute-Marne</option> <option value="53">53 - Mayenne</option> <option value="54">54 - Meurthe-et-Moselle</option> <option value="55">55 - Meuse</option> <option value="56">56 - Morbihan</option> <option value="57">57 - Moselle</option> <option value="58">58 - Nievre</option> <option value="59">59 - Nord</option> <option value="60">60 - Oise</option> <option value="61">61 - Orne</option> <option value="62">62 - Pas-de-Calais</option> <option value="63">63 - Puy-de-Dome</option> <option value="64">64 - Pyrenees-Atlantiques</option> <option value="65">65 - Hautes-Pyrenees</option> <option value="66">66 - Pyrenees-Orientales</option> <option value="67">67 - Bas-Rhin</option> <option value="68">68 - Haut-Rhin</option> <option value="69">69 - Rhone</option> <option value="70">70 - Haute-Saone</option> <option value="71">71 - Saone-et-Loire</option> <option value="72">72 - Sarthe</option> <option value="73">73 - Savoie</option> <option value="74">74 - Haute-Savoie</option> <option value="75">75 - Paris</option> <option value="76">76 - Seine-Maritime</option> <option value="77">77 - Seine-et-Marne</option> <option value="78">78 - Yvelines</option> <option value="79">79 - Deux-Sevres</option> <option value="80">80 - Somme</option> <option value="81">81 - Tarn</option> <option value="82">82 - Tarn-et-Garonne</option> <option value="83">83 - Var</option> <option value="84">84 - Vaucluse</option> <option value="85">85 - Vendee</option> <option value="86">86 - Vienne</option> <option value="87">87 - Haute-Vienne</option> <option value="88">88 - Vosges</option> <option value="89">89 - Yonne</option> <option value="90">90 - Territoire de Belfort</option> <option value="91">91 - Essonne</option> <option value="92">92 - Hauts-de-Seine</option> <option value="93">93 - Seine-Saint-Denis</option> <option value="94">94 - Val-de-Marne</option> <option value="95">95 - Val-d&#39;Oise</option> <option value="971">971 - Guadeloupe</option> <option value="972">972 - Martinique</option> <option value="973">973 - Guyane</option> <option value="974">974 - La Reunion</option> <option value="975">975 - Saint-Pierre-et-Miquelon</option> <option value="976">976 - Mayotte</option> <option value="984">984 - Terres Australes et Antarctiques</option> <option value="986">986 - Wallis et Futuna</option> <option value="987">987 - Polynesie Francaise</option> <option value="988">988 - Nouvelle-Caledonie</option> </select>''' self.assertEqual(f.render('dep', 'Paris'), out)
5,951
Python
.py
140
39.528571
75
0.676714
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,925
tr.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/tr.py
# Tests for the contrib/localflavor/ TR form fields. from django.contrib.localflavor.tr import forms as trforms from django.core.exceptions import ValidationError from django.utils.unittest import TestCase class TRLocalFlavorTests(TestCase): def test_TRPostalCodeField(self): f = trforms.TRPostalCodeField() self.assertEqual(f.clean("06531"), "06531") self.assertEqual(f.clean("12345"), "12345") self.assertRaisesRegexp(ValidationError, "Enter a postal code in the format XXXXX.", f.clean, "a1234") self.assertRaisesRegexp(ValidationError, "Enter a postal code in the format XXXXX.", f.clean, "1234") self.assertRaisesRegexp(ValidationError, "Enter a postal code in the format XXXXX.", f.clean, "82123") self.assertRaisesRegexp(ValidationError, "Enter a postal code in the format XXXXX.", f.clean, "00123") self.assertRaisesRegexp(ValidationError, "Enter a postal code in the format XXXXX.", f.clean, "123456") self.assertRaisesRegexp(ValidationError, "Enter a postal code in the format XXXXX.", f.clean, "12 34") self.assertRaises(ValidationError, f.clean, None) def test_TRPhoneNumberField(self): f = trforms.TRPhoneNumberField() self.assertEqual(f.clean("312 455 56 78"), "3124555678") self.assertEqual(f.clean("312 4555678"), "3124555678") self.assertEqual(f.clean("3124555678"), "3124555678") self.assertEqual(f.clean("0312 455 5678"), "3124555678") self.assertEqual(f.clean("0 312 455 5678"), "3124555678") self.assertEqual(f.clean("0 (312) 455 5678"), "3124555678") self.assertEqual(f.clean("+90 312 455 4567"), "3124554567") self.assertEqual(f.clean("+90 312 455 45 67"), "3124554567") self.assertEqual(f.clean("+90 (312) 4554567"), "3124554567") self.assertRaisesRegexp(ValidationError, 'Phone numbers must be in 0XXX XXX XXXX format.', f.clean, "1234 233 1234") self.assertRaisesRegexp(ValidationError, 'Phone numbers must be in 0XXX XXX XXXX format.', f.clean, "0312 233 12345") self.assertRaisesRegexp(ValidationError, 'Phone numbers must be in 0XXX XXX XXXX format.', f.clean, "0312 233 123") self.assertRaisesRegexp(ValidationError, 'Phone numbers must be in 0XXX XXX XXXX format.', f.clean, "0312 233 xxxx") def test_TRIdentificationNumberField(self): f = trforms.TRIdentificationNumberField() self.assertEqual(f.clean("10000000146"), "10000000146") self.assertRaisesRegexp(ValidationError, 'Enter a valid Turkish Identification number.', f.clean, "10000000136") self.assertRaisesRegexp(ValidationError, 'Enter a valid Turkish Identification number.', f.clean, "10000000147") self.assertRaisesRegexp(ValidationError, 'Turkish Identification number must be 11 digits.', f.clean, "123456789") self.assertRaisesRegexp(ValidationError, 'Enter a valid Turkish Identification number.', f.clean, "1000000014x") self.assertRaisesRegexp(ValidationError, 'Enter a valid Turkish Identification number.', f.clean, "x0000000146")
3,456
Python
.py
69
40.043478
68
0.654153
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,926
es.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/es.py
from django.contrib.localflavor.es.forms import (ESPostalCodeField, ESPhoneNumberField, ESIdentityCardNumberField, ESCCCField, ESRegionSelect, ESProvinceSelect) from utils import LocalFlavorTestCase class ESLocalFlavorTests(LocalFlavorTestCase): def test_ESRegionSelect(self): f = ESRegionSelect() out = u'''<select name="regions"> <option value="AN">Andalusia</option> <option value="AR">Aragon</option> <option value="O">Principality of Asturias</option> <option value="IB">Balearic Islands</option> <option value="PV">Basque Country</option> <option value="CN">Canary Islands</option> <option value="S">Cantabria</option> <option value="CM">Castile-La Mancha</option> <option value="CL">Castile and Leon</option> <option value="CT" selected="selected">Catalonia</option> <option value="EX">Extremadura</option> <option value="GA">Galicia</option> <option value="LO">La Rioja</option> <option value="M">Madrid</option> <option value="MU">Region of Murcia</option> <option value="NA">Foral Community of Navarre</option> <option value="VC">Valencian Community</option> </select>''' self.assertEqual(f.render('regions', 'CT'), out) def test_ESProvinceSelect(self): f = ESProvinceSelect() out = u'''<select name="provinces"> <option value="01">Arava</option> <option value="02">Albacete</option> <option value="03">Alacant</option> <option value="04">Almeria</option> <option value="05">Avila</option> <option value="06">Badajoz</option> <option value="07">Illes Balears</option> <option value="08" selected="selected">Barcelona</option> <option value="09">Burgos</option> <option value="10">Caceres</option> <option value="11">Cadiz</option> <option value="12">Castello</option> <option value="13">Ciudad Real</option> <option value="14">Cordoba</option> <option value="15">A Coruna</option> <option value="16">Cuenca</option> <option value="17">Girona</option> <option value="18">Granada</option> <option value="19">Guadalajara</option> <option value="20">Guipuzkoa</option> <option value="21">Huelva</option> <option value="22">Huesca</option> <option value="23">Jaen</option> <option value="24">Leon</option> <option value="25">Lleida</option> <option value="26">La Rioja</option> <option value="27">Lugo</option> <option value="28">Madrid</option> <option value="29">Malaga</option> <option value="30">Murcia</option> <option value="31">Navarre</option> <option value="32">Ourense</option> <option value="33">Asturias</option> <option value="34">Palencia</option> <option value="35">Las Palmas</option> <option value="36">Pontevedra</option> <option value="37">Salamanca</option> <option value="38">Santa Cruz de Tenerife</option> <option value="39">Cantabria</option> <option value="40">Segovia</option> <option value="41">Seville</option> <option value="42">Soria</option> <option value="43">Tarragona</option> <option value="44">Teruel</option> <option value="45">Toledo</option> <option value="46">Valencia</option> <option value="47">Valladolid</option> <option value="48">Bizkaia</option> <option value="49">Zamora</option> <option value="50">Zaragoza</option> <option value="51">Ceuta</option> <option value="52">Melilla</option> </select>''' self.assertEqual(f.render('provinces', '08'), out) def test_ESPostalCodeField(self): error_invalid = [u'Enter a valid postal code in the range and format 01XXX - 52XXX.'] valid = { '08028': '08028', '28080': '28080', } invalid = { '53001': error_invalid, '0801': error_invalid, '080001': error_invalid, '00999': error_invalid, '08 01': error_invalid, '08A01': error_invalid, } self.assertFieldOutput(ESPostalCodeField, valid, invalid) def test_ESPhoneNumberField(self): error_invalid = [u'Enter a valid phone number in one of the formats 6XXXXXXXX, 8XXXXXXXX or 9XXXXXXXX.'] valid = { '650010101': '650010101', '931234567': '931234567', '800123123': '800123123', } invalid = { '555555555': error_invalid, '789789789': error_invalid, '99123123': error_invalid, '9999123123': error_invalid, } self.assertFieldOutput(ESPhoneNumberField, valid, invalid) def test_ESIdentityCardNumberField(self): error_invalid = [u'Please enter a valid NIF, NIE, or CIF.'] error_checksum_nif = [u'Invalid checksum for NIF.'] error_checksum_nie = [u'Invalid checksum for NIE.'] error_checksum_cif = [u'Invalid checksum for CIF.'] valid = { '78699688J': '78699688J', '78699688-J': '78699688J', '78699688 J': '78699688J', '78699688 j': '78699688J', 'X0901797J': 'X0901797J', 'X-6124387-Q': 'X6124387Q', 'X 0012953 G': 'X0012953G', 'x-3287690-r': 'X3287690R', 't-03287690r': 'T03287690R', 'P2907500I': 'P2907500I', 'B38790911': 'B38790911', 'B31234560': 'B31234560', 'B-3879091A': 'B3879091A', 'B 38790911': 'B38790911', 'P-3900800-H': 'P3900800H', 'P 39008008': 'P39008008', 'C-28795565': 'C28795565', 'C 2879556E': 'C2879556E', } invalid = { '78699688T': error_checksum_nif, 'X-03287690': error_invalid, 'X-03287690-T': error_checksum_nie, 'B 38790917': error_checksum_cif, 'C28795567': error_checksum_cif, 'I38790911': error_invalid, '78699688-2': error_invalid, } self.assertFieldOutput(ESIdentityCardNumberField, valid, invalid) def test_ESCCCField(self): error_invalid = [u'Please enter a valid bank account number in format XXXX-XXXX-XX-XXXXXXXXXX.'] error_checksum = [u'Invalid checksum for bank account number.'] valid = { '20770338793100254321': '20770338793100254321', '2077 0338 79 3100254321': '2077 0338 79 3100254321', '2077-0338-79-3100254321': '2077-0338-79-3100254321', } invalid = { '2077.0338.79.3100254321': error_invalid, '2077-0338-78-3100254321': error_checksum, '2077-0338-89-3100254321': error_checksum, '2077-03-3879-3100254321': error_invalid, } self.assertFieldOutput(ESCCCField, valid, invalid)
6,531
Python
.py
162
33.895062
112
0.652242
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,927
kw.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/kw.py
from django.contrib.localflavor.kw.forms import KWCivilIDNumberField from utils import LocalFlavorTestCase class KWLocalFlavorTests(LocalFlavorTestCase): def test_KWCivilIDNumberField(self): error_invalid = [u'Enter a valid Kuwaiti Civil ID number'] valid = { '282040701483': '282040701483', } invalid = { '289332013455': error_invalid, } self.assertFieldOutput(KWCivilIDNumberField, valid, invalid)
480
Python
.py
12
32.333333
68
0.700431
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,928
br.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/br.py
from django.contrib.localflavor.br.forms import (BRZipCodeField, BRCNPJField, BRCPFField, BRPhoneNumberField, BRStateSelect, BRStateChoiceField) from utils import LocalFlavorTestCase class BRLocalFlavorTests(LocalFlavorTestCase): def test_BRZipCodeField(self): error_format = [u'Enter a zip code in the format XXXXX-XXX.'] valid = { '12345-123': '12345-123', } invalid = { '12345_123': error_format, '1234-123': error_format, 'abcde-abc': error_format, '12345-': error_format, '-123': error_format, } self.assertFieldOutput(BRZipCodeField, valid, invalid) def test_BRCNPJField(self): error_format = [u'Invalid CNPJ number.'] error_numbersonly = [u'This field requires only numbers.'] valid = { '64.132.916/0001-88': '64.132.916/0001-88', '64-132-916/0001-88': '64-132-916/0001-88', '64132916/0001-88': '64132916/0001-88', } invalid = { '12-345-678/9012-10': error_format, '12.345.678/9012-10': error_format, '12345678/9012-10': error_format, '64.132.916/0001-XX': error_numbersonly, } self.assertFieldOutput(BRCNPJField, valid, invalid) def test_BRCPFField(self): error_format = [u'Invalid CPF number.'] error_numbersonly = [u'This field requires only numbers.'] error_atmost_chars = [u'Ensure this value has at most 14 characters (it has 15).'] error_atleast_chars = [u'Ensure this value has at least 11 characters (it has 10).'] error_atmost = [u'This field requires at most 11 digits or 14 characters.'] valid = { '663.256.017-26': '663.256.017-26', '66325601726': '66325601726', '375.788.573-20': '375.788.573-20', '84828509895': '84828509895', } invalid = { '489.294.654-54': error_format, '295.669.575-98': error_format, '539.315.127-22': error_format, '375.788.573-XX': error_numbersonly, '375.788.573-000': error_atmost_chars, '123.456.78': error_atleast_chars, '123456789555': error_atmost, } self.assertFieldOutput(BRCPFField, valid, invalid) def test_BRPhoneNumberField(self): # TODO: this doesn't test for any invalid inputs. valid = { '41-3562-3464': u'41-3562-3464', '4135623464': u'41-3562-3464', '41 3562-3464': u'41-3562-3464', '41 3562 3464': u'41-3562-3464', '(41) 3562 3464': u'41-3562-3464', '41.3562.3464': u'41-3562-3464', '41.3562-3464': u'41-3562-3464', ' (41) 3562.3464': u'41-3562-3464', } invalid = {} self.assertFieldOutput(BRPhoneNumberField, valid, invalid) def test_BRStateSelect(self): f = BRStateSelect() out = u'''<select name="states"> <option value="AC">Acre</option> <option value="AL">Alagoas</option> <option value="AP">Amap\xe1</option> <option value="AM">Amazonas</option> <option value="BA">Bahia</option> <option value="CE">Cear\xe1</option> <option value="DF">Distrito Federal</option> <option value="ES">Esp\xedrito Santo</option> <option value="GO">Goi\xe1s</option> <option value="MA">Maranh\xe3o</option> <option value="MT">Mato Grosso</option> <option value="MS">Mato Grosso do Sul</option> <option value="MG">Minas Gerais</option> <option value="PA">Par\xe1</option> <option value="PB">Para\xedba</option> <option value="PR" selected="selected">Paran\xe1</option> <option value="PE">Pernambuco</option> <option value="PI">Piau\xed</option> <option value="RJ">Rio de Janeiro</option> <option value="RN">Rio Grande do Norte</option> <option value="RS">Rio Grande do Sul</option> <option value="RO">Rond\xf4nia</option> <option value="RR">Roraima</option> <option value="SC">Santa Catarina</option> <option value="SP">S\xe3o Paulo</option> <option value="SE">Sergipe</option> <option value="TO">Tocantins</option> </select>''' self.assertEqual(f.render('states', 'PR'), out) def test_BRStateChoiceField(self): error_invalid = [u'Select a valid brazilian state. That state is not one of the available states.'] valid = { 'AC': 'AC', 'AL': 'AL', 'AP': 'AP', 'AM': 'AM', 'BA': 'BA', 'CE': 'CE', 'DF': 'DF', 'ES': 'ES', 'GO': 'GO', 'MA': 'MA', 'MT': 'MT', 'MS': 'MS', 'MG': 'MG', 'PA': 'PA', 'PB': 'PB', 'PR': 'PR', 'PE': 'PE', 'PI': 'PI', 'RJ': 'RJ', 'RN': 'RN', 'RS': 'RS', 'RO': 'RO', 'RR': 'RR', 'SC': 'SC', 'SP': 'SP', 'SE': 'SE', 'TO': 'TO', } invalid = { 'pr': error_invalid, } self.assertFieldOutput(BRStateChoiceField, valid, invalid)
5,144
Python
.py
136
29.058824
107
0.5658
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,929
ar.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/ar.py
from django.contrib.localflavor.ar.forms import (ARProvinceSelect, ARPostalCodeField, ARDNIField, ARCUITField) from utils import LocalFlavorTestCase class ARLocalFlavorTests(LocalFlavorTestCase): def test_ARProvinceSelect(self): f = ARProvinceSelect() out = u'''<select name="provincias"> <option value="B">Buenos Aires</option> <option value="K">Catamarca</option> <option value="H">Chaco</option> <option value="U">Chubut</option> <option value="C">Ciudad Aut\xf3noma de Buenos Aires</option> <option value="X">C\xf3rdoba</option> <option value="W">Corrientes</option> <option value="E">Entre R\xedos</option> <option value="P">Formosa</option> <option value="Y">Jujuy</option> <option value="L">La Pampa</option> <option value="F">La Rioja</option> <option value="M">Mendoza</option> <option value="N">Misiones</option> <option value="Q">Neuqu\xe9n</option> <option value="R">R\xedo Negro</option> <option value="A" selected="selected">Salta</option> <option value="J">San Juan</option> <option value="D">San Luis</option> <option value="Z">Santa Cruz</option> <option value="S">Santa Fe</option> <option value="G">Santiago del Estero</option> <option value="V">Tierra del Fuego, Ant\xe1rtida e Islas del Atl\xe1ntico Sur</option> <option value="T">Tucum\xe1n</option> </select>''' self.assertEqual(f.render('provincias', 'A'), out) def test_ARPostalCodeField(self): error_format = [u'Enter a postal code in the format NNNN or ANNNNAAA.'] error_atmost = [u'Ensure this value has at most 8 characters (it has 9).'] error_atleast = [u'Ensure this value has at least 4 characters (it has 3).'] valid = { '5000': '5000', 'C1064AAB': 'C1064AAB', 'c1064AAB': 'C1064AAB', 'C1064aab': 'C1064AAB', '4400': '4400', u'C1064AAB': 'C1064AAB', } invalid = { 'C1064AABB': error_atmost + error_format, 'C1064AA': error_format, 'C1064AB': error_format, '106AAB': error_format, '500': error_atleast + error_format, '5PPP': error_format, } self.assertFieldOutput(ARPostalCodeField, valid, invalid) def test_ARDNIField(self): error_length = [u'This field requires 7 or 8 digits.'] error_digitsonly = [u'This field requires only numbers.'] valid = { '20123456': '20123456', '20.123.456': '20123456', u'20123456': '20123456', u'20.123.456': '20123456', '20.123456': '20123456', '9123456': '9123456', '9.123.456': '9123456', } invalid = { '101234566': error_length, 'W0123456': error_digitsonly, '10,123,456': error_digitsonly, } self.assertFieldOutput(ARDNIField, valid, invalid) def test_ARCUITField(self): error_format = [u'Enter a valid CUIT in XX-XXXXXXXX-X or XXXXXXXXXXXX format.'] error_invalid = [u'Invalid CUIT.'] valid = { '20-10123456-9': '20-10123456-9', u'20-10123456-9': '20-10123456-9', '27-10345678-4': '27-10345678-4', '20101234569': '20-10123456-9', '27103456784': '27-10345678-4', } invalid = { '2-10123456-9': error_format, '210123456-9': error_format, '20-10123456': error_format, '20-10123456-': error_format, '20-10123456-5': error_invalid, '2-10123456-9': error_format, '27-10345678-1': error_invalid, u'27-10345678-1': error_invalid, } self.assertFieldOutput(ARCUITField, valid, invalid)
3,743
Python
.py
93
32.268817
87
0.611416
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,930
jp.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/jp.py
from django.contrib.localflavor.jp.forms import (JPPostalCodeField, JPPrefectureSelect) from utils import LocalFlavorTestCase class JPLocalFlavorTests(LocalFlavorTestCase): def test_JPPrefectureSelect(self): f = JPPrefectureSelect() out = u'''<select name="prefecture"> <option value="hokkaido">Hokkaido</option> <option value="aomori">Aomori</option> <option value="iwate">Iwate</option> <option value="miyagi">Miyagi</option> <option value="akita">Akita</option> <option value="yamagata">Yamagata</option> <option value="fukushima">Fukushima</option> <option value="ibaraki">Ibaraki</option> <option value="tochigi">Tochigi</option> <option value="gunma">Gunma</option> <option value="saitama">Saitama</option> <option value="chiba">Chiba</option> <option value="tokyo">Tokyo</option> <option value="kanagawa" selected="selected">Kanagawa</option> <option value="yamanashi">Yamanashi</option> <option value="nagano">Nagano</option> <option value="niigata">Niigata</option> <option value="toyama">Toyama</option> <option value="ishikawa">Ishikawa</option> <option value="fukui">Fukui</option> <option value="gifu">Gifu</option> <option value="shizuoka">Shizuoka</option> <option value="aichi">Aichi</option> <option value="mie">Mie</option> <option value="shiga">Shiga</option> <option value="kyoto">Kyoto</option> <option value="osaka">Osaka</option> <option value="hyogo">Hyogo</option> <option value="nara">Nara</option> <option value="wakayama">Wakayama</option> <option value="tottori">Tottori</option> <option value="shimane">Shimane</option> <option value="okayama">Okayama</option> <option value="hiroshima">Hiroshima</option> <option value="yamaguchi">Yamaguchi</option> <option value="tokushima">Tokushima</option> <option value="kagawa">Kagawa</option> <option value="ehime">Ehime</option> <option value="kochi">Kochi</option> <option value="fukuoka">Fukuoka</option> <option value="saga">Saga</option> <option value="nagasaki">Nagasaki</option> <option value="kumamoto">Kumamoto</option> <option value="oita">Oita</option> <option value="miyazaki">Miyazaki</option> <option value="kagoshima">Kagoshima</option> <option value="okinawa">Okinawa</option> </select>''' self.assertEqual(f.render('prefecture', 'kanagawa'), out) def test_JPPostalCodeField(self): error_format = [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] valid = { '251-0032': '2510032', '2510032': '2510032', } invalid = { '2510-032': error_format, '251a0032': error_format, 'a51-0032': error_format, '25100321': error_format, } self.assertFieldOutput(JPPostalCodeField, valid, invalid)
2,762
Python
.py
69
36.362319
82
0.72183
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,931
nl.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/nl.py
from django.contrib.localflavor.nl.forms import (NLPhoneNumberField, NLZipCodeField, NLSoFiNumberField, NLProvinceSelect) from utils import LocalFlavorTestCase class NLLocalFlavorTests(LocalFlavorTestCase): def test_NLProvinceSelect(self): f = NLProvinceSelect() out = u'''<select name="provinces"> <option value="DR">Drenthe</option> <option value="FL">Flevoland</option> <option value="FR">Friesland</option> <option value="GL">Gelderland</option> <option value="GR">Groningen</option> <option value="LB">Limburg</option> <option value="NB">Noord-Brabant</option> <option value="NH">Noord-Holland</option> <option value="OV" selected="selected">Overijssel</option> <option value="UT">Utrecht</option> <option value="ZE">Zeeland</option> <option value="ZH">Zuid-Holland</option> </select>''' self.assertEqual(f.render('provinces', 'OV'), out) def test_NLPhoneNumberField(self): error_invalid = [u'Enter a valid phone number'] valid = { '012-3456789': '012-3456789', '0123456789': '0123456789', '+31-12-3456789': '+31-12-3456789', '(0123) 456789': '(0123) 456789', } invalid = { 'foo': error_invalid, } self.assertFieldOutput(NLPhoneNumberField, valid, invalid) def test_NLZipCodeField(self): error_invalid = [u'Enter a valid postal code'] valid = { '1234ab': '1234 AB', '1234 ab': '1234 AB', '1234 AB': '1234 AB', } invalid = { '0123AB': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(NLZipCodeField, valid, invalid) def test_NLSoFiNumberField(self): error_invalid = [u'Enter a valid SoFi number'] valid = { '123456782': '123456782', } invalid = { '000000000': error_invalid, '123456789': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(NLSoFiNumberField, valid, invalid)
2,084
Python
.py
56
29.392857
68
0.620673
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,932
sk.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/sk.py
from django.contrib.localflavor.sk.forms import (SKRegionSelect, SKPostalCodeField, SKDistrictSelect) from utils import LocalFlavorTestCase class SKLocalFlavorTests(LocalFlavorTestCase): def test_SKRegionSelect(self): f = SKRegionSelect() out = u'''<select name="regions"> <option value="BB">Banska Bystrica region</option> <option value="BA">Bratislava region</option> <option value="KE">Kosice region</option> <option value="NR">Nitra region</option> <option value="PO">Presov region</option> <option value="TN">Trencin region</option> <option value="TT" selected="selected">Trnava region</option> <option value="ZA">Zilina region</option> </select>''' self.assertEqual(f.render('regions', 'TT'), out) def test_SKDistrictSelect(self): f = SKDistrictSelect() out = u'''<select name="Districts"> <option value="BB">Banska Bystrica</option> <option value="BS">Banska Stiavnica</option> <option value="BJ">Bardejov</option> <option value="BN">Banovce nad Bebravou</option> <option value="BR">Brezno</option> <option value="BA1">Bratislava I</option> <option value="BA2">Bratislava II</option> <option value="BA3">Bratislava III</option> <option value="BA4">Bratislava IV</option> <option value="BA5">Bratislava V</option> <option value="BY">Bytca</option> <option value="CA">Cadca</option> <option value="DT">Detva</option> <option value="DK">Dolny Kubin</option> <option value="DS">Dunajska Streda</option> <option value="GA">Galanta</option> <option value="GL">Gelnica</option> <option value="HC">Hlohovec</option> <option value="HE">Humenne</option> <option value="IL">Ilava</option> <option value="KK">Kezmarok</option> <option value="KN">Komarno</option> <option value="KE1">Kosice I</option> <option value="KE2">Kosice II</option> <option value="KE3">Kosice III</option> <option value="KE4">Kosice IV</option> <option value="KEO">Kosice - okolie</option> <option value="KA">Krupina</option> <option value="KM">Kysucke Nove Mesto</option> <option value="LV">Levice</option> <option value="LE">Levoca</option> <option value="LM">Liptovsky Mikulas</option> <option value="LC">Lucenec</option> <option value="MA">Malacky</option> <option value="MT">Martin</option> <option value="ML">Medzilaborce</option> <option value="MI">Michalovce</option> <option value="MY">Myjava</option> <option value="NO">Namestovo</option> <option value="NR">Nitra</option> <option value="NM">Nove Mesto nad Vahom</option> <option value="NZ">Nove Zamky</option> <option value="PE">Partizanske</option> <option value="PK">Pezinok</option> <option value="PN">Piestany</option> <option value="PT">Poltar</option> <option value="PP">Poprad</option> <option value="PB">Povazska Bystrica</option> <option value="PO">Presov</option> <option value="PD">Prievidza</option> <option value="PU">Puchov</option> <option value="RA">Revuca</option> <option value="RS">Rimavska Sobota</option> <option value="RV">Roznava</option> <option value="RK" selected="selected">Ruzomberok</option> <option value="SB">Sabinov</option> <option value="SC">Senec</option> <option value="SE">Senica</option> <option value="SI">Skalica</option> <option value="SV">Snina</option> <option value="SO">Sobrance</option> <option value="SN">Spisska Nova Ves</option> <option value="SL">Stara Lubovna</option> <option value="SP">Stropkov</option> <option value="SK">Svidnik</option> <option value="SA">Sala</option> <option value="TO">Topolcany</option> <option value="TV">Trebisov</option> <option value="TN">Trencin</option> <option value="TT">Trnava</option> <option value="TR">Turcianske Teplice</option> <option value="TS">Tvrdosin</option> <option value="VK">Velky Krtis</option> <option value="VT">Vranov nad Toplou</option> <option value="ZM">Zlate Moravce</option> <option value="ZV">Zvolen</option> <option value="ZC">Zarnovica</option> <option value="ZH">Ziar nad Hronom</option> <option value="ZA">Zilina</option> </select>''' self.assertEqual(f.render('Districts', 'RK'), out) def test_SKPostalCodeField(self): error_format = [u'Enter a postal code in the format XXXXX or XXX XX.'] valid = { '91909': '91909', '917 01': '91701', } invalid = { '84545x': error_format, } self.assertFieldOutput(SKPostalCodeField, valid, invalid)
4,333
Python
.py
111
36.657658
78
0.727294
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,933
utils.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/utils.py
from django.core.exceptions import ValidationError from django.core.validators import EMPTY_VALUES from django.test.utils import get_warnings_state, restore_warnings_state from django.utils.unittest import TestCase class LocalFlavorTestCase(TestCase): # NOTE: These are copied from the TestCase Django uses for tests which # access the database def save_warnings_state(self): self._warnings_state = get_warnings_state() def restore_warnings_state(self): restore_warnings_state(self._warnings_state) def assertFieldOutput(self, fieldclass, valid, invalid, field_args=[], field_kwargs={}, empty_value=u''): """ Asserts that a field behaves correctly with various inputs. Args: fieldclass: the class of the field to be tested. valid: a dictionary mapping valid inputs to their expected cleaned values. invalid: a dictionary mapping invalid inputs to one or more raised error messages. field_args: the args passed to instantiate the field field_kwargs: the kwargs passed to instantiate the field empty_value: the expected clean output for inputs in EMPTY_VALUES """ required = fieldclass(*field_args, **field_kwargs) optional = fieldclass(*field_args, **dict(field_kwargs, required=False)) # test valid inputs for input, output in valid.items(): self.assertEqual(required.clean(input), output) self.assertEqual(optional.clean(input), output) # test invalid inputs for input, errors in invalid.items(): self.assertRaisesRegexp(ValidationError, unicode(errors), required.clean, input ) self.assertRaisesRegexp(ValidationError, unicode(errors), optional.clean, input ) # test required inputs error_required = u'This field is required' for e in EMPTY_VALUES: self.assertRaisesRegexp(ValidationError, error_required, required.clean, e) self.assertEqual(optional.clean(e), empty_value)
2,190
Python
.py
45
38.466667
80
0.662459
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,934
za.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/za.py
from django.contrib.localflavor.za.forms import ZAIDField, ZAPostCodeField from utils import LocalFlavorTestCase class ZALocalFlavorTests(LocalFlavorTestCase): def test_ZAIDField(self): error_invalid = [u'Enter a valid South African ID number'] valid = { '0002290001003': '0002290001003', '000229 0001 003': '0002290001003', } invalid = { '0102290001001': error_invalid, '811208': error_invalid, '0002290001004': error_invalid, } self.assertFieldOutput(ZAIDField, valid, invalid) def test_ZAPostCodeField(self): error_invalid = [u'Enter a valid South African postal code'] valid = { '0000': '0000', } invalid = { 'abcd': error_invalid, ' 7530': error_invalid, } self.assertFieldOutput(ZAPostCodeField, valid, invalid)
922
Python
.py
25
27.72
74
0.617021
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,935
generic.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/generic.py
import datetime from django.contrib.localflavor.generic.forms import DateField, DateTimeField from utils import LocalFlavorTestCase class GenericLocalFlavorTests(LocalFlavorTestCase): def test_GenericDateField(self): error_invalid = [u'Enter a valid date.'] valid = { datetime.date(2006, 10, 25): datetime.date(2006, 10, 25), datetime.datetime(2006, 10, 25, 14, 30): datetime.date(2006, 10, 25), datetime.datetime(2006, 10, 25, 14, 30, 59): datetime.date(2006, 10, 25), datetime.datetime(2006, 10, 25, 14, 30, 59, 200): datetime.date(2006, 10, 25), '2006-10-25': datetime.date(2006, 10, 25), '25/10/2006': datetime.date(2006, 10, 25), '25/10/06': datetime.date(2006, 10, 25), 'Oct 25 2006': datetime.date(2006, 10, 25), 'October 25 2006': datetime.date(2006, 10, 25), 'October 25, 2006': datetime.date(2006, 10, 25), '25 October 2006': datetime.date(2006, 10, 25), '25 October, 2006': datetime.date(2006, 10, 25), } invalid = { '2006-4-31': error_invalid, '200a-10-25': error_invalid, '10/25/06': error_invalid, } self.assertFieldOutput(DateField, valid, invalid, empty_value=None) # DateField with optional input_formats parameter valid = { datetime.date(2006, 10, 25): datetime.date(2006, 10, 25), datetime.datetime(2006, 10, 25, 14, 30): datetime.date(2006, 10, 25), '2006 10 25': datetime.date(2006, 10, 25), } invalid = { '2006-10-25': error_invalid, '25/10/2006': error_invalid, '25/10/06': error_invalid, } kwargs = {'input_formats':['%Y %m %d'],} self.assertFieldOutput(DateField, valid, invalid, field_kwargs=kwargs, empty_value=None ) def test_GenericDateTimeField(self): error_invalid = [u'Enter a valid date/time.'] valid = { datetime.date(2006, 10, 25): datetime.datetime(2006, 10, 25, 0, 0), datetime.datetime(2006, 10, 25, 14, 30): datetime.datetime(2006, 10, 25, 14, 30), datetime.datetime(2006, 10, 25, 14, 30, 59): datetime.datetime(2006, 10, 25, 14, 30, 59), datetime.datetime(2006, 10, 25, 14, 30, 59, 200): datetime.datetime(2006, 10, 25, 14, 30, 59, 200), '2006-10-25 14:30:45': datetime.datetime(2006, 10, 25, 14, 30, 45), '2006-10-25 14:30:00': datetime.datetime(2006, 10, 25, 14, 30), '2006-10-25 14:30': datetime.datetime(2006, 10, 25, 14, 30), '2006-10-25': datetime.datetime(2006, 10, 25, 0, 0), '25/10/2006 14:30:45': datetime.datetime(2006, 10, 25, 14, 30, 45), '25/10/2006 14:30:00': datetime.datetime(2006, 10, 25, 14, 30), '25/10/2006 14:30': datetime.datetime(2006, 10, 25, 14, 30), '25/10/2006': datetime.datetime(2006, 10, 25, 0, 0), '25/10/06 14:30:45': datetime.datetime(2006, 10, 25, 14, 30, 45), '25/10/06 14:30:00': datetime.datetime(2006, 10, 25, 14, 30), '25/10/06 14:30': datetime.datetime(2006, 10, 25, 14, 30), '25/10/06': datetime.datetime(2006, 10, 25, 0, 0), } invalid = { 'hello': error_invalid, '2006-10-25 4:30 p.m.': error_invalid, } self.assertFieldOutput(DateTimeField, valid, invalid, empty_value=None) # DateTimeField with optional input_formats paramter valid = { datetime.date(2006, 10, 25): datetime.datetime(2006, 10, 25, 0, 0), datetime.datetime(2006, 10, 25, 14, 30): datetime.datetime(2006, 10, 25, 14, 30), datetime.datetime(2006, 10, 25, 14, 30, 59): datetime.datetime(2006, 10, 25, 14, 30, 59), datetime.datetime(2006, 10, 25, 14, 30, 59, 200): datetime.datetime(2006, 10, 25, 14, 30, 59, 200), '2006 10 25 2:30 PM': datetime.datetime(2006, 10, 25, 14, 30), } invalid = { '2006-10-25 14:30:45': error_invalid, } kwargs = {'input_formats':['%Y %m %d %I:%M %p'],} self.assertFieldOutput(DateTimeField, valid, invalid, field_kwargs=kwargs, empty_value=None )
4,326
Python
.py
81
42.493827
111
0.573148
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,936
is_.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/is_.py
from django.contrib.localflavor.is_.forms import (ISIdNumberField, ISPhoneNumberField, ISPostalCodeSelect) from utils import LocalFlavorTestCase class ISLocalFlavorTests(LocalFlavorTestCase): def test_ISPostalCodeSelect(self): f = ISPostalCodeSelect() out = u'''<select name="foo"> <option value="101">101 Reykjav\xedk</option> <option value="103">103 Reykjav\xedk</option> <option value="104">104 Reykjav\xedk</option> <option value="105">105 Reykjav\xedk</option> <option value="107">107 Reykjav\xedk</option> <option value="108">108 Reykjav\xedk</option> <option value="109">109 Reykjav\xedk</option> <option value="110">110 Reykjav\xedk</option> <option value="111">111 Reykjav\xedk</option> <option value="112">112 Reykjav\xedk</option> <option value="113">113 Reykjav\xedk</option> <option value="116">116 Kjalarnes</option> <option value="121">121 Reykjav\xedk</option> <option value="123">123 Reykjav\xedk</option> <option value="124">124 Reykjav\xedk</option> <option value="125">125 Reykjav\xedk</option> <option value="127">127 Reykjav\xedk</option> <option value="128">128 Reykjav\xedk</option> <option value="129">129 Reykjav\xedk</option> <option value="130">130 Reykjav\xedk</option> <option value="132">132 Reykjav\xedk</option> <option value="150">150 Reykjav\xedk</option> <option value="155">155 Reykjav\xedk</option> <option value="170">170 Seltjarnarnes</option> <option value="172">172 Seltjarnarnes</option> <option value="190">190 Vogar</option> <option value="200">200 K\xf3pavogur</option> <option value="201">201 K\xf3pavogur</option> <option value="202">202 K\xf3pavogur</option> <option value="203">203 K\xf3pavogur</option> <option value="210">210 Gar\xf0ab\xe6r</option> <option value="212">212 Gar\xf0ab\xe6r</option> <option value="220">220 Hafnarfj\xf6r\xf0ur</option> <option value="221">221 Hafnarfj\xf6r\xf0ur</option> <option value="222">222 Hafnarfj\xf6r\xf0ur</option> <option value="225">225 \xc1lftanes</option> <option value="230">230 Reykjanesb\xe6r</option> <option value="232">232 Reykjanesb\xe6r</option> <option value="233">233 Reykjanesb\xe6r</option> <option value="235">235 Keflav\xedkurflugv\xf6llur</option> <option value="240">240 Grindav\xedk</option> <option value="245">245 Sandger\xf0i</option> <option value="250">250 Gar\xf0ur</option> <option value="260">260 Reykjanesb\xe6r</option> <option value="270">270 Mosfellsb\xe6r</option> <option value="300">300 Akranes</option> <option value="301">301 Akranes</option> <option value="302">302 Akranes</option> <option value="310">310 Borgarnes</option> <option value="311">311 Borgarnes</option> <option value="320">320 Reykholt \xed Borgarfir\xf0i</option> <option value="340">340 Stykkish\xf3lmur</option> <option value="345">345 Flatey \xe1 Brei\xf0afir\xf0i</option> <option value="350">350 Grundarfj\xf6r\xf0ur</option> <option value="355">355 \xd3lafsv\xedk</option> <option value="356">356 Sn\xe6fellsb\xe6r</option> <option value="360">360 Hellissandur</option> <option value="370">370 B\xfa\xf0ardalur</option> <option value="371">371 B\xfa\xf0ardalur</option> <option value="380">380 Reykh\xf3lahreppur</option> <option value="400">400 \xcdsafj\xf6r\xf0ur</option> <option value="401">401 \xcdsafj\xf6r\xf0ur</option> <option value="410">410 Hn\xedfsdalur</option> <option value="415">415 Bolungarv\xedk</option> <option value="420">420 S\xfa\xf0av\xedk</option> <option value="425">425 Flateyri</option> <option value="430">430 Su\xf0ureyri</option> <option value="450">450 Patreksfj\xf6r\xf0ur</option> <option value="451">451 Patreksfj\xf6r\xf0ur</option> <option value="460">460 T\xe1lknafj\xf6r\xf0ur</option> <option value="465">465 B\xedldudalur</option> <option value="470">470 \xdeingeyri</option> <option value="471">471 \xdeingeyri</option> <option value="500">500 Sta\xf0ur</option> <option value="510">510 H\xf3lmav\xedk</option> <option value="512">512 H\xf3lmav\xedk</option> <option value="520">520 Drangsnes</option> <option value="522">522 Kj\xf6rvogur</option> <option value="523">523 B\xe6r</option> <option value="524">524 Nor\xf0urfj\xf6r\xf0ur</option> <option value="530">530 Hvammstangi</option> <option value="531">531 Hvammstangi</option> <option value="540">540 Bl\xf6ndu\xf3s</option> <option value="541">541 Bl\xf6ndu\xf3s</option> <option value="545">545 Skagastr\xf6nd</option> <option value="550">550 Sau\xf0\xe1rkr\xf3kur</option> <option value="551">551 Sau\xf0\xe1rkr\xf3kur</option> <option value="560">560 Varmahl\xed\xf0</option> <option value="565">565 Hofs\xf3s</option> <option value="566">566 Hofs\xf3s</option> <option value="570">570 Flj\xf3t</option> <option value="580">580 Siglufj\xf6r\xf0ur</option> <option value="600">600 Akureyri</option> <option value="601">601 Akureyri</option> <option value="602">602 Akureyri</option> <option value="603">603 Akureyri</option> <option value="610">610 Greniv\xedk</option> <option value="611">611 Gr\xedmsey</option> <option value="620">620 Dalv\xedk</option> <option value="621">621 Dalv\xedk</option> <option value="625">625 \xd3lafsfj\xf6r\xf0ur</option> <option value="630">630 Hr\xedsey</option> <option value="640">640 H\xfasav\xedk</option> <option value="641">641 H\xfasav\xedk</option> <option value="645">645 Fossh\xf3ll</option> <option value="650">650 Laugar</option> <option value="660">660 M\xfdvatn</option> <option value="670">670 K\xf3pasker</option> <option value="671">671 K\xf3pasker</option> <option value="675">675 Raufarh\xf6fn</option> <option value="680">680 \xde\xf3rsh\xf6fn</option> <option value="681">681 \xde\xf3rsh\xf6fn</option> <option value="685">685 Bakkafj\xf6r\xf0ur</option> <option value="690">690 Vopnafj\xf6r\xf0ur</option> <option value="700">700 Egilssta\xf0ir</option> <option value="701">701 Egilssta\xf0ir</option> <option value="710">710 Sey\xf0isfj\xf6r\xf0ur</option> <option value="715">715 Mj\xf3ifj\xf6r\xf0ur</option> <option value="720">720 Borgarfj\xf6r\xf0ur eystri</option> <option value="730">730 Rey\xf0arfj\xf6r\xf0ur</option> <option value="735">735 Eskifj\xf6r\xf0ur</option> <option value="740">740 Neskaupsta\xf0ur</option> <option value="750">750 F\xe1skr\xfa\xf0sfj\xf6r\xf0ur</option> <option value="755">755 St\xf6\xf0varfj\xf6r\xf0ur</option> <option value="760">760 Brei\xf0dalsv\xedk</option> <option value="765">765 Dj\xfapivogur</option> <option value="780">780 H\xf6fn \xed Hornafir\xf0i</option> <option value="781">781 H\xf6fn \xed Hornafir\xf0i</option> <option value="785">785 \xd6r\xe6fi</option> <option value="800">800 Selfoss</option> <option value="801">801 Selfoss</option> <option value="802">802 Selfoss</option> <option value="810">810 Hverager\xf0i</option> <option value="815">815 \xdeorl\xe1ksh\xf6fn</option> <option value="820">820 Eyrarbakki</option> <option value="825">825 Stokkseyri</option> <option value="840">840 Laugarvatn</option> <option value="845">845 Fl\xfa\xf0ir</option> <option value="850">850 Hella</option> <option value="851">851 Hella</option> <option value="860">860 Hvolsv\xf6llur</option> <option value="861">861 Hvolsv\xf6llur</option> <option value="870">870 V\xedk</option> <option value="871">871 V\xedk</option> <option value="880">880 Kirkjub\xe6jarklaustur</option> <option value="900">900 Vestmannaeyjar</option> <option value="902">902 Vestmannaeyjar</option> </select>''' self.assertEqual(f.render('foo', 'bar'), out) def test_ISIdNumberField(self): error_atleast = [u'Ensure this value has at least 10 characters (it has 9).'] error_invalid = [u'Enter a valid Icelandic identification number. The format is XXXXXX-XXXX.'] error_atmost = [u'Ensure this value has at most 11 characters (it has 12).'] error_notvalid = [u'The Icelandic identification number is not valid.'] valid = { '2308803449': '230880-3449', '230880-3449': '230880-3449', '230880 3449': '230880-3449', '2308803440': '230880-3440', } invalid = { '230880343': error_atleast + error_invalid, '230880343234': error_atmost + error_invalid, 'abcdefghijk': error_invalid, '2308803439': error_notvalid, } self.assertFieldOutput(ISIdNumberField, valid, invalid) def test_ISPhoneNumberField(self): error_invalid = [u'Enter a valid value.'] error_atleast = [u'Ensure this value has at least 7 characters (it has 6).'] error_atmost = [u'Ensure this value has at most 8 characters (it has 9).'] valid = { '1234567': '1234567', '123 4567': '1234567', '123-4567': '1234567', } invalid = { '123-456': error_invalid, '123456': error_atleast + error_invalid, '123456555': error_atmost + error_invalid, 'abcdefg': error_invalid, ' 1234567 ': error_atmost + error_invalid, ' 12367 ': error_invalid } self.assertFieldOutput(ISPhoneNumberField, valid, invalid)
9,043
Python
.py
192
44
102
0.725193
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,937
us.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/us.py
from django.contrib.localflavor.us.forms import (USZipCodeField, USPhoneNumberField, USStateField, USStateSelect, USSocialSecurityNumberField) from utils import LocalFlavorTestCase class USLocalFlavorTests(LocalFlavorTestCase): def test_USStateSelect(self): f = USStateSelect() out = u'''<select name="state"> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AS">American Samoa</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="AA">Armed Forces Americas</option> <option value="AE">Armed Forces Europe</option> <option value="AP">Armed Forces Pacific</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DE">Delaware</option> <option value="DC">District of Columbia</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="GU">Guam</option> <option value="HI">Hawaii</option> <option value="ID">Idaho</option> <option value="IL" selected="selected">Illinois</option> <option value="IN">Indiana</option> <option value="IA">Iowa</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="ME">Maine</option> <option value="MD">Maryland</option> <option value="MA">Massachusetts</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MS">Mississippi</option> <option value="MO">Missouri</option> <option value="MT">Montana</option> <option value="NE">Nebraska</option> <option value="NV">Nevada</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NY">New York</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="MP">Northern Mariana Islands</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="PR">Puerto Rico</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VT">Vermont</option> <option value="VI">Virgin Islands</option> <option value="VA">Virginia</option> <option value="WA">Washington</option> <option value="WV">West Virginia</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </select>''' self.assertEqual(f.render('state', 'IL'), out) def test_USZipCodeField(self): error_format = [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.'] valid = { '60606': '60606', 60606: '60606', '04000': '04000', '60606-1234': '60606-1234', } invalid = { '4000': error_format, '6060-1234': error_format, '60606-': error_format, } self.assertFieldOutput(USZipCodeField, valid, invalid) def test_USPhoneNumberField(self): error_format = [u'Phone numbers must be in XXX-XXX-XXXX format.'] valid = { '312-555-1212': '312-555-1212', '3125551212': '312-555-1212', '312 555-1212': '312-555-1212', '(312) 555-1212': '312-555-1212', '312 555 1212': '312-555-1212', '312.555.1212': '312-555-1212', '312.555-1212': '312-555-1212', ' (312) 555.1212 ': '312-555-1212', } invalid = { '555-1212': error_format, '312-55-1212': error_format, } self.assertFieldOutput(USPhoneNumberField, valid, invalid) def test_USStateField(self): error_invalid = [u'Enter a U.S. state or territory.'] valid = { 'il': 'IL', 'IL': 'IL', 'illinois': 'IL', ' illinois ': 'IL', } invalid = { 60606: error_invalid, } self.assertFieldOutput(USStateField, valid, invalid) def test_USSocialSecurityNumberField(self): error_invalid = [u'Enter a valid U.S. Social Security number in XXX-XX-XXXX format.'] valid = { '987-65-4330': '987-65-4330', '987654330': '987-65-4330', } invalid = { '078-05-1120': error_invalid, } self.assertFieldOutput(USSocialSecurityNumberField, valid, invalid)
4,615
Python
.py
121
32.61157
93
0.656041
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,938
se.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/se.py
# -*- coding: utf-8 -*- from django.contrib.localflavor.se.forms import (SECountySelect, SEOrganisationNumberField, SEPersonalIdentityNumberField, SEPostalCodeField) import datetime from utils import LocalFlavorTestCase class SELocalFlavorTests(LocalFlavorTestCase): def setUp(self): # Mocking datetime.date to make sure # localflavor.se.utils.validate_id_birthday works class MockDate(datetime.date): def today(cls): return datetime.date(2008, 5, 14) today = classmethod(today) self._olddate = datetime.date datetime.date = MockDate def tearDown(self): datetime.date = self._olddate def test_SECountySelect(self): f = SECountySelect() out = u'''<select name="swedish_county"> <option value="AB">Stockholm</option> <option value="AC">V\xe4sterbotten</option> <option value="BD">Norrbotten</option> <option value="C">Uppsala</option> <option value="D">S\xf6dermanland</option> <option value="E" selected="selected">\xd6sterg\xf6tland</option> <option value="F">J\xf6nk\xf6ping</option> <option value="G">Kronoberg</option> <option value="H">Kalmar</option> <option value="I">Gotland</option> <option value="K">Blekinge</option> <option value="M">Sk\xe5ne</option> <option value="N">Halland</option> <option value="O">V\xe4stra G\xf6taland</option> <option value="S">V\xe4rmland</option> <option value="T">\xd6rebro</option> <option value="U">V\xe4stmanland</option> <option value="W">Dalarna</option> <option value="X">G\xe4vleborg</option> <option value="Y">V\xe4sternorrland</option> <option value="Z">J\xe4mtland</option> </select>''' self.assertEqual(f.render('swedish_county', 'E'), out) def test_SEOrganizationNumberField(self): error_invalid = [u'Enter a valid Swedish organisation number.'] valid = { '870512-1989': '198705121989', '19870512-1989': '198705121989', '870512-2128': '198705122128', '081015-6315': '190810156315', '081015+6315': '180810156315', '0810156315': '190810156315', # Test some different organisation numbers # IKEA Linköping '556074-7569': '5560747569', # Volvo Personvagnar '556074-3089': '5560743089', # LJS (organisation) '822001-5476': '8220015476', # LJS (organisation) '8220015476': '8220015476', # Katedralskolan Linköping (school) '2120000449': '2120000449', # Faux organisation number, which tests that the checksum can be 0 '232518-5060': '2325185060', } invalid = { # Ordinary personal identity numbers for sole proprietors # The same rules as for SEPersonalIdentityField applies here '081015 6315': error_invalid, '950231-4496': error_invalid, '6914104499': error_invalid, '950d314496': error_invalid, 'invalid!!!': error_invalid, '870514-1111': error_invalid, # Co-ordination number checking # Co-ordination numbers are not valid organisation numbers '870574-1315': error_invalid, '870573-1311': error_invalid, # Volvo Personvagnar, bad format '556074+3089': error_invalid, # Invalid checksum '2120000441': error_invalid, # Valid checksum but invalid organisation type '1120000441': error_invalid, } self.assertFieldOutput(SEOrganisationNumberField, valid, invalid) def test_SEPersonalIdentityNumberField(self): error_invalid = [u'Enter a valid Swedish personal identity number.'] error_coord = [u'Co-ordination numbers are not allowed.'] valid = { '870512-1989': '198705121989', '870512-2128': '198705122128', '19870512-1989': '198705121989', '198705121989': '198705121989', '081015-6315': '190810156315', '0810156315': '190810156315', # This is a "special-case" in the checksum calculation, # where the sum is divisible by 10 (the checksum digit == 0) '8705141060': '198705141060', # + means that the person is older than 100 years '081015+6315': '180810156315', # Co-ordination number checking '870574-1315': '198705741315', '870574+1315': '188705741315', '198705741315': '198705741315', } invalid = { '081015 6315': error_invalid, '950d314496': error_invalid, 'invalid!!!': error_invalid, # Invalid dates # February 31st does not exist '950231-4496': error_invalid, # Month 14 does not exist '6914104499': error_invalid, # There are no Swedish personal id numbers where year < 1800 '17430309-7135': error_invalid, # Invalid checksum '870514-1111': error_invalid, # Co-ordination number with bad checksum '870573-1311': error_invalid, } self.assertFieldOutput(SEPersonalIdentityNumberField, valid, invalid) valid = {} invalid = { # Check valid co-ordination numbers that should not be accepted # because of coordination_number=False '870574-1315': error_coord, '870574+1315': error_coord, '8705741315': error_coord, # Invalid co-ordination numbers should be treated as invalid, and not # as co-ordination numbers '870573-1311': error_invalid, } kwargs = {'coordination_number': False,} self.assertFieldOutput(SEPersonalIdentityNumberField, valid, invalid, field_kwargs=kwargs) def test_SEPostalCodeField(self): error_format = [u'Enter a Swedish postal code in the format XXXXX.'] valid = { '589 37': '58937', '58937': '58937', } invalid = { 'abcasfassadf': error_format, # Only one space is allowed for separation '589 37': error_format, # The postal code must not start with 0 '01234': error_format, } self.assertFieldOutput(SEPostalCodeField, valid, invalid)
6,442
Python
.py
153
32.385621
81
0.614343
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,939
au.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/au.py
from django.contrib.localflavor.au.forms import (AUPostCodeField, AUPhoneNumberField, AUStateSelect) from utils import LocalFlavorTestCase class AULocalFlavorTests(LocalFlavorTestCase): def test_AUStateSelect(self): f = AUStateSelect() out = u'''<select name="state"> <option value="ACT">Australian Capital Territory</option> <option value="NSW" selected="selected">New South Wales</option> <option value="NT">Northern Territory</option> <option value="QLD">Queensland</option> <option value="SA">South Australia</option> <option value="TAS">Tasmania</option> <option value="VIC">Victoria</option> <option value="WA">Western Australia</option> </select>''' self.assertEqual(f.render('state', 'NSW'), out) def test_AUPostCodeField(self): error_format = [u'Enter a 4 digit post code.'] valid = { '1234': '1234', '2000': '2000', } invalid = { 'abcd': error_format, '20001': error_format, } self.assertFieldOutput(AUPostCodeField, valid, invalid) def test_AUPhoneNumberField(self): error_format = [u'Phone numbers must contain 10 digits.'] valid = { '1234567890': '1234567890', '0213456789': '0213456789', '02 13 45 67 89': '0213456789', '(02) 1345 6789': '0213456789', '(02) 1345-6789': '0213456789', '(02)1345-6789': '0213456789', '0408 123 456': '0408123456', } invalid = { '123': error_format, '1800DJANGO': error_format, } self.assertFieldOutput(AUPhoneNumberField, valid, invalid)
1,685
Python
.py
44
30.431818
66
0.623242
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,940
ch.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/ch.py
from django.contrib.localflavor.ch.forms import (CHZipCodeField, CHPhoneNumberField, CHIdentityCardNumberField, CHStateSelect) from utils import LocalFlavorTestCase class CHLocalFlavorTests(LocalFlavorTestCase): def test_CHStateSelect(self): f = CHStateSelect() out = u'''<select name="state"> <option value="AG" selected="selected">Aargau</option> <option value="AI">Appenzell Innerrhoden</option> <option value="AR">Appenzell Ausserrhoden</option> <option value="BS">Basel-Stadt</option> <option value="BL">Basel-Land</option> <option value="BE">Berne</option> <option value="FR">Fribourg</option> <option value="GE">Geneva</option> <option value="GL">Glarus</option> <option value="GR">Graubuenden</option> <option value="JU">Jura</option> <option value="LU">Lucerne</option> <option value="NE">Neuchatel</option> <option value="NW">Nidwalden</option> <option value="OW">Obwalden</option> <option value="SH">Schaffhausen</option> <option value="SZ">Schwyz</option> <option value="SO">Solothurn</option> <option value="SG">St. Gallen</option> <option value="TG">Thurgau</option> <option value="TI">Ticino</option> <option value="UR">Uri</option> <option value="VS">Valais</option> <option value="VD">Vaud</option> <option value="ZG">Zug</option> <option value="ZH">Zurich</option> </select>''' self.assertEqual(f.render('state', 'AG'), out) def test_CHZipCodeField(self): error_format = [u'Enter a zip code in the format XXXX.'] valid = { '1234': '1234', '0000': '0000', } invalid = { '800x': error_format, '80 00': error_format, } self.assertFieldOutput(CHZipCodeField, valid, invalid) def test_CHPhoneNumberField(self): error_format = [u'Phone numbers must be in 0XX XXX XX XX format.'] valid = { '012 345 67 89': '012 345 67 89', '0123456789': '012 345 67 89', } invalid = { '01234567890': error_format, '1234567890': error_format, } self.assertFieldOutput(CHPhoneNumberField, valid, invalid) def test_CHIdentityCardNumberField(self): error_format = [u'Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.'] valid = { 'C1234567<0': 'C1234567<0', '2123456700': '2123456700', } invalid = { 'C1234567<1': error_format, '2123456701': error_format, } self.assertFieldOutput(CHIdentityCardNumberField, valid, invalid)
2,604
Python
.py
68
32.132353
116
0.661104
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,941
be.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/be.py
from django.contrib.localflavor.be.forms import (BEPostalCodeField, BEPhoneNumberField, BERegionSelect, BEProvinceSelect) from utils import LocalFlavorTestCase class BELocalFlavorTests(LocalFlavorTestCase): def test_BEPostalCodeField(self): error_format = [u'Enter a valid postal code in the range and format 1XXX - 9XXX.'] valid = { u'1451': '1451', u'2540': '2540', } invalid = { '0287': error_format, '14309': error_format, '873': error_format, '35 74': error_format, '859A': error_format, } self.assertFieldOutput(BEPostalCodeField, valid, invalid) def test_BEPhoneNumberField(self): error_format = [ ('Enter a valid phone number in one of the formats 0x xxx xx xx, ' '0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, ' '04xx/xx.xx.xx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx, ' '0xxxxxxxx or 04xxxxxxxx.') ] valid = { u'01 234 56 78': '01 234 56 78', u'01/234.56.78': '01/234.56.78', u'01.234.56.78': '01.234.56.78', u'012 34 56 78': '012 34 56 78', u'012/34.56.78': '012/34.56.78', u'012.34.56.78': '012.34.56.78', u'0412 34 56 78': '0412 34 56 78', u'0412/34.56.78': '0412/34.56.78', u'0412.34.56.78': '0412.34.56.78', u'012345678': '012345678', u'0412345678': '0412345678', } invalid = { '01234567': error_format, '12/345.67.89': error_format, '012/345.678.90': error_format, '012/34.56.789': error_format, '0123/45.67.89': error_format, '012/345 678 90': error_format, '012/34 56 789': error_format, '012.34 56 789': error_format, } self.assertFieldOutput(BEPhoneNumberField, valid, invalid) def test_BERegionSelect(self): f = BERegionSelect() out = u'''<select name="regions"> <option value="BRU">Brussels Capital Region</option> <option value="VLG" selected="selected">Flemish Region</option> <option value="WAL">Wallonia</option> </select>''' self.assertEqual(f.render('regions', 'VLG'), out) def test_BEProvinceSelect(self): f = BEProvinceSelect() out = u'''<select name="provinces"> <option value="VAN">Antwerp</option> <option value="BRU">Brussels</option> <option value="VOV">East Flanders</option> <option value="VBR">Flemish Brabant</option> <option value="WHT">Hainaut</option> <option value="WLG" selected="selected">Liege</option> <option value="VLI">Limburg</option> <option value="WLX">Luxembourg</option> <option value="WNA">Namur</option> <option value="WBR">Walloon Brabant</option> <option value="VWV">West Flanders</option> </select>''' self.assertEqual(f.render('provinces', 'WLG'), out)
2,977
Python
.py
73
32.246575
90
0.594548
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,942
it.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/it.py
from django.contrib.localflavor.it.forms import (ITZipCodeField, ITRegionSelect, ITSocialSecurityNumberField, ITVatNumberField) from utils import LocalFlavorTestCase class ITLocalFlavorTests(LocalFlavorTestCase): def test_ITRegionSelect(self): f = ITRegionSelect() out = u'''<select name="regions"> <option value="ABR">Abruzzo</option> <option value="BAS">Basilicata</option> <option value="CAL">Calabria</option> <option value="CAM">Campania</option> <option value="EMR">Emilia-Romagna</option> <option value="FVG">Friuli-Venezia Giulia</option> <option value="LAZ">Lazio</option> <option value="LIG">Liguria</option> <option value="LOM">Lombardia</option> <option value="MAR">Marche</option> <option value="MOL">Molise</option> <option value="PMN" selected="selected">Piemonte</option> <option value="PUG">Puglia</option> <option value="SAR">Sardegna</option> <option value="SIC">Sicilia</option> <option value="TOS">Toscana</option> <option value="TAA">Trentino-Alto Adige</option> <option value="UMB">Umbria</option> <option value="VAO">Valle d\u2019Aosta</option> <option value="VEN">Veneto</option> </select>''' self.assertEqual(f.render('regions', 'PMN'), out) def test_ITZipCodeField(self): error_invalid = [u'Enter a valid zip code.'] valid = { '00100': '00100', } invalid = { ' 00100': error_invalid, } self.assertFieldOutput(ITZipCodeField, valid, invalid) def test_ITSocialSecurityNumberField(self): error_invalid = [u'Enter a valid Social Security number.'] valid = { 'LVSGDU99T71H501L': 'LVSGDU99T71H501L', 'LBRRME11A01L736W': 'LBRRME11A01L736W', 'lbrrme11a01l736w': 'LBRRME11A01L736W', 'LBR RME 11A01 L736W': 'LBRRME11A01L736W', } invalid = { 'LBRRME11A01L736A': error_invalid, '%BRRME11A01L736W': error_invalid, } self.assertFieldOutput(ITSocialSecurityNumberField, valid, invalid) def test_ITVatNumberField(self): error_invalid = [u'Enter a valid VAT number.'] valid = { '07973780013': '07973780013', '7973780013': '07973780013', 7973780013: '07973780013', } invalid = { '07973780014': error_invalid, 'A7973780013': error_invalid, } self.assertFieldOutput(ITVatNumberField, valid, invalid)
2,466
Python
.py
63
32.444444
80
0.667923
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,943
uy.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/uy.py
from django.contrib.localflavor.uy.forms import UYDepartamentSelect, UYCIField from django.contrib.localflavor.uy.util import get_validation_digit from utils import LocalFlavorTestCase class UYLocalFlavorTests(LocalFlavorTestCase): def test_UYDepartmentSelect(self): f = UYDepartamentSelect() out = u'''<select name="departamentos"> <option value="G">Artigas</option> <option value="A">Canelones</option> <option value="E">Cerro Largo</option> <option value="L">Colonia</option> <option value="Q">Durazno</option> <option value="N">Flores</option> <option value="O">Florida</option> <option value="P">Lavalleja</option> <option value="B">Maldonado</option> <option value="S" selected="selected">Montevideo</option> <option value="I">Paysand\xfa</option> <option value="J">R\xedo Negro</option> <option value="F">Rivera</option> <option value="C">Rocha</option> <option value="H">Salto</option> <option value="M">San Jos\xe9</option> <option value="K">Soriano</option> <option value="R">Tacuaremb\xf3</option> <option value="D">Treinta y Tres</option> </select>''' self.assertEqual(f.render('departamentos', 'S'), out) def test_UYCIField(self): error_format = [u'Enter a valid CI number in X.XXX.XXX-X,XXXXXXX-X or XXXXXXXX format.'] error_invalid = [u'Enter a valid CI number.'] valid = { '4098053': '4098053', '409805-3': '409805-3', '409.805-3': '409.805-3', '10054112': '10054112', '1005411-2': '1005411-2', '1.005.411-2': '1.005.411-2', } invalid = { 'foo': [u'Enter a valid CI number in X.XXX.XXX-X,XXXXXXX-X or XXXXXXXX format.'], '409805-2': [u'Enter a valid CI number.'], '1.005.411-5': [u'Enter a valid CI number.'], } self.assertFieldOutput(UYCIField, valid, invalid) self.assertEqual(get_validation_digit(409805), 3) self.assertEqual(get_validation_digit(1005411), 2)
2,000
Python
.py
47
36.851064
96
0.665123
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,944
ca.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/ca.py
import warnings from django.contrib.localflavor.ca.forms import (CAPostalCodeField, CAPhoneNumberField, CAProvinceField, CAProvinceSelect, CASocialInsuranceNumberField) from utils import LocalFlavorTestCase class CALocalFlavorTests(LocalFlavorTestCase): def setUp(self): self.save_warnings_state() warnings.filterwarnings( "ignore", category=RuntimeWarning, module='django.contrib.localflavor.ca.ca_provinces' ) def tearDown(self): self.restore_warnings_state() def test_CAProvinceSelect(self): f = CAProvinceSelect() out = u'''<select name="province"> <option value="AB" selected="selected">Alberta</option> <option value="BC">British Columbia</option> <option value="MB">Manitoba</option> <option value="NB">New Brunswick</option> <option value="NL">Newfoundland and Labrador</option> <option value="NT">Northwest Territories</option> <option value="NS">Nova Scotia</option> <option value="NU">Nunavut</option> <option value="ON">Ontario</option> <option value="PE">Prince Edward Island</option> <option value="QC">Quebec</option> <option value="SK">Saskatchewan</option> <option value="YT">Yukon</option> </select>''' self.assertEqual(f.render('province', 'AB'), out) def test_CAPostalCodeField(self): error_format = [u'Enter a postal code in the format XXX XXX.'] valid = { 'T2S 2H7': 'T2S 2H7', 'T2S 2W7': 'T2S 2W7', 'T2S 2Z7': 'T2S 2Z7', 'T2Z 2H7': 'T2Z 2H7', } invalid = { 'T2S2H7' : error_format, 'T2S 2H' : error_format, '2T6 H8I': error_format, 'T2S2H' : error_format, 90210 : error_format, 'W2S 2H3': error_format, 'Z2S 2H3': error_format, 'F2S 2H3': error_format, 'A2S 2D3': error_format, 'A2I 2R3': error_format, 'A2Q 2R3': error_format, 'U2B 2R3': error_format, 'O2B 2R3': error_format, } self.assertFieldOutput(CAPostalCodeField, valid, invalid) def test_CAPhoneNumberField(self): error_format = [u'Phone numbers must be in XXX-XXX-XXXX format.'] valid = { '403-555-1212': '403-555-1212', '4035551212': '403-555-1212', '403 555-1212': '403-555-1212', '(403) 555-1212': '403-555-1212', '403 555 1212': '403-555-1212', '403.555.1212': '403-555-1212', '403.555-1212': '403-555-1212', ' (403) 555.1212 ': '403-555-1212', } invalid = { '555-1212': error_format, '403-55-1212': error_format, } self.assertFieldOutput(CAPhoneNumberField, valid, invalid) def test_CAProvinceField(self): error_format = [u'Enter a Canadian province or territory.'] valid = { 'ab': 'AB', 'BC': 'BC', 'nova scotia': 'NS', ' manitoba ': 'MB', } invalid = { 'T2S 2H7': error_format, } self.assertFieldOutput(CAProvinceField, valid, invalid) def test_CASocialInsuranceField(self): error_format = [u'Enter a valid Canadian Social Insurance number in XXX-XXX-XXX format.'] valid = { '046-454-286': '046-454-286', } invalid = { '046-454-287': error_format, '046 454 286': error_format, '046-44-286': error_format, } self.assertFieldOutput(CASocialInsuranceNumberField, valid, invalid)
3,636
Python
.py
97
28.556701
97
0.589286
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,945
cl.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/cl.py
from django.contrib.localflavor.cl.forms import CLRutField, CLRegionSelect from django.core.exceptions import ValidationError from utils import LocalFlavorTestCase class CLLocalFlavorTests(LocalFlavorTestCase): def test_CLRegionSelect(self): f = CLRegionSelect() out = u'''<select name="foo"> <option value="RM">Regi\xf3n Metropolitana de Santiago</option> <option value="I">Regi\xf3n de Tarapac\xe1</option> <option value="II">Regi\xf3n de Antofagasta</option> <option value="III">Regi\xf3n de Atacama</option> <option value="IV">Regi\xf3n de Coquimbo</option> <option value="V">Regi\xf3n de Valpara\xedso</option> <option value="VI">Regi\xf3n del Libertador Bernardo O&#39;Higgins</option> <option value="VII">Regi\xf3n del Maule</option> <option value="VIII">Regi\xf3n del B\xedo B\xedo</option> <option value="IX">Regi\xf3n de la Araucan\xeda</option> <option value="X">Regi\xf3n de los Lagos</option> <option value="XI">Regi\xf3n de Ays\xe9n del General Carlos Ib\xe1\xf1ez del Campo</option> <option value="XII">Regi\xf3n de Magallanes y la Ant\xe1rtica Chilena</option> <option value="XIV">Regi\xf3n de Los R\xedos</option> <option value="XV">Regi\xf3n de Arica-Parinacota</option> </select>''' self.assertEqual(f.render('foo', 'bar'), out) def test_CLRutField(self): error_invalid = [u'The Chilean RUT is not valid.'] error_format = [u'Enter a valid Chilean RUT. The format is XX.XXX.XXX-X.'] valid = { '11-6': '11-6', '116': '11-6', '767484100': '76.748.410-0', '78.412.790-7': '78.412.790-7', '8.334.6043': '8.334.604-3', '76793310-K': '76.793.310-K', '76793310-k': '76.793.310-K', } invalid = { '11.111.111-0': error_invalid, '111': error_invalid, } self.assertFieldOutput(CLRutField, valid, invalid) # deal with special "Strict Mode". invalid = { '11-6': error_format, '767484100': error_format, '8.334.6043': error_format, '76793310-K': error_format, '11.111.111-0': error_invalid } self.assertFieldOutput(CLRutField, {}, invalid, field_kwargs={"strict": True} )
2,290
Python
.py
52
37.019231
91
0.643081
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,946
il.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/il.py
from django.contrib.localflavor.il.forms import (ILPostalCodeField, ILIDNumberField) from utils import LocalFlavorTestCase class ILLocalFlavorTests(LocalFlavorTestCase): def test_ILPostalCodeField(self): error_format = [u'Enter a postal code in the format XXXXX'] valid = { '69973': '69973', '699 73': '69973', '12345': '12345', } invalid = { '84545x': error_format, '123456': error_format, '1234': error_format, '123 4': error_format, } self.assertFieldOutput(ILPostalCodeField, valid, invalid) def test_ILIDNumberField(self): error_invalid = [u'Enter a valid ID number.'] valid = { '3933742-3': '39337423', '39337423': '39337423', '039337423': '039337423', '03933742-3': '039337423', '0091': '0091', } invalid = { '123456789': error_invalid, '12345678-9': error_invalid, '012346578': error_invalid, '012346578-': error_invalid, '0001': error_invalid, } self.assertFieldOutput(ILIDNumberField, valid, invalid)
1,227
Python
.py
35
25.028571
67
0.564815
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,947
fi.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/fi.py
from django.contrib.localflavor.fi.forms import (FIZipCodeField, FISocialSecurityNumber, FIMunicipalitySelect) from utils import LocalFlavorTestCase class FILocalFlavorTests(LocalFlavorTestCase): def test_FIMunicipalitySelect(self): f = FIMunicipalitySelect() out = u'''<select name="municipalities"> <option value="akaa">Akaa</option> <option value="alajarvi">Alaj\xe4rvi</option> <option value="alavieska">Alavieska</option> <option value="alavus">Alavus</option> <option value="artjarvi">Artj\xe4rvi</option> <option value="asikkala">Asikkala</option> <option value="askola">Askola</option> <option value="aura">Aura</option> <option value="brando">Br\xe4nd\xf6</option> <option value="eckero">Ecker\xf6</option> <option value="enonkoski">Enonkoski</option> <option value="enontekio">Enonteki\xf6</option> <option value="espoo">Espoo</option> <option value="eura">Eura</option> <option value="eurajoki">Eurajoki</option> <option value="evijarvi">Evij\xe4rvi</option> <option value="finstrom">Finstr\xf6m</option> <option value="forssa">Forssa</option> <option value="foglo">F\xf6gl\xf6</option> <option value="geta">Geta</option> <option value="haapajarvi">Haapaj\xe4rvi</option> <option value="haapavesi">Haapavesi</option> <option value="hailuoto">Hailuoto</option> <option value="halsua">Halsua</option> <option value="hamina">Hamina</option> <option value="hammarland">Hammarland</option> <option value="hankasalmi">Hankasalmi</option> <option value="hanko">Hanko</option> <option value="harjavalta">Harjavalta</option> <option value="hartola">Hartola</option> <option value="hattula">Hattula</option> <option value="haukipudas">Haukipudas</option> <option value="hausjarvi">Hausj\xe4rvi</option> <option value="heinola">Heinola</option> <option value="heinavesi">Hein\xe4vesi</option> <option value="helsinki">Helsinki</option> <option value="hirvensalmi">Hirvensalmi</option> <option value="hollola">Hollola</option> <option value="honkajoki">Honkajoki</option> <option value="huittinen">Huittinen</option> <option value="humppila">Humppila</option> <option value="hyrynsalmi">Hyrynsalmi</option> <option value="hyvinkaa">Hyvink\xe4\xe4</option> <option value="hameenkoski">H\xe4meenkoski</option> <option value="hameenkyro">H\xe4meenkyr\xf6</option> <option value="hameenlinna">H\xe4meenlinna</option> <option value="ii">Ii</option> <option value="iisalmi">Iisalmi</option> <option value="iitti">Iitti</option> <option value="ikaalinen">Ikaalinen</option> <option value="ilmajoki">Ilmajoki</option> <option value="ilomantsi">Ilomantsi</option> <option value="imatra">Imatra</option> <option value="inari">Inari</option> <option value="inkoo">Inkoo</option> <option value="isojoki">Isojoki</option> <option value="isokyro">Isokyr\xf6</option> <option value="jalasjarvi">Jalasj\xe4rvi</option> <option value="janakkala">Janakkala</option> <option value="joensuu">Joensuu</option> <option value="jokioinen">Jokioinen</option> <option value="jomala">Jomala</option> <option value="joroinen">Joroinen</option> <option value="joutsa">Joutsa</option> <option value="juankoski">Juankoski</option> <option value="juuka">Juuka</option> <option value="juupajoki">Juupajoki</option> <option value="juva">Juva</option> <option value="jyvaskyla">Jyv\xe4skyl\xe4</option> <option value="jamijarvi">J\xe4mij\xe4rvi</option> <option value="jamsa">J\xe4ms\xe4</option> <option value="jarvenpaa">J\xe4rvenp\xe4\xe4</option> <option value="kaarina">Kaarina</option> <option value="kaavi">Kaavi</option> <option value="kajaani">Kajaani</option> <option value="kalajoki">Kalajoki</option> <option value="kangasala">Kangasala</option> <option value="kangasniemi">Kangasniemi</option> <option value="kankaanpaa">Kankaanp\xe4\xe4</option> <option value="kannonkoski">Kannonkoski</option> <option value="kannus">Kannus</option> <option value="karijoki">Karijoki</option> <option value="karjalohja">Karjalohja</option> <option value="karkkila">Karkkila</option> <option value="karstula">Karstula</option> <option value="karttula">Karttula</option> <option value="karvia">Karvia</option> <option value="kaskinen">Kaskinen</option> <option value="kauhajoki">Kauhajoki</option> <option value="kauhava">Kauhava</option> <option value="kauniainen">Kauniainen</option> <option value="kaustinen">Kaustinen</option> <option value="keitele">Keitele</option> <option value="kemi">Kemi</option> <option value="kemijarvi">Kemij\xe4rvi</option> <option value="keminmaa">Keminmaa</option> <option value="kemionsaari">Kemi\xf6nsaari</option> <option value="kempele">Kempele</option> <option value="kerava">Kerava</option> <option value="kerimaki">Kerim\xe4ki</option> <option value="kesalahti">Kes\xe4lahti</option> <option value="keuruu">Keuruu</option> <option value="kihnio">Kihni\xf6</option> <option value="kiikoinen">Kiikoinen</option> <option value="kiiminki">Kiiminki</option> <option value="kinnula">Kinnula</option> <option value="kirkkonummi">Kirkkonummi</option> <option value="kitee">Kitee</option> <option value="kittila">Kittil\xe4</option> <option value="kiuruvesi">Kiuruvesi</option> <option value="kivijarvi">Kivij\xe4rvi</option> <option value="kokemaki">Kokem\xe4ki</option> <option value="kokkola">Kokkola</option> <option value="kolari">Kolari</option> <option value="konnevesi">Konnevesi</option> <option value="kontiolahti">Kontiolahti</option> <option value="korsnas">Korsn\xe4s</option> <option value="koskitl">Koski Tl</option> <option value="kotka">Kotka</option> <option value="kouvola">Kouvola</option> <option value="kristiinankaupunki">Kristiinankaupunki</option> <option value="kruunupyy">Kruunupyy</option> <option value="kuhmalahti">Kuhmalahti</option> <option value="kuhmo">Kuhmo</option> <option value="kuhmoinen">Kuhmoinen</option> <option value="kumlinge">Kumlinge</option> <option value="kuopio">Kuopio</option> <option value="kuortane">Kuortane</option> <option value="kurikka">Kurikka</option> <option value="kustavi">Kustavi</option> <option value="kuusamo">Kuusamo</option> <option value="kylmakoski">Kylm\xe4koski</option> <option value="kyyjarvi">Kyyj\xe4rvi</option> <option value="karkola">K\xe4rk\xf6l\xe4</option> <option value="karsamaki">K\xe4rs\xe4m\xe4ki</option> <option value="kokar">K\xf6kar</option> <option value="koylio">K\xf6yli\xf6</option> <option value="lahti">Lahti</option> <option value="laihia">Laihia</option> <option value="laitila">Laitila</option> <option value="lapinjarvi">Lapinj\xe4rvi</option> <option value="lapinlahti">Lapinlahti</option> <option value="lappajarvi">Lappaj\xe4rvi</option> <option value="lappeenranta">Lappeenranta</option> <option value="lapua">Lapua</option> <option value="laukaa">Laukaa</option> <option value="lavia">Lavia</option> <option value="lemi">Lemi</option> <option value="lemland">Lemland</option> <option value="lempaala">Lemp\xe4\xe4l\xe4</option> <option value="leppavirta">Lepp\xe4virta</option> <option value="lestijarvi">Lestij\xe4rvi</option> <option value="lieksa">Lieksa</option> <option value="lieto">Lieto</option> <option value="liminka">Liminka</option> <option value="liperi">Liperi</option> <option value="lohja">Lohja</option> <option value="loimaa">Loimaa</option> <option value="loppi">Loppi</option> <option value="loviisa">Loviisa</option> <option value="luhanka">Luhanka</option> <option value="lumijoki">Lumijoki</option> <option value="lumparland">Lumparland</option> <option value="luoto">Luoto</option> <option value="luumaki">Luum\xe4ki</option> <option value="luvia">Luvia</option> <option value="lansi-turunmaa">L\xe4nsi-Turunmaa</option> <option value="maalahti">Maalahti</option> <option value="maaninka">Maaninka</option> <option value="maarianhamina">Maarianhamina</option> <option value="marttila">Marttila</option> <option value="masku">Masku</option> <option value="merijarvi">Merij\xe4rvi</option> <option value="merikarvia">Merikarvia</option> <option value="miehikkala">Miehikk\xe4l\xe4</option> <option value="mikkeli">Mikkeli</option> <option value="muhos">Muhos</option> <option value="multia">Multia</option> <option value="muonio">Muonio</option> <option value="mustasaari">Mustasaari</option> <option value="muurame">Muurame</option> <option value="mynamaki">Myn\xe4m\xe4ki</option> <option value="myrskyla">Myrskyl\xe4</option> <option value="mantsala">M\xe4nts\xe4l\xe4</option> <option value="mantta-vilppula">M\xe4ntt\xe4-Vilppula</option> <option value="mantyharju">M\xe4ntyharju</option> <option value="naantali">Naantali</option> <option value="nakkila">Nakkila</option> <option value="nastola">Nastola</option> <option value="nilsia">Nilsi\xe4</option> <option value="nivala">Nivala</option> <option value="nokia">Nokia</option> <option value="nousiainen">Nousiainen</option> <option value="nummi-pusula">Nummi-Pusula</option> <option value="nurmes">Nurmes</option> <option value="nurmijarvi">Nurmij\xe4rvi</option> <option value="narpio">N\xe4rpi\xf6</option> <option value="oravainen">Oravainen</option> <option value="orimattila">Orimattila</option> <option value="oripaa">Orip\xe4\xe4</option> <option value="orivesi">Orivesi</option> <option value="oulainen">Oulainen</option> <option value="oulu">Oulu</option> <option value="oulunsalo">Oulunsalo</option> <option value="outokumpu">Outokumpu</option> <option value="padasjoki">Padasjoki</option> <option value="paimio">Paimio</option> <option value="paltamo">Paltamo</option> <option value="parikkala">Parikkala</option> <option value="parkano">Parkano</option> <option value="pedersore">Peders\xf6re</option> <option value="pelkosenniemi">Pelkosenniemi</option> <option value="pello">Pello</option> <option value="perho">Perho</option> <option value="pertunmaa">Pertunmaa</option> <option value="petajavesi">Pet\xe4j\xe4vesi</option> <option value="pieksamaki">Pieks\xe4m\xe4ki</option> <option value="pielavesi">Pielavesi</option> <option value="pietarsaari">Pietarsaari</option> <option value="pihtipudas">Pihtipudas</option> <option value="pirkkala">Pirkkala</option> <option value="polvijarvi">Polvij\xe4rvi</option> <option value="pomarkku">Pomarkku</option> <option value="pori">Pori</option> <option value="pornainen">Pornainen</option> <option value="porvoo">Porvoo</option> <option value="posio">Posio</option> <option value="pudasjarvi">Pudasj\xe4rvi</option> <option value="pukkila">Pukkila</option> <option value="punkaharju">Punkaharju</option> <option value="punkalaidun">Punkalaidun</option> <option value="puolanka">Puolanka</option> <option value="puumala">Puumala</option> <option value="pyhtaa">Pyht\xe4\xe4</option> <option value="pyhajoki">Pyh\xe4joki</option> <option value="pyhajarvi">Pyh\xe4j\xe4rvi</option> <option value="pyhanta">Pyh\xe4nt\xe4</option> <option value="pyharanta">Pyh\xe4ranta</option> <option value="palkane">P\xe4lk\xe4ne</option> <option value="poytya">P\xf6yty\xe4</option> <option value="raahe">Raahe</option> <option value="raasepori">Raasepori</option> <option value="raisio">Raisio</option> <option value="rantasalmi">Rantasalmi</option> <option value="ranua">Ranua</option> <option value="rauma">Rauma</option> <option value="rautalampi">Rautalampi</option> <option value="rautavaara">Rautavaara</option> <option value="rautjarvi">Rautj\xe4rvi</option> <option value="reisjarvi">Reisj\xe4rvi</option> <option value="riihimaki">Riihim\xe4ki</option> <option value="ristiina">Ristiina</option> <option value="ristijarvi">Ristij\xe4rvi</option> <option value="rovaniemi">Rovaniemi</option> <option value="ruokolahti">Ruokolahti</option> <option value="ruovesi">Ruovesi</option> <option value="rusko">Rusko</option> <option value="raakkyla">R\xe4\xe4kkyl\xe4</option> <option value="saarijarvi">Saarij\xe4rvi</option> <option value="salla">Salla</option> <option value="salo">Salo</option> <option value="saltvik">Saltvik</option> <option value="sastamala">Sastamala</option> <option value="sauvo">Sauvo</option> <option value="savitaipale">Savitaipale</option> <option value="savonlinna">Savonlinna</option> <option value="savukoski">Savukoski</option> <option value="seinajoki">Sein\xe4joki</option> <option value="sievi">Sievi</option> <option value="siikainen">Siikainen</option> <option value="siikajoki">Siikajoki</option> <option value="siikalatva">Siikalatva</option> <option value="siilinjarvi">Siilinj\xe4rvi</option> <option value="simo">Simo</option> <option value="sipoo">Sipoo</option> <option value="siuntio">Siuntio</option> <option value="sodankyla">Sodankyl\xe4</option> <option value="soini">Soini</option> <option value="somero">Somero</option> <option value="sonkajarvi">Sonkaj\xe4rvi</option> <option value="sotkamo">Sotkamo</option> <option value="sottunga">Sottunga</option> <option value="sulkava">Sulkava</option> <option value="sund">Sund</option> <option value="suomenniemi">Suomenniemi</option> <option value="suomussalmi">Suomussalmi</option> <option value="suonenjoki">Suonenjoki</option> <option value="sysma">Sysm\xe4</option> <option value="sakyla">S\xe4kyl\xe4</option> <option value="taipalsaari">Taipalsaari</option> <option value="taivalkoski">Taivalkoski</option> <option value="taivassalo">Taivassalo</option> <option value="tammela">Tammela</option> <option value="tampere">Tampere</option> <option value="tarvasjoki">Tarvasjoki</option> <option value="tervo">Tervo</option> <option value="tervola">Tervola</option> <option value="teuva">Teuva</option> <option value="tohmajarvi">Tohmaj\xe4rvi</option> <option value="toholampi">Toholampi</option> <option value="toivakka">Toivakka</option> <option value="tornio">Tornio</option> <option value="turku" selected="selected">Turku</option> <option value="tuusniemi">Tuusniemi</option> <option value="tuusula">Tuusula</option> <option value="tyrnava">Tyrn\xe4v\xe4</option> <option value="toysa">T\xf6ys\xe4</option> <option value="ulvila">Ulvila</option> <option value="urjala">Urjala</option> <option value="utajarvi">Utaj\xe4rvi</option> <option value="utsjoki">Utsjoki</option> <option value="uurainen">Uurainen</option> <option value="uusikaarlepyy">Uusikaarlepyy</option> <option value="uusikaupunki">Uusikaupunki</option> <option value="vaala">Vaala</option> <option value="vaasa">Vaasa</option> <option value="valkeakoski">Valkeakoski</option> <option value="valtimo">Valtimo</option> <option value="vantaa">Vantaa</option> <option value="varkaus">Varkaus</option> <option value="varpaisjarvi">Varpaisj\xe4rvi</option> <option value="vehmaa">Vehmaa</option> <option value="vesanto">Vesanto</option> <option value="vesilahti">Vesilahti</option> <option value="veteli">Veteli</option> <option value="vierema">Vierem\xe4</option> <option value="vihanti">Vihanti</option> <option value="vihti">Vihti</option> <option value="viitasaari">Viitasaari</option> <option value="vimpeli">Vimpeli</option> <option value="virolahti">Virolahti</option> <option value="virrat">Virrat</option> <option value="vardo">V\xe5rd\xf6</option> <option value="vahakyro">V\xe4h\xe4kyr\xf6</option> <option value="voyri-maksamaa">V\xf6yri-Maksamaa</option> <option value="yli-ii">Yli-Ii</option> <option value="ylitornio">Ylitornio</option> <option value="ylivieska">Ylivieska</option> <option value="ylojarvi">Yl\xf6j\xe4rvi</option> <option value="ypaja">Yp\xe4j\xe4</option> <option value="ahtari">\xc4ht\xe4ri</option> <option value="aanekoski">\xc4\xe4nekoski</option> </select>''' self.assertEqual(f.render('municipalities', 'turku'), out) def test_FIZipCodeField(self): error_format = [u'Enter a zip code in the format XXXXX.'] valid = { '20540': '20540', '20101': '20101', } invalid = { '20s40': error_format, '205401': error_format } self.assertFieldOutput(FIZipCodeField, valid, invalid) def test_FISocialSecurityNumber(self): error_invalid = [u'Enter a valid Finnish social security number.'] valid = { '010101-0101': '010101-0101', '010101+0101': '010101+0101', '010101A0101': '010101A0101', } invalid = { '101010-0102': error_invalid, '10a010-0101': error_invalid, '101010-0\xe401': error_invalid, '101010b0101': error_invalid, } self.assertFieldOutput(FISocialSecurityNumber, valid, invalid)
16,281
Python
.py
376
41.571809
74
0.766652
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,948
pl.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/pl.py
from django.contrib.localflavor.pl.forms import (PLProvinceSelect, PLCountySelect, PLPostalCodeField, PLNIPField, PLPESELField, PLREGONField) from utils import LocalFlavorTestCase class PLLocalFlavorTests(LocalFlavorTestCase): def test_PLProvinceSelect(self): f = PLProvinceSelect() out = u'''<select name="voivodeships"> <option value="lower_silesia">Lower Silesia</option> <option value="kuyavia-pomerania">Kuyavia-Pomerania</option> <option value="lublin">Lublin</option> <option value="lubusz">Lubusz</option> <option value="lodz">Lodz</option> <option value="lesser_poland">Lesser Poland</option> <option value="masovia">Masovia</option> <option value="opole">Opole</option> <option value="subcarpatia">Subcarpatia</option> <option value="podlasie">Podlasie</option> <option value="pomerania" selected="selected">Pomerania</option> <option value="silesia">Silesia</option> <option value="swietokrzyskie">Swietokrzyskie</option> <option value="warmia-masuria">Warmia-Masuria</option> <option value="greater_poland">Greater Poland</option> <option value="west_pomerania">West Pomerania</option> </select>''' self.assertEqual(f.render('voivodeships', 'pomerania'), out) def test_PLCountrySelect(self): f = PLCountySelect() out = u'''<select name="administrativeunit"> <option value="wroclaw">Wroc\u0142aw</option> <option value="jeleniagora">Jelenia G\xf3ra</option> <option value="legnica">Legnica</option> <option value="boleslawiecki">boles\u0142awiecki</option> <option value="dzierzoniowski">dzier\u017coniowski</option> <option value="glogowski">g\u0142ogowski</option> <option value="gorowski">g\xf3rowski</option> <option value="jaworski">jaworski</option> <option value="jeleniogorski">jeleniog\xf3rski</option> <option value="kamiennogorski">kamiennog\xf3rski</option> <option value="klodzki">k\u0142odzki</option> <option value="legnicki">legnicki</option> <option value="lubanski">luba\u0144ski</option> <option value="lubinski">lubi\u0144ski</option> <option value="lwowecki">lw\xf3wecki</option> <option value="milicki">milicki</option> <option value="olesnicki">ole\u015bnicki</option> <option value="olawski">o\u0142awski</option> <option value="polkowicki">polkowicki</option> <option value="strzelinski">strzeli\u0144ski</option> <option value="sredzki">\u015bredzki</option> <option value="swidnicki">\u015bwidnicki</option> <option value="trzebnicki">trzebnicki</option> <option value="walbrzyski">wa\u0142brzyski</option> <option value="wolowski">wo\u0142owski</option> <option value="wroclawski">wroc\u0142awski</option> <option value="zabkowicki">z\u0105bkowicki</option> <option value="zgorzelecki">zgorzelecki</option> <option value="zlotoryjski">z\u0142otoryjski</option> <option value="bydgoszcz">Bydgoszcz</option> <option value="torun">Toru\u0144</option> <option value="wloclawek">W\u0142oc\u0142awek</option> <option value="grudziadz">Grudzi\u0105dz</option> <option value="aleksandrowski">aleksandrowski</option> <option value="brodnicki">brodnicki</option> <option value="bydgoski">bydgoski</option> <option value="chelminski">che\u0142mi\u0144ski</option> <option value="golubsko-dobrzynski">golubsko-dobrzy\u0144ski</option> <option value="grudziadzki">grudzi\u0105dzki</option> <option value="inowroclawski">inowroc\u0142awski</option> <option value="lipnowski">lipnowski</option> <option value="mogilenski">mogile\u0144ski</option> <option value="nakielski">nakielski</option> <option value="radziejowski">radziejowski</option> <option value="rypinski">rypi\u0144ski</option> <option value="sepolenski">s\u0119pole\u0144ski</option> <option value="swiecki">\u015bwiecki</option> <option value="torunski">toru\u0144ski</option> <option value="tucholski">tucholski</option> <option value="wabrzeski">w\u0105brzeski</option> <option value="wloclawski">wroc\u0142awski</option> <option value="zninski">\u017ani\u0144ski</option> <option value="lublin">Lublin</option> <option value="biala-podlaska">Bia\u0142a Podlaska</option> <option value="chelm">Che\u0142m</option> <option value="zamosc">Zamo\u015b\u0107</option> <option value="bialski">bialski</option> <option value="bilgorajski">bi\u0142gorajski</option> <option value="chelmski">che\u0142mski</option> <option value="hrubieszowski">hrubieszowski</option> <option value="janowski">janowski</option> <option value="krasnostawski">krasnostawski</option> <option value="krasnicki">kra\u015bnicki</option> <option value="lubartowski">lubartowski</option> <option value="lubelski">lubelski</option> <option value="leczynski">\u0142\u0119czy\u0144ski</option> <option value="lukowski">\u0142ukowski</option> <option value="opolski">opolski</option> <option value="parczewski">parczewski</option> <option value="pulawski">pu\u0142awski</option> <option value="radzynski">radzy\u0144ski</option> <option value="rycki">rycki</option> <option value="swidnicki">\u015bwidnicki</option> <option value="tomaszowski">tomaszowski</option> <option value="wlodawski">w\u0142odawski</option> <option value="zamojski">zamojski</option> <option value="gorzow-wielkopolski">Gorz\xf3w Wielkopolski</option> <option value="zielona-gora">Zielona G\xf3ra</option> <option value="gorzowski">gorzowski</option> <option value="krosnienski">kro\u015bnie\u0144ski</option> <option value="miedzyrzecki">mi\u0119dzyrzecki</option> <option value="nowosolski">nowosolski</option> <option value="slubicki">s\u0142ubicki</option> <option value="strzelecko-drezdenecki">strzelecko-drezdenecki</option> <option value="sulecinski">sule\u0144ci\u0144ski</option> <option value="swiebodzinski">\u015bwiebodzi\u0144ski</option> <option value="wschowski">wschowski</option> <option value="zielonogorski">zielonog\xf3rski</option> <option value="zaganski">\u017caga\u0144ski</option> <option value="zarski">\u017carski</option> <option value="lodz">\u0141\xf3d\u017a</option> <option value="piotrkow-trybunalski">Piotrk\xf3w Trybunalski</option> <option value="skierniewice">Skierniewice</option> <option value="belchatowski">be\u0142chatowski</option> <option value="brzezinski">brzezi\u0144ski</option> <option value="kutnowski">kutnowski</option> <option value="laski">\u0142aski</option> <option value="leczycki">\u0142\u0119czycki</option> <option value="lowicki">\u0142owicki</option> <option value="lodzki wschodni">\u0142\xf3dzki wschodni</option> <option value="opoczynski">opoczy\u0144ski</option> <option value="pabianicki">pabianicki</option> <option value="pajeczanski">paj\u0119cza\u0144ski</option> <option value="piotrkowski">piotrkowski</option> <option value="poddebicki">podd\u0119bicki</option> <option value="radomszczanski">radomszcza\u0144ski</option> <option value="rawski">rawski</option> <option value="sieradzki">sieradzki</option> <option value="skierniewicki">skierniewicki</option> <option value="tomaszowski">tomaszowski</option> <option value="wielunski">wielu\u0144ski</option> <option value="wieruszowski">wieruszowski</option> <option value="zdunskowolski">zdu\u0144skowolski</option> <option value="zgierski">zgierski</option> <option value="krakow">Krak\xf3w</option> <option value="tarnow">Tarn\xf3w</option> <option value="nowy-sacz">Nowy S\u0105cz</option> <option value="bochenski">boche\u0144ski</option> <option value="brzeski">brzeski</option> <option value="chrzanowski">chrzanowski</option> <option value="dabrowski">d\u0105browski</option> <option value="gorlicki">gorlicki</option> <option value="krakowski">krakowski</option> <option value="limanowski">limanowski</option> <option value="miechowski">miechowski</option> <option value="myslenicki">my\u015blenicki</option> <option value="nowosadecki">nowos\u0105decki</option> <option value="nowotarski">nowotarski</option> <option value="olkuski">olkuski</option> <option value="oswiecimski">o\u015bwi\u0119cimski</option> <option value="proszowicki">proszowicki</option> <option value="suski">suski</option> <option value="tarnowski">tarnowski</option> <option value="tatrzanski">tatrza\u0144ski</option> <option value="wadowicki">wadowicki</option> <option value="wielicki">wielicki</option> <option value="warszawa">Warszawa</option> <option value="ostroleka">Ostro\u0142\u0119ka</option> <option value="plock">P\u0142ock</option> <option value="radom">Radom</option> <option value="siedlce">Siedlce</option> <option value="bialobrzeski">bia\u0142obrzeski</option> <option value="ciechanowski">ciechanowski</option> <option value="garwolinski">garwoli\u0144ski</option> <option value="gostyninski">gostyni\u0144ski</option> <option value="grodziski">grodziski</option> <option value="grojecki">gr\xf3jecki</option> <option value="kozienicki">kozenicki</option> <option value="legionowski">legionowski</option> <option value="lipski">lipski</option> <option value="losicki">\u0142osicki</option> <option value="makowski">makowski</option> <option value="minski">mi\u0144ski</option> <option value="mlawski">m\u0142awski</option> <option value="nowodworski">nowodworski</option> <option value="ostrolecki">ostro\u0142\u0119cki</option> <option value="ostrowski">ostrowski</option> <option value="otwocki">otwocki</option> <option value="piaseczynski">piaseczy\u0144ski</option> <option value="plocki">p\u0142ocki</option> <option value="plonski">p\u0142o\u0144ski</option> <option value="pruszkowski">pruszkowski</option> <option value="przasnyski">przasnyski</option> <option value="przysuski">przysuski</option> <option value="pultuski">pu\u0142tuski</option> <option value="radomski">radomski</option> <option value="siedlecki">siedlecki</option> <option value="sierpecki">sierpecki</option> <option value="sochaczewski">sochaczewski</option> <option value="sokolowski">soko\u0142owski</option> <option value="szydlowiecki">szyd\u0142owiecki</option> <option value="warszawski-zachodni">warszawski zachodni</option> <option value="wegrowski">w\u0119growski</option> <option value="wolominski">wo\u0142omi\u0144ski</option> <option value="wyszkowski">wyszkowski</option> <option value="zwolenski">zwole\u0144ski</option> <option value="zurominski">\u017curomi\u0144ski</option> <option value="zyrardowski">\u017cyrardowski</option> <option value="opole">Opole</option> <option value="brzeski">brzeski</option> <option value="glubczycki">g\u0142ubczyski</option> <option value="kedzierzynsko-kozielski">k\u0119dzierzy\u0144ski-kozielski</option> <option value="kluczborski">kluczborski</option> <option value="krapkowicki">krapkowicki</option> <option value="namyslowski">namys\u0142owski</option> <option value="nyski">nyski</option> <option value="oleski">oleski</option> <option value="opolski">opolski</option> <option value="prudnicki">prudnicki</option> <option value="strzelecki">strzelecki</option> <option value="rzeszow">Rzesz\xf3w</option> <option value="krosno">Krosno</option> <option value="przemysl">Przemy\u015bl</option> <option value="tarnobrzeg">Tarnobrzeg</option> <option value="bieszczadzki">bieszczadzki</option> <option value="brzozowski">brzozowski</option> <option value="debicki">d\u0119bicki</option> <option value="jaroslawski">jaros\u0142awski</option> <option value="jasielski">jasielski</option> <option value="kolbuszowski">kolbuszowski</option> <option value="krosnienski">kro\u015bnie\u0144ski</option> <option value="leski">leski</option> <option value="lezajski">le\u017cajski</option> <option value="lubaczowski">lubaczowski</option> <option value="lancucki">\u0142a\u0144cucki</option> <option value="mielecki">mielecki</option> <option value="nizanski">ni\u017ca\u0144ski</option> <option value="przemyski">przemyski</option> <option value="przeworski">przeworski</option> <option value="ropczycko-sedziszowski">ropczycko-s\u0119dziszowski</option> <option value="rzeszowski">rzeszowski</option> <option value="sanocki">sanocki</option> <option value="stalowowolski">stalowowolski</option> <option value="strzyzowski">strzy\u017cowski</option> <option value="tarnobrzeski">tarnobrzeski</option> <option value="bialystok">Bia\u0142ystok</option> <option value="lomza">\u0141om\u017ca</option> <option value="suwalki">Suwa\u0142ki</option> <option value="augustowski">augustowski</option> <option value="bialostocki">bia\u0142ostocki</option> <option value="bielski">bielski</option> <option value="grajewski">grajewski</option> <option value="hajnowski">hajnowski</option> <option value="kolnenski">kolne\u0144ski</option> <option value="\u0142omzynski">\u0142om\u017cy\u0144ski</option> <option value="moniecki">moniecki</option> <option value="sejnenski">sejne\u0144ski</option> <option value="siemiatycki">siematycki</option> <option value="sokolski">sok\xf3lski</option> <option value="suwalski">suwalski</option> <option value="wysokomazowiecki">wysokomazowiecki</option> <option value="zambrowski">zambrowski</option> <option value="gdansk">Gda\u0144sk</option> <option value="gdynia">Gdynia</option> <option value="slupsk">S\u0142upsk</option> <option value="sopot">Sopot</option> <option value="bytowski">bytowski</option> <option value="chojnicki">chojnicki</option> <option value="czluchowski">cz\u0142uchowski</option> <option value="kartuski">kartuski</option> <option value="koscierski">ko\u015bcierski</option> <option value="kwidzynski">kwidzy\u0144ski</option> <option value="leborski">l\u0119borski</option> <option value="malborski">malborski</option> <option value="nowodworski">nowodworski</option> <option value="gdanski">gda\u0144ski</option> <option value="pucki">pucki</option> <option value="slupski">s\u0142upski</option> <option value="starogardzki">starogardzki</option> <option value="sztumski">sztumski</option> <option value="tczewski">tczewski</option> <option value="wejherowski">wejcherowski</option> <option value="katowice" selected="selected">Katowice</option> <option value="bielsko-biala">Bielsko-Bia\u0142a</option> <option value="bytom">Bytom</option> <option value="chorzow">Chorz\xf3w</option> <option value="czestochowa">Cz\u0119stochowa</option> <option value="dabrowa-gornicza">D\u0105browa G\xf3rnicza</option> <option value="gliwice">Gliwice</option> <option value="jastrzebie-zdroj">Jastrz\u0119bie Zdr\xf3j</option> <option value="jaworzno">Jaworzno</option> <option value="myslowice">Mys\u0142owice</option> <option value="piekary-slaskie">Piekary \u015al\u0105skie</option> <option value="ruda-slaska">Ruda \u015al\u0105ska</option> <option value="rybnik">Rybnik</option> <option value="siemianowice-slaskie">Siemianowice \u015al\u0105skie</option> <option value="sosnowiec">Sosnowiec</option> <option value="swietochlowice">\u015awi\u0119toch\u0142owice</option> <option value="tychy">Tychy</option> <option value="zabrze">Zabrze</option> <option value="zory">\u017bory</option> <option value="bedzinski">b\u0119dzi\u0144ski</option> <option value="bielski">bielski</option> <option value="bierunsko-ledzinski">bieru\u0144sko-l\u0119dzi\u0144ski</option> <option value="cieszynski">cieszy\u0144ski</option> <option value="czestochowski">cz\u0119stochowski</option> <option value="gliwicki">gliwicki</option> <option value="klobucki">k\u0142obucki</option> <option value="lubliniecki">lubliniecki</option> <option value="mikolowski">miko\u0142owski</option> <option value="myszkowski">myszkowski</option> <option value="pszczynski">pszczy\u0144ski</option> <option value="raciborski">raciborski</option> <option value="rybnicki">rybnicki</option> <option value="tarnogorski">tarnog\xf3rski</option> <option value="wodzislawski">wodzis\u0142awski</option> <option value="zawiercianski">zawiercia\u0144ski</option> <option value="zywiecki">\u017cywiecki</option> <option value="kielce">Kielce</option> <option value="buski">buski</option> <option value="jedrzejowski">j\u0119drzejowski</option> <option value="kazimierski">kazimierski</option> <option value="kielecki">kielecki</option> <option value="konecki">konecki</option> <option value="opatowski">opatowski</option> <option value="ostrowiecki">ostrowiecki</option> <option value="pinczowski">pi\u0144czowski</option> <option value="sandomierski">sandomierski</option> <option value="skarzyski">skar\u017cyski</option> <option value="starachowicki">starachowicki</option> <option value="staszowski">staszowski</option> <option value="wloszczowski">w\u0142oszczowski</option> <option value="olsztyn">Olsztyn</option> <option value="elblag">Elbl\u0105g</option> <option value="bartoszycki">bartoszycki</option> <option value="braniewski">braniewski</option> <option value="dzialdowski">dzia\u0142dowski</option> <option value="elblaski">elbl\u0105ski</option> <option value="elcki">e\u0142cki</option> <option value="gizycki">gi\u017cycki</option> <option value="goldapski">go\u0142dapski</option> <option value="ilawski">i\u0142awski</option> <option value="ketrzynski">k\u0119trzy\u0144ski</option> <option value="lidzbarski">lidzbarski</option> <option value="mragowski">mr\u0105gowski</option> <option value="nidzicki">nidzicki</option> <option value="nowomiejski">nowomiejski</option> <option value="olecki">olecki</option> <option value="olsztynski">olszty\u0144ski</option> <option value="ostrodzki">ostr\xf3dzki</option> <option value="piski">piski</option> <option value="szczycienski">szczycie\u0144ski</option> <option value="wegorzewski">w\u0119gorzewski</option> <option value="poznan">Pozna\u0144</option> <option value="kalisz">Kalisz</option> <option value="konin">Konin</option> <option value="leszno">Leszno</option> <option value="chodzieski">chodziejski</option> <option value="czarnkowsko-trzcianecki">czarnkowsko-trzcianecki</option> <option value="gnieznienski">gnie\u017anie\u0144ski</option> <option value="gostynski">gosty\u0144ski</option> <option value="grodziski">grodziski</option> <option value="jarocinski">jaroci\u0144ski</option> <option value="kaliski">kaliski</option> <option value="kepinski">k\u0119pi\u0144ski</option> <option value="kolski">kolski</option> <option value="koninski">koni\u0144ski</option> <option value="koscianski">ko\u015bcia\u0144ski</option> <option value="krotoszynski">krotoszy\u0144ski</option> <option value="leszczynski">leszczy\u0144ski</option> <option value="miedzychodzki">mi\u0119dzychodzki</option> <option value="nowotomyski">nowotomyski</option> <option value="obornicki">obornicki</option> <option value="ostrowski">ostrowski</option> <option value="ostrzeszowski">ostrzeszowski</option> <option value="pilski">pilski</option> <option value="pleszewski">pleszewski</option> <option value="poznanski">pozna\u0144ski</option> <option value="rawicki">rawicki</option> <option value="slupecki">s\u0142upecki</option> <option value="szamotulski">szamotulski</option> <option value="sredzki">\u015bredzki</option> <option value="sremski">\u015bremski</option> <option value="turecki">turecki</option> <option value="wagrowiecki">w\u0105growiecki</option> <option value="wolsztynski">wolszty\u0144ski</option> <option value="wrzesinski">wrzesi\u0144ski</option> <option value="zlotowski">z\u0142otowski</option> <option value="bialogardzki">bia\u0142ogardzki</option> <option value="choszczenski">choszcze\u0144ski</option> <option value="drawski">drawski</option> <option value="goleniowski">goleniowski</option> <option value="gryficki">gryficki</option> <option value="gryfinski">gryfi\u0144ski</option> <option value="kamienski">kamie\u0144ski</option> <option value="kolobrzeski">ko\u0142obrzeski</option> <option value="koszalinski">koszali\u0144ski</option> <option value="lobeski">\u0142obeski</option> <option value="mysliborski">my\u015bliborski</option> <option value="policki">policki</option> <option value="pyrzycki">pyrzycki</option> <option value="slawienski">s\u0142awie\u0144ski</option> <option value="stargardzki">stargardzki</option> <option value="szczecinecki">szczecinecki</option> <option value="swidwinski">\u015bwidwi\u0144ski</option> <option value="walecki">wa\u0142ecki</option> </select>''' self.assertEqual(f.render('administrativeunit', 'katowice'), out) def test_PLPostalCodeField(self): error_format = [u'Enter a postal code in the format XX-XXX.'] valid = { '41-403': '41-403', } invalid = { '43--434': error_format, } self.assertFieldOutput(PLPostalCodeField, valid, invalid) def test_PLNIPField(self): error_format = [u'Enter a tax number field (NIP) in the format XXX-XXX-XX-XX or XX-XX-XXX-XXX.'] error_checksum = [u'Wrong checksum for the Tax Number (NIP).'] valid = { '64-62-414-124': '6462414124', '646-241-41-24': '6462414124', } invalid = { '43-343-234-323': error_format, '646-241-41-23': error_checksum, } self.assertFieldOutput(PLNIPField, valid, invalid) def test_PLPESELField(self): error_checksum = [u'Wrong checksum for the National Identification Number.'] error_format = [u'National Identification Number consists of 11 digits.'] valid = { '80071610614': '80071610614', } invalid = { '80071610610': error_checksum, '80': error_format, '800716106AA': error_format, } self.assertFieldOutput(PLPESELField, valid, invalid) def test_PLREGONField(self): error_checksum = [u'Wrong checksum for the National Business Register Number (REGON).'] error_format = [u'National Business Register Number (REGON) consists of 9 or 14 digits.'] valid = { '12345678512347': '12345678512347', '590096454': '590096454', } invalid = { '123456784': error_checksum, '12345678412342': error_checksum, '590096453': error_checksum, '590096': error_format, } self.assertFieldOutput(PLREGONField, valid, invalid)
21,811
Python
.py
453
46.015453
104
0.776642
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,949
pt.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/pt.py
from django.contrib.localflavor.pt.forms import PTZipCodeField, PTPhoneNumberField from utils import LocalFlavorTestCase class PTLocalFlavorTests(LocalFlavorTestCase): def test_PTZipCodeField(self): error_format = [u'Enter a zip code in the format XXXX-XXX.'] valid = { '3030-034': '3030-034', '1003456': '1003-456', } invalid = { '2A200': error_format, '980001': error_format, } self.assertFieldOutput(PTZipCodeField, valid, invalid) def test_PTPhoneNumberField(self): error_format = [u'Phone numbers must have 9 digits, or start by + or 00'] valid = { '917845189': '917845189', '91 784 5189': '917845189', '91 784 5189': '917845189', '+351 91 111': '+35191111', '00351873': '00351873', } invalid = { '91 784 51 8': error_format, '091 456 987 1': error_format, } self.assertFieldOutput(PTPhoneNumberField, valid, invalid)
1,063
Python
.py
28
28.392857
82
0.588749
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,950
id.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/id.py
import warnings from django.contrib.localflavor.id.forms import (IDPhoneNumberField, IDPostCodeField, IDNationalIdentityNumberField, IDLicensePlateField, IDProvinceSelect, IDLicensePlatePrefixSelect) from utils import LocalFlavorTestCase class IDLocalFlavorTests(LocalFlavorTestCase): def setUp(self): self.save_warnings_state() warnings.filterwarnings( "ignore", category=RuntimeWarning, module='django.contrib.localflavor.id.id_choices' ) def tearDown(self): self.restore_warnings_state() def test_IDProvinceSelect(self): f = IDProvinceSelect() out = u'''<select name="provinces"> <option value="ACE">Aceh</option> <option value="BLI">Bali</option> <option value="BTN">Banten</option> <option value="BKL">Bengkulu</option> <option value="DIY">Yogyakarta</option> <option value="JKT">Jakarta</option> <option value="GOR">Gorontalo</option> <option value="JMB">Jambi</option> <option value="JBR">Jawa Barat</option> <option value="JTG">Jawa Tengah</option> <option value="JTM">Jawa Timur</option> <option value="KBR">Kalimantan Barat</option> <option value="KSL">Kalimantan Selatan</option> <option value="KTG">Kalimantan Tengah</option> <option value="KTM">Kalimantan Timur</option> <option value="BBL">Kepulauan Bangka-Belitung</option> <option value="KRI">Kepulauan Riau</option> <option value="LPG" selected="selected">Lampung</option> <option value="MLK">Maluku</option> <option value="MUT">Maluku Utara</option> <option value="NTB">Nusa Tenggara Barat</option> <option value="NTT">Nusa Tenggara Timur</option> <option value="PPA">Papua</option> <option value="PPB">Papua Barat</option> <option value="RIU">Riau</option> <option value="SLB">Sulawesi Barat</option> <option value="SLS">Sulawesi Selatan</option> <option value="SLT">Sulawesi Tengah</option> <option value="SLR">Sulawesi Tenggara</option> <option value="SLU">Sulawesi Utara</option> <option value="SMB">Sumatera Barat</option> <option value="SMS">Sumatera Selatan</option> <option value="SMU">Sumatera Utara</option> </select>''' self.assertEqual(f.render('provinces', 'LPG'), out) def test_IDLicensePlatePrefixSelect(self): f = IDLicensePlatePrefixSelect() out = u'''<select name="codes"> <option value="A">Banten</option> <option value="AA">Magelang</option> <option value="AB">Yogyakarta</option> <option value="AD">Surakarta - Solo</option> <option value="AE">Madiun</option> <option value="AG">Kediri</option> <option value="B">Jakarta</option> <option value="BA">Sumatera Barat</option> <option value="BB">Tapanuli</option> <option value="BD">Bengkulu</option> <option value="BE" selected="selected">Lampung</option> <option value="BG">Sumatera Selatan</option> <option value="BH">Jambi</option> <option value="BK">Sumatera Utara</option> <option value="BL">Nanggroe Aceh Darussalam</option> <option value="BM">Riau</option> <option value="BN">Kepulauan Bangka Belitung</option> <option value="BP">Kepulauan Riau</option> <option value="CC">Corps Consulate</option> <option value="CD">Corps Diplomatic</option> <option value="D">Bandung</option> <option value="DA">Kalimantan Selatan</option> <option value="DB">Sulawesi Utara Daratan</option> <option value="DC">Sulawesi Barat</option> <option value="DD">Sulawesi Selatan</option> <option value="DE">Maluku</option> <option value="DG">Maluku Utara</option> <option value="DH">NTT - Timor</option> <option value="DK">Bali</option> <option value="DL">Sulawesi Utara Kepulauan</option> <option value="DM">Gorontalo</option> <option value="DN">Sulawesi Tengah</option> <option value="DR">NTB - Lombok</option> <option value="DS">Papua dan Papua Barat</option> <option value="DT">Sulawesi Tenggara</option> <option value="E">Cirebon</option> <option value="EA">NTB - Sumbawa</option> <option value="EB">NTT - Flores</option> <option value="ED">NTT - Sumba</option> <option value="F">Bogor</option> <option value="G">Pekalongan</option> <option value="H">Semarang</option> <option value="K">Pati</option> <option value="KB">Kalimantan Barat</option> <option value="KH">Kalimantan Tengah</option> <option value="KT">Kalimantan Timur</option> <option value="L">Surabaya</option> <option value="M">Madura</option> <option value="N">Malang</option> <option value="P">Jember</option> <option value="R">Banyumas</option> <option value="RI">Federal Government</option> <option value="S">Bojonegoro</option> <option value="T">Purwakarta</option> <option value="W">Sidoarjo</option> <option value="Z">Garut</option> </select>''' self.assertEqual(f.render('codes', 'BE'), out) def test_IDPhoneNumberField(self): error_invalid = [u'Enter a valid phone number'] valid = { '0812-3456789': u'0812-3456789', '081234567890': u'081234567890', '021 345 6789': u'021 345 6789', '0213456789': u'0213456789', '+62-21-3456789': u'+62-21-3456789', '(021) 345 6789': u'(021) 345 6789', } invalid = { '0123456789': error_invalid, '+62-021-3456789': error_invalid, '+62-021-3456789': error_invalid, '+62-0812-3456789': error_invalid, '0812345678901': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDPhoneNumberField, valid, invalid) def test_IDPostCodeField(self): error_invalid = [u'Enter a valid post code'] valid = { '12340': u'12340', '25412': u'25412', ' 12340 ': u'12340', } invalid = { '12 3 4 0': error_invalid, '12345': error_invalid, '10100': error_invalid, '123456': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDPostCodeField, valid, invalid) def test_IDNationalIdentityNumberField(self): error_invalid = [u'Enter a valid NIK/KTP number'] valid = { ' 12.3456.010178 3456 ': u'12.3456.010178.3456', '1234560101783456': u'12.3456.010178.3456', '12.3456.010101.3456': u'12.3456.010101.3456', } invalid = { '12.3456.310278.3456': error_invalid, '00.0000.010101.0000': error_invalid, '1234567890123456': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDNationalIdentityNumberField, valid, invalid) def test_IDLicensePlateField(self): error_invalid = [u'Enter a valid vehicle license plate number'] valid = { ' b 1234 ab ': u'B 1234 AB', 'B 1234 ABC': u'B 1234 ABC', 'A 12': u'A 12', 'DK 12345 12': u'DK 12345 12', 'RI 10': u'RI 10', 'CD 12 12': u'CD 12 12', } invalid = { 'CD 10 12': error_invalid, 'CD 1234 12': error_invalid, 'RI 10 AB': error_invalid, 'B 12345 01': error_invalid, 'N 1234 12': error_invalid, 'A 12 XYZ': error_invalid, 'Q 1234 AB': error_invalid, 'foo': error_invalid, } self.assertFieldOutput(IDLicensePlateField, valid, invalid)
7,253
Python
.py
183
33.983607
77
0.665958
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,951
at.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/at.py
from django.contrib.localflavor.at.forms import (ATZipCodeField, ATStateSelect, ATSocialSecurityNumberField) from utils import LocalFlavorTestCase class ATLocalFlavorTests(LocalFlavorTestCase): def test_ATStateSelect(self): f = ATStateSelect() out = u'''<select name="bundesland"> <option value="BL">Burgenland</option> <option value="KA">Carinthia</option> <option value="NO">Lower Austria</option> <option value="OO">Upper Austria</option> <option value="SA">Salzburg</option> <option value="ST">Styria</option> <option value="TI">Tyrol</option> <option value="VO">Vorarlberg</option> <option value="WI" selected="selected">Vienna</option> </select>''' self.assertEqual(f.render('bundesland', 'WI'), out) def test_ATZipCodeField(self): error_format = [u'Enter a zip code in the format XXXX.'] valid = { '1150': '1150', '4020': '4020', '8020': '8020', } invalid = { '111222': error_format, 'eeffee': error_format, } self.assertFieldOutput(ATZipCodeField, valid, invalid) def test_ATSocialSecurityNumberField(self): error_format = [u'Enter a valid Austrian Social Security Number in XXXX XXXXXX format.'] valid = { '1237 010180': '1237 010180', } invalid = { '1237 010181': error_format, '12370 010180': error_format, } self.assertFieldOutput(ATSocialSecurityNumberField, valid, invalid)
1,525
Python
.py
40
31.2
96
0.652027
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,952
ro.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/forms/localflavor/ro.py
# -*- coding: utf-8 -*- from django.contrib.localflavor.ro.forms import (ROCIFField, ROCNPField, ROCountyField, ROCountySelect, ROIBANField, ROPhoneNumberField, ROPostalCodeField) from utils import LocalFlavorTestCase class ROLocalFlavorTests(LocalFlavorTestCase): def test_ROCountySelect(self): f = ROCountySelect() out = u'''<select name="county"> <option value="AB">Alba</option> <option value="AR">Arad</option> <option value="AG">Arge\u015f</option> <option value="BC">Bac\u0103u</option> <option value="BH">Bihor</option> <option value="BN">Bistri\u0163a-N\u0103s\u0103ud</option> <option value="BT">Boto\u015fani</option> <option value="BV">Bra\u015fov</option> <option value="BR">Br\u0103ila</option> <option value="B">Bucure\u015fti</option> <option value="BZ">Buz\u0103u</option> <option value="CS">Cara\u015f-Severin</option> <option value="CL">C\u0103l\u0103ra\u015fi</option> <option value="CJ" selected="selected">Cluj</option> <option value="CT">Constan\u0163a</option> <option value="CV">Covasna</option> <option value="DB">D\xe2mbovi\u0163a</option> <option value="DJ">Dolj</option> <option value="GL">Gala\u0163i</option> <option value="GR">Giurgiu</option> <option value="GJ">Gorj</option> <option value="HR">Harghita</option> <option value="HD">Hunedoara</option> <option value="IL">Ialomi\u0163a</option> <option value="IS">Ia\u015fi</option> <option value="IF">Ilfov</option> <option value="MM">Maramure\u015f</option> <option value="MH">Mehedin\u0163i</option> <option value="MS">Mure\u015f</option> <option value="NT">Neam\u0163</option> <option value="OT">Olt</option> <option value="PH">Prahova</option> <option value="SM">Satu Mare</option> <option value="SJ">S\u0103laj</option> <option value="SB">Sibiu</option> <option value="SV">Suceava</option> <option value="TR">Teleorman</option> <option value="TM">Timi\u015f</option> <option value="TL">Tulcea</option> <option value="VS">Vaslui</option> <option value="VL">V\xe2lcea</option> <option value="VN">Vrancea</option> </select>''' self.assertEqual(f.render('county', 'CJ'), out) def test_ROCIFField(self): error_invalid = [u'Enter a valid CIF.'] error_atmost = [u'Ensure this value has at most 10 characters (it has 11).'] error_atleast = [u'Ensure this value has at least 2 characters (it has 1).'] valid = { '21694681': u'21694681', 'RO21694681': u'21694681', } invalid = { '21694680': error_invalid, '21694680000': error_atmost, '0': error_atleast, } self.assertFieldOutput(ROCIFField, valid, invalid) def test_ROCNPField(self): error_invalid = [u'Enter a valid CNP.'] error_atleast = [u'Ensure this value has at least 13 characters (it has 10).'] error_atmost = [u'Ensure this value has at most 13 characters (it has 14).'] valid = { '1981211204489': '1981211204489', } invalid = { '1981211204487': error_invalid, '1981232204489': error_invalid, '9981211204489': error_invalid, '9981211209': error_atleast, '19812112044891': error_atmost, } self.assertFieldOutput(ROCNPField, valid, invalid) def test_ROCountyField(self): error_format = [u'Enter a Romanian county code or name.'] valid = { 'CJ': 'CJ', 'cj': 'CJ', u'Argeş': 'AG', u'argeş': 'AG', } invalid = { 'Arges': error_format, } self.assertFieldOutput(ROCountyField, valid, invalid) def test_ROIBANField(self): error_invalid = [u'Enter a valid IBAN in ROXX-XXXX-XXXX-XXXX-XXXX-XXXX format'] error_atleast = [u'Ensure this value has at least 24 characters (it has 23).'] valid = { 'RO56RZBR0000060003291177': 'RO56RZBR0000060003291177', 'RO56-RZBR-0000-0600-0329-1177': 'RO56RZBR0000060003291177', } invalid = { 'RO56RZBR0000060003291176': error_invalid, 'AT61 1904 3002 3457 3201': error_invalid, 'RO56RZBR000006000329117': error_atleast, } self.assertFieldOutput(ROIBANField, valid, invalid) def test_ROPhoneNumberField(self): error_format = [u'Phone numbers must be in XXXX-XXXXXX format.'] error_atleast = [u'Ensure this value has at least 10 characters (it has 9).'] valid = { '0264485936': '0264485936', '(0264)-485936': '0264485936', } invalid = { '02644859368': error_format, '026448593': error_atleast, } self.assertFieldOutput(ROPhoneNumberField, valid, invalid) def test_ROPostalCodeField(self): error_atleast = [u'Ensure this value has at least 6 characters (it has 5).'] error_atmost = [u'Ensure this value has at most 6 characters (it has 7).'] valid = { '400473': '400473', } invalid = { '40047': error_atleast, '4004731': error_atmost, } self.assertFieldOutput(ROPostalCodeField, valid, invalid)
5,203
Python
.py
130
33.238462
87
0.644537
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,953
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/handlers/tests.py
from django.utils import unittest from django.conf import settings from django.core.handlers.wsgi import WSGIHandler class HandlerTests(unittest.TestCase): def test_lock_safety(self): """ Tests for bug #11193 (errors inside middleware shouldn't leave the initLock locked). """ # Mangle settings so the handler will fail old_middleware_classes = settings.MIDDLEWARE_CLASSES settings.MIDDLEWARE_CLASSES = 42 # Try running the handler, it will fail in load_middleware handler = WSGIHandler() self.assertEqual(handler.initLock.locked(), False) try: handler(None, None) except: pass self.assertEqual(handler.initLock.locked(), False) # Reset settings settings.MIDDLEWARE_CLASSES = old_middleware_classes
850
Python
.py
22
30.772727
70
0.678788
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,954
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/file_storage/tests.py
# -*- coding: utf-8 -*- import os import shutil import sys import tempfile import time from datetime import datetime, timedelta try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: import threading except ImportError: import dummy_threading as threading from django.conf import settings from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured from django.core.files.base import ContentFile, File from django.core.files.images import get_image_dimensions from django.core.files.storage import FileSystemStorage, get_storage_class from django.core.files.uploadedfile import UploadedFile from django.utils import unittest # Try to import PIL in either of the two ways it can end up installed. # Checking for the existence of Image is enough for CPython, but # for PyPy, you need to check for the underlying modules try: from PIL import Image, _imaging except ImportError: try: import Image, _imaging except ImportError: Image = None class GetStorageClassTests(unittest.TestCase): def assertRaisesErrorWithMessage(self, error, message, callable, *args, **kwargs): self.assertRaises(error, callable, *args, **kwargs) try: callable(*args, **kwargs) except error, e: self.assertEqual(message, str(e)) def test_get_filesystem_storage(self): """ get_storage_class returns the class for a storage backend name/path. """ self.assertEqual( get_storage_class('django.core.files.storage.FileSystemStorage'), FileSystemStorage) def test_get_invalid_storage_module(self): """ get_storage_class raises an error if the requested import don't exist. """ self.assertRaisesErrorWithMessage( ImproperlyConfigured, "NonExistingStorage isn't a storage module.", get_storage_class, 'NonExistingStorage') def test_get_nonexisting_storage_class(self): """ get_storage_class raises an error if the requested class don't exist. """ self.assertRaisesErrorWithMessage( ImproperlyConfigured, 'Storage module "django.core.files.storage" does not define a '\ '"NonExistingStorage" class.', get_storage_class, 'django.core.files.storage.NonExistingStorage') def test_get_nonexisting_storage_module(self): """ get_storage_class raises an error if the requested module don't exist. """ # Error message may or may not be the fully qualified path. self.assertRaisesRegexp( ImproperlyConfigured, ('Error importing storage module django.core.files.non_existing_' 'storage: "No module named .*non_existing_storage"'), get_storage_class, 'django.core.files.non_existing_storage.NonExistingStorage' ) class FileStorageTests(unittest.TestCase): storage_class = FileSystemStorage def setUp(self): self.temp_dir = tempfile.mktemp() os.makedirs(self.temp_dir) self.storage = self.storage_class(location=self.temp_dir, base_url='/test_media_url/') def tearDown(self): shutil.rmtree(self.temp_dir) def test_file_access_options(self): """ Standard file access options are available, and work as expected. """ self.assertFalse(self.storage.exists('storage_test')) f = self.storage.open('storage_test', 'w') f.write('storage contents') f.close() self.assertTrue(self.storage.exists('storage_test')) f = self.storage.open('storage_test', 'r') self.assertEqual(f.read(), 'storage contents') f.close() self.storage.delete('storage_test') self.assertFalse(self.storage.exists('storage_test')) def test_file_accessed_time(self): """ File storage returns a Datetime object for the last accessed time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) atime = self.storage.accessed_time(f_name) self.assertEqual(atime, datetime.fromtimestamp( os.path.getatime(self.storage.path(f_name)))) self.assertTrue(datetime.now() - self.storage.accessed_time(f_name) < timedelta(seconds=2)) self.storage.delete(f_name) def test_file_created_time(self): """ File storage returns a Datetime object for the creation time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) ctime = self.storage.created_time(f_name) self.assertEqual(ctime, datetime.fromtimestamp( os.path.getctime(self.storage.path(f_name)))) self.assertTrue(datetime.now() - self.storage.created_time(f_name) < timedelta(seconds=2)) self.storage.delete(f_name) def test_file_modified_time(self): """ File storage returns a Datetime object for the last modified time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) mtime = self.storage.modified_time(f_name) self.assertEqual(mtime, datetime.fromtimestamp( os.path.getmtime(self.storage.path(f_name)))) self.assertTrue(datetime.now() - self.storage.modified_time(f_name) < timedelta(seconds=2)) self.storage.delete(f_name) def test_file_save_without_name(self): """ File storage extracts the filename from the content object if no name is given explicitly. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f.name = 'test.file' storage_f_name = self.storage.save(None, f) self.assertEqual(storage_f_name, f.name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name))) self.storage.delete(storage_f_name) def test_file_path(self): """ File storage returns the full path of a file """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name)) self.storage.delete(f_name) def test_file_url(self): """ File storage returns a url to access a given file from the Web. """ self.assertEqual(self.storage.url('test.file'), '%s%s' % (self.storage.base_url, 'test.file')) # should encode special chars except ~!*()' # like encodeURIComponent() JavaScript function do self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+=.file"""), """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%3D.file""") # should stanslate os path separator(s) to the url path separator self.assertEqual(self.storage.url("""a/b\\c.file"""), """/test_media_url/a/b/c.file""") self.storage.base_url = None self.assertRaises(ValueError, self.storage.url, 'test.file') def test_file_with_mixin(self): """ File storage can get a mixin to extend the functionality of the returned file. """ self.assertFalse(self.storage.exists('test.file')) class TestFileMixin(object): mixed_in = True f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.assertTrue(isinstance( self.storage.open('test.file', mixin=TestFileMixin), TestFileMixin )) self.storage.delete('test.file') def test_listdir(self): """ File storage returns a tuple containing directories and files. """ self.assertFalse(self.storage.exists('storage_test_1')) self.assertFalse(self.storage.exists('storage_test_2')) self.assertFalse(self.storage.exists('storage_dir_1')) f = self.storage.save('storage_test_1', ContentFile('custom content')) f = self.storage.save('storage_test_2', ContentFile('custom content')) os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1')) dirs, files = self.storage.listdir('') self.assertEqual(set(dirs), set([u'storage_dir_1'])) self.assertEqual(set(files), set([u'storage_test_1', u'storage_test_2'])) self.storage.delete('storage_test_1') self.storage.delete('storage_test_2') os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1')) def test_file_storage_prevents_directory_traversal(self): """ File storage prevents directory traversal (files can only be accessed if they're below the storage location). """ self.assertRaises(SuspiciousOperation, self.storage.exists, '..') self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd') class CustomStorage(FileSystemStorage): def get_available_name(self, name): """ Append numbers to duplicate files rather than underscores, like Trac. """ parts = name.split('.') basename, ext = parts[0], parts[1:] number = 2 while self.exists(name): name = '.'.join([basename, str(number)] + ext) number += 1 return name class CustomStorageTests(FileStorageTests): storage_class = CustomStorage def test_custom_get_available_name(self): first = self.storage.save('custom_storage', ContentFile('custom contents')) self.assertEqual(first, 'custom_storage') second = self.storage.save('custom_storage', ContentFile('more contents')) self.assertEqual(second, 'custom_storage.2') self.storage.delete(first) self.storage.delete(second) class UnicodeFileNameTests(unittest.TestCase): def test_unicode_file_names(self): """ Regression test for #8156: files with unicode names I can't quite figure out the encoding situation between doctest and this file, but the actual repr doesn't matter; it just shouldn't return a unicode object. """ uf = UploadedFile(name=u'¿Cómo?',content_type='text') self.assertEqual(type(uf.__repr__()), str) # Tests for a race condition on file saving (#4948). # This is written in such a way that it'll always pass on platforms # without threading. class SlowFile(ContentFile): def chunks(self): time.sleep(1) return super(ContentFile, self).chunks() class FileSaveRaceConditionTest(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) self.thread = threading.Thread(target=self.save_file, args=['conflict']) def tearDown(self): shutil.rmtree(self.storage_dir) def save_file(self, name): name = self.storage.save(name, SlowFile("Data")) def test_race_condition(self): self.thread.start() name = self.save_file('conflict') self.thread.join() self.assertTrue(self.storage.exists('conflict')) self.assertTrue(self.storage.exists('conflict_1')) self.storage.delete('conflict') self.storage.delete('conflict_1') class FileStoragePermissions(unittest.TestCase): def setUp(self): self.old_perms = settings.FILE_UPLOAD_PERMISSIONS settings.FILE_UPLOAD_PERMISSIONS = 0666 self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): settings.FILE_UPLOAD_PERMISSIONS = self.old_perms shutil.rmtree(self.storage_dir) def test_file_upload_permissions(self): name = self.storage.save("the_file", ContentFile("data")) actual_mode = os.stat(self.storage.path(name))[0] & 0777 self.assertEqual(actual_mode, 0666) class FileStoragePathParsing(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) def test_directory_with_dot(self): """Regression test for #9610. If the directory name contains a dot and the file name doesn't, make sure we still mangle the file name instead of the directory name. """ self.storage.save('dotted.path/test', ContentFile("1")) self.storage.save('dotted.path/test', ContentFile("2")) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1'))) def test_first_character_dot(self): """ File names with a dot as their first character don't have an extension, and the underscore should get added to the end. """ self.storage.save('dotted.path/.test', ContentFile("1")) self.storage.save('dotted.path/.test', ContentFile("2")) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test'))) # Before 2.6, a leading dot was treated as an extension, and so # underscore gets added to beginning instead of end. if sys.version_info < (2, 6): self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_1.test'))) else: self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1'))) class DimensionClosingBug(unittest.TestCase): """ Test that get_image_dimensions() properly closes files (#8817) """ @unittest.skipUnless(Image, "PIL not installed") def test_not_closing_of_files(self): """ Open files passed into get_image_dimensions() should stay opened. """ empty_io = StringIO() try: get_image_dimensions(empty_io) finally: self.assertTrue(not empty_io.closed) @unittest.skipUnless(Image, "PIL not installed") def test_closing_of_filenames(self): """ get_image_dimensions() called with a filename should closed the file. """ # We need to inject a modified open() builtin into the images module # that checks if the file was closed properly if the function is # called with a filename instead of an file object. # get_image_dimensions will call our catching_open instead of the # regular builtin one. class FileWrapper(object): _closed = [] def __init__(self, f): self.f = f def __getattr__(self, name): return getattr(self.f, name) def close(self): self._closed.append(True) self.f.close() def catching_open(*args): return FileWrapper(open(*args)) from django.core.files import images images.open = catching_open try: get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png")) finally: del images.open self.assertTrue(FileWrapper._closed) class InconsistentGetImageDimensionsBug(unittest.TestCase): """ Test that get_image_dimensions() works properly after various calls using a file handler (#11158) """ @unittest.skipUnless(Image, "PIL not installed") def test_multiple_calls(self): """ Multiple calls of get_image_dimensions() should return the same size. """ from django.core.files.images import ImageFile img_path = os.path.join(os.path.dirname(__file__), "test.png") image = ImageFile(open(img_path, 'rb')) image_pil = Image.open(img_path) size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image) self.assertEqual(image_pil.size, size_1) self.assertEqual(size_1, size_2)
16,422
Python
.py
372
35.696237
99
0.651177
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,955
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/custom_columns_regress/models.py
""" Regression for #9736. Checks some pathological column naming to make sure it doesn't break table creation or queries. """ from django.db import models class Article(models.Model): Article_ID = models.AutoField(primary_key=True, db_column='Article ID') headline = models.CharField(max_length=100) authors = models.ManyToManyField('Author', db_table='my m2m table') primary_author = models.ForeignKey('Author', db_column='Author ID', related_name='primary_set') def __unicode__(self): return self.headline class Meta: ordering = ('headline',) class Author(models.Model): Author_ID = models.AutoField(primary_key=True, db_column='Author ID') first_name = models.CharField(max_length=30, db_column='first name') last_name = models.CharField(max_length=30, db_column='last name') def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class Meta: db_table = 'my author table' ordering = ('last_name','first_name')
1,029
Python
.py
24
37.875
99
0.696878
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,956
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/custom_columns_regress/tests.py
from django.test import TestCase from django.core.exceptions import FieldError from models import Author, Article def pks(objects): """ Return pks to be able to compare lists""" return [o.pk for o in objects] class CustomColumnRegression(TestCase): def assertRaisesMessage(self, exc, msg, func, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.assertEqual(msg, str(e)) self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e))) def setUp(self): self.a1 = Author.objects.create(first_name='John', last_name='Smith') self.a2 = Author.objects.create(first_name='Peter', last_name='Jones') self.authors = [self.a1, self.a2] def test_basic_creation(self): art = Article(headline='Django lets you build Web apps easily', primary_author=self.a1) art.save() art.authors = [self.a1, self.a2] def test_author_querying(self): self.assertQuerysetEqual( Author.objects.all().order_by('last_name'), ['<Author: Peter Jones>', '<Author: John Smith>'] ) def test_author_filtering(self): self.assertQuerysetEqual( Author.objects.filter(first_name__exact='John'), ['<Author: John Smith>'] ) def test_author_get(self): self.assertEqual(self.a1, Author.objects.get(first_name__exact='John')) def test_filter_on_nonexistant_field(self): self.assertRaisesMessage( FieldError, "Cannot resolve keyword 'firstname' into field. Choices are: Author_ID, article, first_name, last_name, primary_set", Author.objects.filter, firstname__exact='John' ) def test_author_get_attributes(self): a = Author.objects.get(last_name__exact='Smith') self.assertEqual('John', a.first_name) self.assertEqual('Smith', a.last_name) self.assertRaisesMessage( AttributeError, "'Author' object has no attribute 'firstname'", getattr, a, 'firstname' ) self.assertRaisesMessage( AttributeError, "'Author' object has no attribute 'last'", getattr, a, 'last' ) def test_m2m_table(self): art = Article.objects.create(headline='Django lets you build Web apps easily', primary_author=self.a1) art.authors = self.authors self.assertQuerysetEqual( art.authors.all().order_by('last_name'), ['<Author: Peter Jones>', '<Author: John Smith>'] ) self.assertQuerysetEqual( self.a1.article_set.all(), ['<Article: Django lets you build Web apps easily>'] ) self.assertQuerysetEqual( art.authors.filter(last_name='Jones'), ['<Author: Peter Jones>'] )
2,919
Python
.py
71
31.704225
129
0.610229
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,957
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/null_queries/models.py
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) def __unicode__(self): return u"Q: %s " % self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) def __unicode__(self): return u"Choice: %s in poll %s" % (self.choice, self.poll) # A set of models with an inner one pointing to two outer ones. class OuterA(models.Model): pass class OuterB(models.Model): data = models.CharField(max_length=10) class Inner(models.Model): first = models.ForeignKey(OuterA) second = models.ForeignKey(OuterB, null=True)
668
Python
.py
18
32.833333
66
0.709176
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,958
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/null_queries/tests.py
from django.test import TestCase from django.core.exceptions import FieldError from regressiontests.null_queries.models import * class NullQueriesTests(TestCase): def test_none_as_null(self): """ Regression test for the use of None as a query value. None is interpreted as an SQL NULL, but only in __exact queries. Set up some initial polls and choices """ p1 = Poll(question='Why?') p1.save() c1 = Choice(poll=p1, choice='Because.') c1.save() c2 = Choice(poll=p1, choice='Why Not?') c2.save() # Exact query with value None returns nothing ("is NULL" in sql, # but every 'id' field has a value). self.assertQuerysetEqual(Choice.objects.filter(choice__exact=None), []) # Excluding the previous result returns everything. self.assertQuerysetEqual( Choice.objects.exclude(choice=None).order_by('id'), [ '<Choice: Choice: Because. in poll Q: Why? >', '<Choice: Choice: Why Not? in poll Q: Why? >' ] ) # Valid query, but fails because foo isn't a keyword self.assertRaises(FieldError, Choice.objects.filter, foo__exact=None) # Can't use None on anything other than __exact self.assertRaises(ValueError, Choice.objects.filter, id__gt=None) # Can't use None on anything other than __exact self.assertRaises(ValueError, Choice.objects.filter, foo__gt=None) # Related managers use __exact=None implicitly if the object hasn't been saved. p2 = Poll(question="How?") self.assertEqual(repr(p2.choice_set.all()), '[]') def test_reverse_relations(self): """ Querying across reverse relations and then another relation should insert outer joins correctly so as not to exclude results. """ obj = OuterA.objects.create() self.assertQuerysetEqual( OuterA.objects.filter(inner__second=None), ['<OuterA: OuterA object>'] ) self.assertQuerysetEqual( OuterA.objects.filter(inner__second__data=None), ['<OuterA: OuterA object>'] ) inner_obj = Inner.objects.create(first=obj) self.assertQuerysetEqual( Inner.objects.filter(first__inner__second=None), ['<Inner: Inner object>'] ) # Ticket #13815: check if <reverse>_isnull=False does not produce # faulty empty lists objB = OuterB.objects.create(data="reverse") self.assertQuerysetEqual( OuterB.objects.filter(inner__isnull=False), [] ) Inner.objects.create(first=obj) self.assertQuerysetEqual( OuterB.objects.exclude(inner__isnull=False), ['<OuterB: OuterB object>'] )
2,893
Python
.py
67
33.253731
87
0.614509
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,959
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_forms_regress/models.py
import os from django.db import models from django.core.exceptions import ValidationError class Person(models.Model): name = models.CharField(max_length=100) class Triple(models.Model): left = models.IntegerField() middle = models.IntegerField() right = models.IntegerField() class Meta: unique_together = (('left', 'middle'), (u'middle', u'right')) class FilePathModel(models.Model): path = models.FilePathField(path=os.path.dirname(__file__), match=".*\.py$", blank=True) class Publication(models.Model): title = models.CharField(max_length=30) date_published = models.DateField() def __unicode__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) def __unicode__(self): return self.headline class CustomFileField(models.FileField): def save_form_data(self, instance, data): been_here = getattr(self, 'been_saved', False) assert not been_here, "save_form_data called more than once" setattr(self, 'been_saved', True) class CustomFF(models.Model): f = CustomFileField(upload_to='unused', blank=True) class RealPerson(models.Model): name = models.CharField(max_length=100) def clean(self): if self.name.lower() == 'anonymous': raise ValidationError("Please specify a real name.") class Author(models.Model): publication = models.OneToOneField(Publication, null=True, blank=True) full_name = models.CharField(max_length=255) class Author1(models.Model): publication = models.OneToOneField(Publication, null=False) full_name = models.CharField(max_length=255) class Homepage(models.Model): url = models.URLField(verify_exists=False) class Document(models.Model): myfile = models.FileField(upload_to='unused', blank=True) class Edition(models.Model): author = models.ForeignKey(Person) publication = models.ForeignKey(Publication) edition = models.IntegerField() isbn = models.CharField(max_length=13, unique=True) class Meta: unique_together = (('author', 'publication'), ('publication', 'edition'),)
2,200
Python
.py
52
37.403846
92
0.720526
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,960
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_forms_regress/tests.py
from datetime import date from django import forms from django.core.exceptions import FieldError, ValidationError from django.core.files.uploadedfile import SimpleUploadedFile from django.forms.models import (modelform_factory, ModelChoiceField, fields_for_model, construct_instance) from django.utils import unittest from django.test import TestCase from models import Person, RealPerson, Triple, FilePathModel, Article, \ Publication, CustomFF, Author, Author1, Homepage, Document, Edition class ModelMultipleChoiceFieldTests(TestCase): def test_model_multiple_choice_number_of_queries(self): """ Test that ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Person.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Person.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]]) def test_model_multiple_choice_run_validators(self): """ Test that ModelMultipleChoiceField run given validators (#14144). """ for i in range(30): Person.objects.create(name="Person %s" % i) self._validator_run = False def my_validator(value): self._validator_run = True f = forms.ModelMultipleChoiceField(queryset=Person.objects.all(), validators=[my_validator]) f.clean([p.pk for p in Person.objects.all()[8:9]]) self.assertTrue(self._validator_run) class TripleForm(forms.ModelForm): class Meta: model = Triple class UniqueTogetherTests(TestCase): def test_multiple_field_unique_together(self): """ When the same field is involved in multiple unique_together constraints, we need to make sure we don't remove the data for it before doing all the validation checking (not just failing after the first one). """ Triple.objects.create(left=1, middle=2, right=3) form = TripleForm({'left': '1', 'middle': '2', 'right': '3'}) self.assertFalse(form.is_valid()) form = TripleForm({'left': '1', 'middle': '3', 'right': '1'}) self.assertTrue(form.is_valid()) class TripleFormWithCleanOverride(forms.ModelForm): class Meta: model = Triple def clean(self): if not self.cleaned_data['left'] == self.cleaned_data['right']: raise forms.ValidationError('Left and right should be equal') return self.cleaned_data class OverrideCleanTests(TestCase): def test_override_clean(self): """ Regression for #12596: Calling super from ModelForm.clean() should be optional. """ form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1}) self.assertTrue(form.is_valid()) # form.instance.left will be None if the instance was not constructed # by form.full_clean(). self.assertEqual(form.instance.left, 1) # Regression test for #12960. # Make sure the cleaned_data returned from ModelForm.clean() is applied to the # model instance. class PublicationForm(forms.ModelForm): def clean(self): self.cleaned_data['title'] = self.cleaned_data['title'].upper() return self.cleaned_data class Meta: model = Publication class ModelFormCleanTest(TestCase): def test_model_form_clean_applies_to_model(self): data = {'title': 'test', 'date_published': '2010-2-25'} form = PublicationForm(data) publication = form.save() self.assertEqual(publication.title, 'TEST') class FPForm(forms.ModelForm): class Meta: model = FilePathModel class FilePathFieldTests(TestCase): def test_file_path_field_blank(self): """ Regression test for #8842: FilePathField(blank=True) """ form = FPForm() names = [p[1] for p in form['path'].field.choices] names.sort() self.assertEqual(names, ['---------', '__init__.py', 'models.py', 'tests.py']) class ManyToManyCallableInitialTests(TestCase): def test_callable(self): "Regression for #10349: A callable can be provided as the initial value for an m2m field" # Set up a callable initial value def formfield_for_dbfield(db_field, **kwargs): if db_field.name == 'publications': kwargs['initial'] = lambda: Publication.objects.all().order_by('date_published')[:2] return db_field.formfield(**kwargs) # Set up some Publications to use as data book1 = Publication.objects.create(title="First Book", date_published=date(2007,1,1)) book2 = Publication.objects.create(title="Second Book", date_published=date(2008,1,1)) book3 = Publication.objects.create(title="Third Book", date_published=date(2009,1,1)) # Create a ModelForm, instantiate it, and check that the output is as expected ModelForm = modelform_factory(Article, formfield_callback=formfield_for_dbfield) form = ModelForm() self.assertEqual(form.as_ul(), u"""<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li> <li><label for="id_publications">Publications:</label> <select multiple="multiple" name="publications" id="id_publications"> <option value="%d" selected="selected">First Book</option> <option value="%d" selected="selected">Second Book</option> <option value="%d">Third Book</option> </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>""" % (book1.pk, book2.pk, book3.pk)) class CFFForm(forms.ModelForm): class Meta: model = CustomFF class CustomFieldSaveTests(TestCase): def test_save(self): "Regression for #11149: save_form_data should be called only once" # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. form = CFFForm(data = {'f': None}) form.save() class ModelChoiceIteratorTests(TestCase): def test_len(self): class Form(forms.ModelForm): class Meta: model = Article fields = ["publications"] Publication.objects.create(title="Pravda", date_published=date(1991, 8, 22)) f = Form() self.assertEqual(len(f.fields["publications"].choices), 1) class RealPersonForm(forms.ModelForm): class Meta: model = RealPerson class CustomModelFormSaveMethod(TestCase): def test_string_message(self): data = {'name': 'anonymous'} form = RealPersonForm(data) self.assertEqual(form.is_valid(), False) self.assertEqual(form.errors['__all__'], ['Please specify a real name.']) class ModelClassTests(TestCase): def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass self.assertRaises(ValueError, NoModelModelForm) class OneToOneFieldTests(TestCase): def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=date(1991, 8, 22)) author = Author.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['publication'], None) author = form.save() # author object returned from form still retains original publication object # that's why we need to retreive it from database again new_author = Author.objects.get(pk=author.pk) self.assertEqual(new_author.publication, None) def test_assignment_of_none_null_false(self): class AuthorForm(forms.ModelForm): class Meta: model = Author1 fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=date(1991, 8, 22)) author = Author1.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication':u'', 'full_name':'John Doe'}, instance=author) self.assertTrue(not form.is_valid()) class ModelChoiceForm(forms.Form): person = ModelChoiceField(Person.objects.all()) class TestTicket11183(TestCase): def test_11183(self): form1 = ModelChoiceForm() field1 = form1.fields['person'] # To allow the widget to change the queryset of field1.widget.choices correctly, # without affecting other forms, the following must hold: self.assertTrue(field1 is not ModelChoiceForm.base_fields['person']) self.assertTrue(field1.widget.choices.field is field1) class HomepageForm(forms.ModelForm): class Meta: model = Homepage class URLFieldTests(TestCase): def test_url_on_modelform(self): "Check basic URL field validation on model forms" self.assertFalse(HomepageForm({'url': 'foo'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://com.'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://localhost'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com/foo/bar'}).is_valid()) def test_http_prefixing(self): "If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613)" form = HomepageForm({'url': 'example.com'}) form.is_valid() # self.assertTrue(form.is_valid()) # self.assertEqual(form.cleaned_data['url'], 'http://example.com/') form = HomepageForm({'url': 'example.com/test'}) form.is_valid() # self.assertTrue(form.is_valid()) # self.assertEqual(form.cleaned_data['url'], 'http://example.com/test') class FormFieldCallbackTests(TestCase): def test_baseform_with_widgets_in_meta(self): """Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.""" widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} Form = modelform_factory(Person, form=BaseForm) self.assertTrue(Form.base_fields['name'].widget is widget) def test_custom_callback(self): """Test that a custom formfield_callback is used if provided""" callback_args = [] def callback(db_field, **kwargs): callback_args.append((db_field, kwargs)) return db_field.formfield(**kwargs) widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} _ = modelform_factory(Person, form=BaseForm, formfield_callback=callback) id_field, name_field = Person._meta.fields self.assertEqual(callback_args, [(id_field, {}), (name_field, {'widget': widget})]) def test_bad_callback(self): # A bad callback provided by user still gives an error self.assertRaises(TypeError, modelform_factory, Person, formfield_callback='not a function or callable') class InvalidFieldAndFactory(TestCase): """ Tests for #11905 """ def test_extra_field_model_form(self): try: class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'no-field') except FieldError, e: # Make sure the exception contains some reference to the # field responsible for the problem. self.assertTrue('no-field' in e.args[0]) else: self.fail('Invalid "no-field" field not caught') def test_extra_declared_field_model_form(self): try: class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'age') except FieldError: self.fail('Declarative field raised FieldError incorrectly') def test_extra_field_modelform_factory(self): self.assertRaises(FieldError, modelform_factory, Person, fields=['no-field', 'name']) class DocumentForm(forms.ModelForm): class Meta: model = Document class FileFieldTests(unittest.TestCase): def test_clean_false(self): """ If the ``clean`` method on a non-required FileField receives False as the data (meaning clear the field value), it returns False, regardless of the value of ``initial``. """ f = forms.FileField(required=False) self.assertEqual(f.clean(False), False) self.assertEqual(f.clean(False, 'initial'), False) def test_clean_false_required(self): """ If the ``clean`` method on a required FileField receives False as the data, it has the same effect as None: initial is returned if non-empty, otherwise the validation catches the lack of a required value. """ f = forms.FileField(required=True) self.assertEqual(f.clean(False, 'initial'), 'initial') self.assertRaises(ValidationError, f.clean, False) def test_full_clear(self): """ Integration happy-path test that a model FileField can actually be set and cleared via a ModelForm. """ form = DocumentForm() self.assertTrue('name="myfile"' in unicode(form)) self.assertTrue('myfile-clear' not in unicode(form)) form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', 'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) self.assertEqual(doc.myfile.name, 'something.txt') form = DocumentForm(instance=doc) self.assertTrue('myfile-clear' in unicode(form)) form = DocumentForm(instance=doc, data={'myfile-clear': 'true'}) doc = form.save(commit=False) self.assertEqual(bool(doc.myfile), False) def test_clear_and_file_contradiction(self): """ If the user submits a new file upload AND checks the clear checkbox, they get a validation error, and the bound redisplay of the form still includes the current file and the clear checkbox. """ form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', 'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) form = DocumentForm(instance=doc, files={'myfile': SimpleUploadedFile('something.txt', 'content')}, data={'myfile-clear': 'true'}) self.assertTrue(not form.is_valid()) self.assertEqual(form.errors['myfile'], [u'Please either submit a file or check the clear checkbox, not both.']) rendered = unicode(form) self.assertTrue('something.txt' in rendered) self.assertTrue('myfile-clear' in rendered) class EditionForm(forms.ModelForm): author = forms.ModelChoiceField(queryset=Person.objects.all()) publication = forms.ModelChoiceField(queryset=Publication.objects.all()) edition = forms.IntegerField() isbn = forms.CharField(max_length=13) class Meta: model = Edition class UniqueErrorsTests(TestCase): def setUp(self): self.author1 = Person.objects.create(name=u'Author #1') self.author2 = Person.objects.create(name=u'Author #2') self.pub1 = Publication.objects.create(title='Pub #1', date_published=date(2000, 10, 31)) self.pub2 = Publication.objects.create(title='Pub #2', date_published=date(2004, 1, 5)) form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub1.pk, 'edition': 1, 'isbn': '9783161484100'}) form.save() def test_unique_error_message(self): form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub2.pk, 'edition': 1, 'isbn': '9783161484100'}) self.assertEqual(form.errors, {'isbn': [u'Edition with this Isbn already exists.']}) def test_unique_together_error_message(self): form = EditionForm(data={'author': self.author1.pk, 'publication': self.pub1.pk, 'edition': 2, 'isbn': '9783161489999'}) self.assertEqual(form.errors, {'__all__': [u'Edition with this Author and Publication already exists.']}) form = EditionForm(data={'author': self.author2.pk, 'publication': self.pub1.pk, 'edition': 1, 'isbn': '9783161487777'}) self.assertEqual(form.errors, {'__all__': [u'Edition with this Publication and Edition already exists.']}) class EmptyFieldsTestCase(TestCase): "Tests for fields=() cases as reported in #14119" class EmptyPersonForm(forms.ModelForm): class Meta: model = Person fields = () def test_empty_fields_to_fields_for_model(self): "An argument of fields=() to fields_for_model should return an empty dictionary" field_dict = fields_for_model(Person, fields=()) self.assertEqual(len(field_dict), 0) def test_empty_fields_on_modelform(self): "No fields on a ModelForm should actually result in no fields" form = self.EmptyPersonForm() self.assertEqual(len(form.fields), 0) def test_empty_fields_to_construct_instance(self): "No fields should be set on a model instance if construct_instance receives fields=()" form = modelform_factory(Person)({'name': 'John Doe'}) self.assertTrue(form.is_valid()) instance = construct_instance(form, Person(), fields=()) self.assertEqual(instance.name, '')
18,937
Python
.py
373
41.823056
165
0.650771
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,961
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/delete_regress/models.py
from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType class Award(models.Model): name = models.CharField(max_length=25) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType) content_object = generic.GenericForeignKey() class AwardNote(models.Model): award = models.ForeignKey(Award) note = models.CharField(max_length=100) class Person(models.Model): name = models.CharField(max_length=25) awards = generic.GenericRelation(Award) class Book(models.Model): pagecount = models.IntegerField() class Toy(models.Model): name = models.CharField(max_length=50) class Child(models.Model): name = models.CharField(max_length=50) toys = models.ManyToManyField(Toy, through='PlayedWith') class PlayedWith(models.Model): child = models.ForeignKey(Child) toy = models.ForeignKey(Toy) date = models.DateField(db_column='date_col') class PlayedWithNote(models.Model): played = models.ForeignKey(PlayedWith) note = models.TextField() class Contact(models.Model): label = models.CharField(max_length=100) class Email(Contact): email_address = models.EmailField(max_length=100) class Researcher(models.Model): contacts = models.ManyToManyField(Contact, related_name="research_contacts") class Food(models.Model): name = models.CharField(max_length=20, unique=True) class Eaten(models.Model): food = models.ForeignKey(Food, to_field="name") meal = models.CharField(max_length=20)
1,583
Python
.py
39
36.871795
80
0.766667
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,962
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/delete_regress/tests.py
import datetime from django.conf import settings from django.db import backend, connection, transaction, DEFAULT_DB_ALIAS from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from models import (Book, Award, AwardNote, Person, Child, Toy, PlayedWith, PlayedWithNote, Contact, Email, Researcher, Food, Eaten) # Can't run this test under SQLite, because you can't # get two connections to an in-memory database. class DeleteLockingTest(TransactionTestCase): def setUp(self): # Create a second connection to the default database conn_settings = settings.DATABASES[DEFAULT_DB_ALIAS] self.conn2 = backend.DatabaseWrapper({ 'HOST': conn_settings['HOST'], 'NAME': conn_settings['NAME'], 'OPTIONS': conn_settings['OPTIONS'], 'PASSWORD': conn_settings['PASSWORD'], 'PORT': conn_settings['PORT'], 'USER': conn_settings['USER'], 'TIME_ZONE': settings.TIME_ZONE, }) # Put both DB connections into managed transaction mode transaction.enter_transaction_management() transaction.managed(True) self.conn2._enter_transaction_management(True) def tearDown(self): # Close down the second connection. transaction.leave_transaction_management() self.conn2.close() @skipUnlessDBFeature('test_db_allows_multiple_connections') def test_concurrent_delete(self): "Deletes on concurrent transactions don't collide and lock the database. Regression for #9479" # Create some dummy data b1 = Book(id=1, pagecount=100) b2 = Book(id=2, pagecount=200) b3 = Book(id=3, pagecount=300) b1.save() b2.save() b3.save() transaction.commit() self.assertEqual(3, Book.objects.count()) # Delete something using connection 2. cursor2 = self.conn2.cursor() cursor2.execute('DELETE from delete_regress_book WHERE id=1') self.conn2._commit(); # Now perform a queryset delete that covers the object # deleted in connection 2. This causes an infinite loop # under MySQL InnoDB unless we keep track of already # deleted objects. Book.objects.filter(pagecount__lt=250).delete() transaction.commit() self.assertEqual(1, Book.objects.count()) transaction.commit() class DeleteCascadeTests(TestCase): def test_generic_relation_cascade(self): """ Django cascades deletes through generic-related objects to their reverse relations. """ person = Person.objects.create(name='Nelson Mandela') award = Award.objects.create(name='Nobel', content_object=person) note = AwardNote.objects.create(note='a peace prize', award=award) self.assertEqual(AwardNote.objects.count(), 1) person.delete() self.assertEqual(Award.objects.count(), 0) # first two asserts are just sanity checks, this is the kicker: self.assertEqual(AwardNote.objects.count(), 0) def test_fk_to_m2m_through(self): """ If an M2M relationship has an explicitly-specified through model, and some other model has an FK to that through model, deletion is cascaded from one of the participants in the M2M, to the through model, to its related model. """ juan = Child.objects.create(name='Juan') paints = Toy.objects.create(name='Paints') played = PlayedWith.objects.create(child=juan, toy=paints, date=datetime.date.today()) note = PlayedWithNote.objects.create(played=played, note='the next Jackson Pollock') self.assertEqual(PlayedWithNote.objects.count(), 1) paints.delete() self.assertEqual(PlayedWith.objects.count(), 0) # first two asserts just sanity checks, this is the kicker: self.assertEqual(PlayedWithNote.objects.count(), 0) class DeleteCascadeTransactionTests(TransactionTestCase): def test_inheritance(self): """ Auto-created many-to-many through tables referencing a parent model are correctly found by the delete cascade when a child of that parent is deleted. Refs #14896. """ r = Researcher.objects.create() email = Email.objects.create( label="office-email", email_address="[email protected]" ) r.contacts.add(email) email.delete() def test_to_field(self): """ Cascade deletion works with ForeignKey.to_field set to non-PK. """ apple = Food.objects.create(name="apple") eaten = Eaten.objects.create(food=apple, meal="lunch") apple.delete() class LargeDeleteTests(TestCase): def test_large_deletes(self): "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs" for x in range(300): track = Book.objects.create(pagecount=x+100) Book.objects.all().delete() self.assertEqual(Book.objects.count(), 0)
5,217
Python
.py
114
36.438596
102
0.651438
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,963
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/middleware_exceptions/urls.py
# coding: utf-8 from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^view/$', views.normal_view), (r'^not_found/$', views.not_found), (r'^error/$', views.server_error), (r'^null_view/$', views.null_view), (r'^permission_denied/$', views.permission_denied), (r'^template_response/$', views.template_response), (r'^template_response_error/$', views.template_response_error), )
437
Python
.py
12
32.833333
67
0.668246
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,964
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/middleware_exceptions/tests.py
import sys from django.conf import settings from django.core.signals import got_request_exception from django.http import HttpResponse from django.template.response import TemplateResponse from django.template import Template from django.test import TestCase class TestException(Exception): pass # A middleware base class that tracks which methods have been called class TestMiddleware(object): def __init__(self): self.process_request_called = False self.process_view_called = False self.process_response_called = False self.process_template_response_called = False self.process_exception_called = False def process_request(self, request): self.process_request_called = True def process_view(self, request, view_func, view_args, view_kwargs): self.process_view_called = True def process_template_response(self, request, response): self.process_template_response_called = True return response def process_response(self, request, response): self.process_response_called = True return response def process_exception(self, request, exception): self.process_exception_called = True # Middleware examples that do the right thing class RequestMiddleware(TestMiddleware): def process_request(self, request): super(RequestMiddleware, self).process_request(request) return HttpResponse('Request Middleware') class ViewMiddleware(TestMiddleware): def process_view(self, request, view_func, view_args, view_kwargs): super(ViewMiddleware, self).process_view(request, view_func, view_args, view_kwargs) return HttpResponse('View Middleware') class ResponseMiddleware(TestMiddleware): def process_response(self, request, response): super(ResponseMiddleware, self).process_response(request, response) return HttpResponse('Response Middleware') class TemplateResponseMiddleware(TestMiddleware): def process_template_response(self, request, response): super(TemplateResponseMiddleware, self).process_template_response(request, response) return TemplateResponse(request, Template('Template Response Middleware')) class ExceptionMiddleware(TestMiddleware): def process_exception(self, request, exception): super(ExceptionMiddleware, self).process_exception(request, exception) return HttpResponse('Exception Middleware') # Sample middlewares that raise exceptions class BadRequestMiddleware(TestMiddleware): def process_request(self, request): super(BadRequestMiddleware, self).process_request(request) raise TestException('Test Request Exception') class BadViewMiddleware(TestMiddleware): def process_view(self, request, view_func, view_args, view_kwargs): super(BadViewMiddleware, self).process_view(request, view_func, view_args, view_kwargs) raise TestException('Test View Exception') class BadTemplateResponseMiddleware(TestMiddleware): def process_template_response(self, request, response): super(BadTemplateResponseMiddleware, self).process_template_response(request, response) raise TestException('Test Template Response Exception') class BadResponseMiddleware(TestMiddleware): def process_response(self, request, response): super(BadResponseMiddleware, self).process_response(request, response) raise TestException('Test Response Exception') class BadExceptionMiddleware(TestMiddleware): def process_exception(self, request, exception): super(BadExceptionMiddleware, self).process_exception(request, exception) raise TestException('Test Exception Exception') class BaseMiddlewareExceptionTest(TestCase): def setUp(self): self.exceptions = [] got_request_exception.connect(self._on_request_exception) self.client.handler.load_middleware() def tearDown(self): got_request_exception.disconnect(self._on_request_exception) self.exceptions = [] def _on_request_exception(self, sender, request, **kwargs): self.exceptions.append(sys.exc_info()) def _add_middleware(self, middleware): self.client.handler._request_middleware.insert(0, middleware.process_request) self.client.handler._view_middleware.insert(0, middleware.process_view) self.client.handler._template_response_middleware.append(middleware.process_template_response) self.client.handler._response_middleware.append(middleware.process_response) self.client.handler._exception_middleware.append(middleware.process_exception) def assert_exceptions_handled(self, url, errors, extra_error=None): try: response = self.client.get(url) except TestException, e: # Test client intentionally re-raises any exceptions being raised # during request handling. Hence actual testing that exception was # properly handled is done by relying on got_request_exception # signal being sent. pass except Exception, e: if type(extra_error) != type(e): self.fail("Unexpected exception: %s" % e) self.assertEqual(len(self.exceptions), len(errors)) for i, error in enumerate(errors): exception, value, tb = self.exceptions[i] self.assertEqual(value.args, (error, )) def assert_middleware_usage(self, middleware, request, view, template_response, response, exception): self.assertEqual(middleware.process_request_called, request) self.assertEqual(middleware.process_view_called, view) self.assertEqual(middleware.process_template_response_called, template_response) self.assertEqual(middleware.process_response_called, response) self.assertEqual(middleware.process_exception_called, exception) class MiddlewareTests(BaseMiddlewareExceptionTest): def test_process_request_middleware(self): pre_middleware = TestMiddleware() middleware = RequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_middleware(self): pre_middleware = TestMiddleware() middleware = ViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_middleware(self): pre_middleware = TestMiddleware() middleware = ResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_template_response_middleware(self): pre_middleware = TestMiddleware() middleware = TemplateResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/template_response/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, True, True, False) self.assert_middleware_usage(middleware, True, True, True, True, False) self.assert_middleware_usage(post_middleware, True, True, True, True, False) def test_process_exception_middleware(self): pre_middleware = TestMiddleware() middleware = ExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_request_middleware_not_found(self): pre_middleware = TestMiddleware() middleware = RequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_middleware_not_found(self): pre_middleware = TestMiddleware() middleware = ViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_template_response_middleware_not_found(self): pre_middleware = TestMiddleware() middleware = TemplateResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, True) self.assert_middleware_usage(middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_response_middleware_not_found(self): pre_middleware = TestMiddleware() middleware = ResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, True) self.assert_middleware_usage(middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_exception_middleware_not_found(self): pre_middleware = TestMiddleware() middleware = ExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_request_middleware_exception(self): pre_middleware = TestMiddleware() middleware = RequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_middleware_exception(self): pre_middleware = TestMiddleware() middleware = ViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_middleware_exception(self): pre_middleware = TestMiddleware() middleware = ResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', ['Error in view'], Exception()) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, True) self.assert_middleware_usage(middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_exception_middleware_exception(self): pre_middleware = TestMiddleware() middleware = ExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_request_middleware_null_view(self): pre_middleware = TestMiddleware() middleware = RequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_middleware_null_view(self): pre_middleware = TestMiddleware() middleware = ViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_middleware_null_view(self): pre_middleware = TestMiddleware() middleware = ResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', [ "The view regressiontests.middleware_exceptions.views.null_view didn't return an HttpResponse object.", ], ValueError()) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_exception_middleware_null_view(self): pre_middleware = TestMiddleware() middleware = ExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', [ "The view regressiontests.middleware_exceptions.views.null_view didn't return an HttpResponse object." ], ValueError()) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_request_middleware_permission_denied(self): pre_middleware = TestMiddleware() middleware = RequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_middleware_permission_denied(self): pre_middleware = TestMiddleware() middleware = ViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_middleware_permission_denied(self): pre_middleware = TestMiddleware() middleware = ResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, True) self.assert_middleware_usage(middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_exception_middleware_permission_denied(self): pre_middleware = TestMiddleware() middleware = ExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_template_response_error(self): middleware = TestMiddleware() self._add_middleware(middleware) self.assert_exceptions_handled('/middleware_exceptions/template_response_error/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(middleware, True, True, True, True, False) class BadMiddlewareTests(BaseMiddlewareExceptionTest): def test_process_request_bad_middleware(self): pre_middleware = TestMiddleware() bad_middleware = BadRequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test Request Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(bad_middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_bad_middleware(self): pre_middleware = TestMiddleware() bad_middleware = BadViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test View Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_template_response_bad_middleware(self): pre_middleware = TestMiddleware() bad_middleware = BadTemplateResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/template_response/', ['Test Template Response Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, True, True, False) self.assert_middleware_usage(post_middleware, True, True, True, True, False) def test_process_response_bad_middleware(self): pre_middleware = TestMiddleware() bad_middleware = BadResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test Response Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, False, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_exception_bad_middleware(self): pre_middleware = TestMiddleware() bad_middleware = BadExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/view/', []) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_request_bad_middleware_not_found(self): pre_middleware = TestMiddleware() bad_middleware = BadRequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Request Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(bad_middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_bad_middleware_not_found(self): pre_middleware = TestMiddleware() bad_middleware = BadViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test View Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_bad_middleware_not_found(self): pre_middleware = TestMiddleware() bad_middleware = BadResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Response Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, False, True) self.assert_middleware_usage(bad_middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_exception_bad_middleware_not_found(self): pre_middleware = TestMiddleware() bad_middleware = BadExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Exception Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_request_bad_middleware_exception(self): pre_middleware = TestMiddleware() bad_middleware = BadRequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test Request Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(bad_middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_bad_middleware_exception(self): pre_middleware = TestMiddleware() bad_middleware = BadViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test View Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_bad_middleware_exception(self): pre_middleware = TestMiddleware() bad_middleware = BadResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', ['Error in view', 'Test Response Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, False, True) self.assert_middleware_usage(bad_middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_exception_bad_middleware_exception(self): pre_middleware = TestMiddleware() bad_middleware = BadExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test Exception Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_request_bad_middleware_null_view(self): pre_middleware = TestMiddleware() bad_middleware = BadRequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', ['Test Request Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(bad_middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_bad_middleware_null_view(self): pre_middleware = TestMiddleware() bad_middleware = BadViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', ['Test View Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_bad_middleware_null_view(self): pre_middleware = TestMiddleware() bad_middleware = BadResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', [ "The view regressiontests.middleware_exceptions.views.null_view didn't return an HttpResponse object.", 'Test Response Exception' ]) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, False, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_exception_bad_middleware_null_view(self): pre_middleware = TestMiddleware() bad_middleware = BadExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/null_view/', [ "The view regressiontests.middleware_exceptions.views.null_view didn't return an HttpResponse object." ], ValueError()) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, True, False, True, False) def test_process_request_bad_middleware_permission_denied(self): pre_middleware = TestMiddleware() bad_middleware = BadRequestMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Request Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, False, False, True, False) self.assert_middleware_usage(bad_middleware, True, False, False, True, False) self.assert_middleware_usage(post_middleware, False, False, False, True, False) def test_process_view_bad_middleware_permission_denied(self): pre_middleware = TestMiddleware() bad_middleware = BadViewMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test View Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, False) self.assert_middleware_usage(post_middleware, True, False, False, True, False) def test_process_response_bad_middleware_permission_denied(self): pre_middleware = TestMiddleware() bad_middleware = BadResponseMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Response Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, False, True) self.assert_middleware_usage(bad_middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) def test_process_exception_bad_middleware_permission_denied(self): pre_middleware = TestMiddleware() bad_middleware = BadExceptionMiddleware() post_middleware = TestMiddleware() self._add_middleware(post_middleware) self._add_middleware(bad_middleware) self._add_middleware(pre_middleware) self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Exception Exception']) # Check that the right middleware methods have been invoked self.assert_middleware_usage(pre_middleware, True, True, False, True, False) self.assert_middleware_usage(bad_middleware, True, True, False, True, True) self.assert_middleware_usage(post_middleware, True, True, False, True, True) _missing = object() class RootUrlconfTests(TestCase): def test_missing_root_urlconf(self): try: original_ROOT_URLCONF = settings.ROOT_URLCONF del settings.ROOT_URLCONF except AttributeError: original_ROOT_URLCONF = _missing self.assertRaises(AttributeError, self.client.get, "/middleware_exceptions/view/" ) if original_ROOT_URLCONF is not _missing: settings.ROOT_URLCONF = original_ROOT_URLCONF
39,506
Python
.py
658
51.392097
121
0.708217
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,965
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/middleware_exceptions/views.py
from django import http from django.core.exceptions import PermissionDenied from django.template import Template from django.template.response import TemplateResponse def normal_view(request): return http.HttpResponse('OK') def template_response(request): return TemplateResponse(request, Template('OK')) def template_response_error(request): return TemplateResponse(request, Template('{%')) def not_found(request): raise http.Http404() def server_error(request): raise Exception('Error in view') def null_view(request): return None def permission_denied(request): raise PermissionDenied()
626
Python
.py
18
31.777778
53
0.796667
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,966
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_validation/models.py
""" Tests of ModelAdmin validation logic. """ from django.db import models class Album(models.Model): title = models.CharField(max_length=150) class Song(models.Model): title = models.CharField(max_length=150) album = models.ForeignKey(Album) original_release = models.DateField(editable=False) class Meta: ordering = ('title',) def __unicode__(self): return self.title def readonly_method_on_model(self): # does nothing pass class TwoAlbumFKAndAnE(models.Model): album1 = models.ForeignKey(Album, related_name="album1_set") album2 = models.ForeignKey(Album, related_name="album2_set") e = models.CharField(max_length=1) class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=100) subtitle = models.CharField(max_length=100) price = models.FloatField() authors = models.ManyToManyField(Author, through='AuthorsBooks') class AuthorsBooks(models.Model): author = models.ForeignKey(Author) book = models.ForeignKey(Book) class State(models.Model): name = models.CharField(max_length=15) class City(models.Model): state = models.ForeignKey(State)
1,245
Python
.py
35
30.914286
68
0.727731
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,967
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_validation/tests.py
from django.contrib import admin from django import forms from django.contrib.admin.validation import validate, validate_inline, \ ImproperlyConfigured from django.test import TestCase from models import Song, Book, Album, TwoAlbumFKAndAnE, State, City class SongForm(forms.ModelForm): pass class ValidFields(admin.ModelAdmin): form = SongForm fields = ['title'] class InvalidFields(admin.ModelAdmin): form = SongForm fields = ['spam'] class ValidationTestCase(TestCase): def assertRaisesMessage(self, exc, msg, func, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.assertEqual(msg, str(e)) self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e))) def test_readonly_and_editable(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ["original_release"] fieldsets = [ (None, { "fields": ["title", "original_release"], }), ] validate(SongAdmin, Song) def test_custom_modelforms_with_fields_fieldsets(self): """ # Regression test for #8027: custom ModelForms with fields/fieldsets """ validate(ValidFields, Song) self.assertRaisesMessage(ImproperlyConfigured, "'InvalidFields.fields' refers to field 'spam' that is missing from the form.", validate, InvalidFields, Song) def test_exclude_values(self): """ Tests for basic validation of 'exclude' option values (#12689) """ class ExcludedFields1(admin.ModelAdmin): exclude = ('foo') self.assertRaisesMessage(ImproperlyConfigured, "'ExcludedFields1.exclude' must be a list or tuple.", validate, ExcludedFields1, Book) def test_exclude_duplicate_values(self): class ExcludedFields2(admin.ModelAdmin): exclude = ('name', 'name') self.assertRaisesMessage(ImproperlyConfigured, "There are duplicate field(s) in ExcludedFields2.exclude", validate, ExcludedFields2, Book) def test_exclude_in_inline(self): class ExcludedFieldsInline(admin.TabularInline): model = Song exclude = ('foo') class ExcludedFieldsAlbumAdmin(admin.ModelAdmin): model = Album inlines = [ExcludedFieldsInline] self.assertRaisesMessage(ImproperlyConfigured, "'ExcludedFieldsInline.exclude' must be a list or tuple.", validate, ExcludedFieldsAlbumAdmin, Album) def test_exclude_inline_model_admin(self): """ # Regression test for #9932 - exclude in InlineModelAdmin # should not contain the ForeignKey field used in ModelAdmin.model """ class SongInline(admin.StackedInline): model = Song exclude = ['album'] class AlbumAdmin(admin.ModelAdmin): model = Album inlines = [SongInline] self.assertRaisesMessage(ImproperlyConfigured, "SongInline cannot exclude the field 'album' - this is the foreign key to the parent model Album.", validate, AlbumAdmin, Album) def test_fk_exclusion(self): """ Regression test for #11709 - when testing for fk excluding (when exclude is given) make sure fk_name is honored or things blow up when there is more than one fk to the parent model. """ class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE exclude = ("e",) fk_name = "album1" validate_inline(TwoAlbumFKAndAnEInline, None, Album) def test_inline_self_validation(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE self.assertRaisesMessage(Exception, "<class 'regressiontests.admin_validation.models.TwoAlbumFKAndAnE'> has more than 1 ForeignKey to <class 'regressiontests.admin_validation.models.Album'>", validate_inline, TwoAlbumFKAndAnEInline, None, Album) def test_inline_with_specified(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE fk_name = "album1" validate_inline(TwoAlbumFKAndAnEInline, None, Album) def test_readonly(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title",) validate(SongAdmin, Song) def test_readonly_on_method(self): def my_function(obj): pass class SongAdmin(admin.ModelAdmin): readonly_fields = (my_function,) validate(SongAdmin, Song) def test_readonly_on_modeladmin(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_modeladmin",) def readonly_method_on_modeladmin(self, obj): pass validate(SongAdmin, Song) def test_readonly_method_on_model(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_model",) validate(SongAdmin, Song) def test_nonexistant_field(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title", "nonexistant") self.assertRaisesMessage(ImproperlyConfigured, "SongAdmin.readonly_fields[1], 'nonexistant' is not a callable or an attribute of 'SongAdmin' or found in the model 'Song'.", validate, SongAdmin, Song) def test_nonexistant_field_on_inline(self): class CityInline(admin.TabularInline): model = City readonly_fields=['i_dont_exist'] # Missing attribute self.assertRaisesMessage(ImproperlyConfigured, "CityInline.readonly_fields[0], 'i_dont_exist' is not a callable or an attribute of 'CityInline' or found in the model 'City'.", validate_inline, CityInline, None, State) def test_extra(self): class SongAdmin(admin.ModelAdmin): def awesome_song(self, instance): if instance.title == "Born to Run": return "Best Ever!" return "Status unknown." validate(SongAdmin, Song) def test_readonly_lambda(self): class SongAdmin(admin.ModelAdmin): readonly_fields = (lambda obj: "test",) validate(SongAdmin, Song) def test_graceful_m2m_fail(self): """ Regression test for #12203/#12237 - Fail more gracefully when a M2M field that specifies the 'through' option is included in the 'fields' or the 'fieldsets' ModelAdmin options. """ class BookAdmin(admin.ModelAdmin): fields = ['authors'] self.assertRaisesMessage(ImproperlyConfigured, "'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", validate, BookAdmin, Book) def test_cannon_include_through(self): class FieldsetBookAdmin(admin.ModelAdmin): fieldsets = ( ('Header 1', {'fields': ('name',)}), ('Header 2', {'fields': ('authors',)}), ) self.assertRaisesMessage(ImproperlyConfigured, "'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", validate, FieldsetBookAdmin, Book) def test_nested_fieldsets(self): class NestedFieldsetAdmin(admin.ModelAdmin): fieldsets = ( ('Main', {'fields': ('price', ('name', 'subtitle'))}), ) validate(NestedFieldsetAdmin, Book) def test_explicit_through_override(self): """ Regression test for #12209 -- If the explicitly provided through model is specified as a string, the admin should still be able use Model.m2m_field.through """ class AuthorsInline(admin.TabularInline): model = Book.authors.through class BookAdmin(admin.ModelAdmin): inlines = [AuthorsInline] # If the through model is still a string (and hasn't been resolved to a model) # the validation will fail. validate(BookAdmin, Book) def test_non_model_fields(self): """ Regression for ensuring ModelAdmin.fields can contain non-model fields that broke with r11737 """ class SongForm(forms.ModelForm): extra_data = forms.CharField() class Meta: model = Song class FieldsOnFormOnlyAdmin(admin.ModelAdmin): form = SongForm fields = ['title', 'extra_data'] validate(FieldsOnFormOnlyAdmin, Song)
9,015
Python
.py
205
33.565854
167
0.629651
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,968
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/string_lookup/models.py
# -*- coding: utf-8 -*- from django.db import models class Foo(models.Model): name = models.CharField(max_length=50) friend = models.CharField(max_length=50, blank=True) def __unicode__(self): return "Foo %s" % self.name class Bar(models.Model): name = models.CharField(max_length=50) normal = models.ForeignKey(Foo, related_name='normal_foo') fwd = models.ForeignKey("Whiz") back = models.ForeignKey("Foo") def __unicode__(self): return "Bar %s" % self.place.name class Whiz(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return "Whiz %s" % self.name class Child(models.Model): parent = models.OneToOneField('Base') name = models.CharField(max_length=50) def __unicode__(self): return "Child %s" % self.name class Base(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return "Base %s" % self.name class Article(models.Model): name = models.CharField(max_length=50) text = models.TextField() submitted_from = models.IPAddressField(blank=True, null=True) def __str__(self): return "Article %s" % self.name
1,199
Python
.py
33
31.212121
65
0.664645
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,969
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/string_lookup/tests.py
# -*- coding: utf-8 -*- from django.test import TestCase from regressiontests.string_lookup.models import Foo, Whiz, Bar, Article, Base, Child class StringLookupTests(TestCase): def test_string_form_referencing(self): """ Regression test for #1661 and #1662 Check that string form referencing of models works, both as pre and post reference, on all RelatedField types. """ f1 = Foo(name="Foo1") f1.save() f2 = Foo(name="Foo2") f2.save() w1 = Whiz(name="Whiz1") w1.save() b1 = Bar(name="Bar1", normal=f1, fwd=w1, back=f2) b1.save() self.assertEqual(b1.normal, f1) self.assertEqual(b1.fwd, w1) self.assertEqual(b1.back, f2) base1 = Base(name="Base1") base1.save() child1 = Child(name="Child1", parent=base1) child1.save() self.assertEqual(child1.parent, base1) def test_unicode_chars_in_queries(self): """ Regression tests for #3937 make sure we can use unicode characters in queries. If these tests fail on MySQL, it's a problem with the test setup. A properly configured UTF-8 database can handle this. """ fx = Foo(name='Bjorn', friend=u'François') fx.save() self.assertEqual(Foo.objects.get(friend__contains=u'\xe7'), fx) # We can also do the above query using UTF-8 strings. self.assertEqual(Foo.objects.get(friend__contains='\xc3\xa7'), fx) def test_queries_on_textfields(self): """ Regression tests for #5087 make sure we can perform queries on TextFields. """ a = Article(name='Test', text='The quick brown fox jumps over the lazy dog.') a.save() self.assertEqual(Article.objects.get(text__exact='The quick brown fox jumps over the lazy dog.'), a) self.assertEqual(Article.objects.get(text__contains='quick brown fox'), a) def test_ipaddress_on_postgresql(self): """ Regression test for #708 "like" queries on IP address fields require casting to text (on PostgreSQL). """ a = Article(name='IP test', text='The body', submitted_from='192.0.2.100') a.save() self.assertEqual(repr(Article.objects.filter(submitted_from__contains='192.0.2')), repr([a]))
2,384
Python
.py
56
33.964286
108
0.624892
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,970
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/aggregation_regress/models.py
# coding: utf-8 from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) def __unicode__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=255) num_awards = models.IntegerField() def __unicode__(self): return self.name class Book(models.Model): isbn = models.CharField(max_length=9) name = models.CharField(max_length=255) pages = models.IntegerField() rating = models.FloatField() price = models.DecimalField(decimal_places=2, max_digits=6) authors = models.ManyToManyField(Author) contact = models.ForeignKey(Author, related_name='book_contact_set') publisher = models.ForeignKey(Publisher) pubdate = models.DateField() class Meta: ordering = ('name',) def __unicode__(self): return self.name class Store(models.Model): name = models.CharField(max_length=255) books = models.ManyToManyField(Book) original_opening = models.DateTimeField() friday_night_closing = models.TimeField() def __unicode__(self): return self.name class Entries(models.Model): EntryID = models.AutoField(primary_key=True, db_column='Entry ID') Entry = models.CharField(unique=True, max_length=50) Exclude = models.BooleanField() class Clues(models.Model): ID = models.AutoField(primary_key=True) EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column = 'Entry ID') Clue = models.CharField(max_length=150) class HardbackBook(Book): weight = models.FloatField() def __unicode__(self): return "%s (hardback): %s" % (self.name, self.weight)
1,778
Python
.py
46
33.5
86
0.703444
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,971
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/aggregation_regress/tests.py
import datetime import pickle from decimal import Decimal from operator import attrgetter from django.core.exceptions import FieldError from django.db.models import Count, Max, Avg, Sum, StdDev, Variance, F, Q from django.test import TestCase, Approximate, skipUnlessDBFeature from models import Author, Book, Publisher, Clues, Entries, HardbackBook class AggregationTests(TestCase): def assertObjectAttrs(self, obj, **kwargs): for attr, value in kwargs.iteritems(): self.assertEqual(getattr(obj, attr), value) def test_aggregates_in_where_clause(self): """ Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Tests that the subselect works and returns results equivalent to a query with the IDs listed. Before the corresponding fix for this bug, this test passed in 1.1 and failed in 1.2-beta (trunk). """ qs = Book.objects.values('contact').annotate(Max('id')) qs = qs.order_by('contact').values_list('id__max', flat=True) # don't do anything with the queryset (qs) before including it as a # subquery books = Book.objects.order_by('id') qs1 = books.filter(id__in=qs) qs2 = books.filter(id__in=list(qs)) self.assertEqual(list(qs1), list(qs2)) def test_aggregates_in_where_clause_pre_eval(self): """ Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Same as the above test, but evaluates the queryset for the subquery before it's used as a subquery. Before the corresponding fix for this bug, this test failed in both 1.1 and 1.2-beta (trunk). """ qs = Book.objects.values('contact').annotate(Max('id')) qs = qs.order_by('contact').values_list('id__max', flat=True) # force the queryset (qs) for the subquery to be evaluated in its # current state list(qs) books = Book.objects.order_by('id') qs1 = books.filter(id__in=qs) qs2 = books.filter(id__in=list(qs)) self.assertEqual(list(qs1), list(qs2)) @skipUnlessDBFeature('supports_subqueries_in_group_by') def test_annotate_with_extra(self): """ Regression test for #11916: Extra params + aggregation creates incorrect SQL. """ #oracle doesn't support subqueries in group by clause shortest_book_sql = """ SELECT name FROM aggregation_regress_book b WHERE b.publisher_id = aggregation_regress_publisher.id ORDER BY b.pages LIMIT 1 """ # tests that this query does not raise a DatabaseError due to the full # subselect being (erroneously) added to the GROUP BY parameters qs = Publisher.objects.extra(select={ 'name_of_shortest_book': shortest_book_sql, }).annotate(total_books=Count('book')) # force execution of the query list(qs) def test_aggregate(self): # Ordering requests are ignored self.assertEqual( Author.objects.order_by("name").aggregate(Avg("age")), {"age__avg": Approximate(37.444, places=1)} ) # Implicit ordering is also ignored self.assertEqual( Book.objects.aggregate(Sum("pages")), {"pages__sum": 3703}, ) # Baseline results self.assertEqual( Book.objects.aggregate(Sum('pages'), Avg('pages')), {'pages__sum': 3703, 'pages__avg': Approximate(617.166, places=2)} ) # Empty values query doesn't affect grouping or results self.assertEqual( Book.objects.values().aggregate(Sum('pages'), Avg('pages')), {'pages__sum': 3703, 'pages__avg': Approximate(617.166, places=2)} ) # Aggregate overrides extra selected column self.assertEqual( Book.objects.extra(select={'price_per_page' : 'price / pages'}).aggregate(Sum('pages')), {'pages__sum': 3703} ) def test_annotation(self): # Annotations get combined with extra select clauses obj = Book.objects.annotate(mean_auth_age=Avg("authors__age")).extra(select={"manufacture_cost": "price * .5"}).get(pk=2) self.assertObjectAttrs(obj, contact_id=3, id=2, isbn=u'067232959', mean_auth_age=45.0, name='Sams Teach Yourself Django in 24 Hours', pages=528, price=Decimal("23.09"), pubdate=datetime.date(2008, 3, 3), publisher_id=2, rating=3.0 ) # Different DB backends return different types for the extra select computation self.assertTrue(obj.manufacture_cost == 11.545 or obj.manufacture_cost == Decimal('11.545')) # Order of the annotate/extra in the query doesn't matter obj = Book.objects.extra(select={'manufacture_cost' : 'price * .5'}).annotate(mean_auth_age=Avg('authors__age')).get(pk=2) self.assertObjectAttrs(obj, contact_id=3, id=2, isbn=u'067232959', mean_auth_age=45.0, name=u'Sams Teach Yourself Django in 24 Hours', pages=528, price=Decimal("23.09"), pubdate=datetime.date(2008, 3, 3), publisher_id=2, rating=3.0 ) # Different DB backends return different types for the extra select computation self.assertTrue(obj.manufacture_cost == 11.545 or obj.manufacture_cost == Decimal('11.545')) # Values queries can be combined with annotate and extra obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).values().get(pk=2) manufacture_cost = obj['manufacture_cost'] self.assertTrue(manufacture_cost == 11.545 or manufacture_cost == Decimal('11.545')) del obj['manufacture_cost'] self.assertEqual(obj, { "contact_id": 3, "id": 2, "isbn": u"067232959", "mean_auth_age": 45.0, "name": u"Sams Teach Yourself Django in 24 Hours", "pages": 528, "price": Decimal("23.09"), "pubdate": datetime.date(2008, 3, 3), "publisher_id": 2, "rating": 3.0, }) # The order of the (empty) values, annotate and extra clauses doesn't # matter obj = Book.objects.values().annotate(mean_auth_age=Avg('authors__age')).extra(select={'manufacture_cost' : 'price * .5'}).get(pk=2) manufacture_cost = obj['manufacture_cost'] self.assertTrue(manufacture_cost == 11.545 or manufacture_cost == Decimal('11.545')) del obj['manufacture_cost'] self.assertEqual(obj, { 'contact_id': 3, 'id': 2, 'isbn': u'067232959', 'mean_auth_age': 45.0, 'name': u'Sams Teach Yourself Django in 24 Hours', 'pages': 528, 'price': Decimal("23.09"), 'pubdate': datetime.date(2008, 3, 3), 'publisher_id': 2, 'rating': 3.0 }) # If the annotation precedes the values clause, it won't be included # unless it is explicitly named obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name').get(pk=1) self.assertEqual(obj, { "name": u'The Definitive Guide to Django: Web Development Done Right', }) obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name','mean_auth_age').get(pk=1) self.assertEqual(obj, { 'mean_auth_age': 34.5, 'name': u'The Definitive Guide to Django: Web Development Done Right', }) # If an annotation isn't included in the values, it can still be used # in a filter qs = Book.objects.annotate(n_authors=Count('authors')).values('name').filter(n_authors__gt=2) self.assertQuerysetEqual( qs, [ {"name": u'Python Web Development with Django'} ], lambda b: b, ) # The annotations are added to values output if values() precedes # annotate() obj = Book.objects.values('name').annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).get(pk=1) self.assertEqual(obj, { 'mean_auth_age': 34.5, 'name': u'The Definitive Guide to Django: Web Development Done Right', }) # Check that all of the objects are getting counted (allow_nulls) and # that values respects the amount of objects self.assertEqual( len(Author.objects.annotate(Avg('friends__age')).values()), 9 ) # Check that consecutive calls to annotate accumulate in the query qs = Book.objects.values('price').annotate(oldest=Max('authors__age')).order_by('oldest', 'price').annotate(Max('publisher__num_awards')) self.assertQuerysetEqual( qs, [ {'price': Decimal("30"), 'oldest': 35, 'publisher__num_awards__max': 3}, {'price': Decimal("29.69"), 'oldest': 37, 'publisher__num_awards__max': 7}, {'price': Decimal("23.09"), 'oldest': 45, 'publisher__num_awards__max': 1}, {'price': Decimal("75"), 'oldest': 57, 'publisher__num_awards__max': 9}, {'price': Decimal("82.8"), 'oldest': 57, 'publisher__num_awards__max': 7} ], lambda b: b, ) def test_aggrate_annotation(self): # Aggregates can be composed over annotations. # The return type is derived from the composed aggregate vals = Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('pages'), Max('price'), Sum('num_authors'), Avg('num_authors')) self.assertEqual(vals, { 'num_authors__sum': 10, 'num_authors__avg': Approximate(1.666, places=2), 'pages__max': 1132, 'price__max': Decimal("82.80") }) def test_field_error(self): # Bad field requests in aggregates are caught and reported self.assertRaises( FieldError, lambda: Book.objects.all().aggregate(num_authors=Count('foo')) ) self.assertRaises( FieldError, lambda: Book.objects.all().annotate(num_authors=Count('foo')) ) self.assertRaises( FieldError, lambda: Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo')) ) def test_more(self): # Old-style count aggregations can be mixed with new-style self.assertEqual( Book.objects.annotate(num_authors=Count('authors')).count(), 6 ) # Non-ordinal, non-computed Aggregates over annotations correctly # inherit the annotation's internal type if the annotation is ordinal # or computed vals = Book.objects.annotate(num_authors=Count('authors')).aggregate(Max('num_authors')) self.assertEqual( vals, {'num_authors__max': 3} ) vals = Publisher.objects.annotate(avg_price=Avg('book__price')).aggregate(Max('avg_price')) self.assertEqual( vals, {'avg_price__max': 75.0} ) # Aliases are quoted to protected aliases that might be reserved names vals = Book.objects.aggregate(number=Max('pages'), select=Max('pages')) self.assertEqual( vals, {'number': 1132, 'select': 1132} ) # Regression for #10064: select_related() plays nice with aggregates obj = Book.objects.select_related('publisher').annotate(num_authors=Count('authors')).values()[0] self.assertEqual(obj, { 'contact_id': 8, 'id': 5, 'isbn': u'013790395', 'name': u'Artificial Intelligence: A Modern Approach', 'num_authors': 2, 'pages': 1132, 'price': Decimal("82.8"), 'pubdate': datetime.date(1995, 1, 15), 'publisher_id': 3, 'rating': 4.0, }) # Regression for #10010: exclude on an aggregate field is correctly # negated self.assertEqual( len(Book.objects.annotate(num_authors=Count('authors'))), 6 ) self.assertEqual( len(Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=2)), 1 ) self.assertEqual( len(Book.objects.annotate(num_authors=Count('authors')).exclude(num_authors__gt=2)), 5 ) self.assertEqual( len(Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__lt=3).exclude(num_authors__lt=2)), 2 ) self.assertEqual( len(Book.objects.annotate(num_authors=Count('authors')).exclude(num_authors__lt=2).filter(num_authors__lt=3)), 2 ) def test_aggregate_fexpr(self): # Aggregates can be used with F() expressions # ... where the F() is pushed into the HAVING clause qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ {'num_books': 1, 'name': u'Morgan Kaufmann', 'num_awards': 9}, {'num_books': 2, 'name': u'Prentice Hall', 'num_awards': 7} ], lambda p: p, ) qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ {'num_books': 2, 'name': u'Apress', 'num_awards': 3}, {'num_books': 0, 'name': u"Jonno's House of Books", 'num_awards': 0}, {'num_books': 1, 'name': u'Sams', 'num_awards': 1} ], lambda p: p, ) # ... and where the F() references an aggregate qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_awards__gt=2*F('num_books')).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ {'num_books': 1, 'name': u'Morgan Kaufmann', 'num_awards': 9}, {'num_books': 2, 'name': u'Prentice Hall', 'num_awards': 7} ], lambda p: p, ) qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') self.assertQuerysetEqual( qs, [ {'num_books': 2, 'name': u'Apress', 'num_awards': 3}, {'num_books': 0, 'name': u"Jonno's House of Books", 'num_awards': 0}, {'num_books': 1, 'name': u'Sams', 'num_awards': 1} ], lambda p: p, ) def test_db_col_table(self): # Tests on fields with non-default table and column names. qs = Clues.objects.values('EntryID__Entry').annotate(Appearances=Count('EntryID'), Distinct_Clues=Count('Clue', distinct=True)) self.assertQuerysetEqual(qs, []) qs = Entries.objects.annotate(clue_count=Count('clues__ID')) self.assertQuerysetEqual(qs, []) def test_empty(self): # Regression for #10089: Check handling of empty result sets with # aggregates self.assertEqual( Book.objects.filter(id__in=[]).count(), 0 ) vals = Book.objects.filter(id__in=[]).aggregate(num_authors=Count('authors'), avg_authors=Avg('authors'), max_authors=Max('authors'), max_price=Max('price'), max_rating=Max('rating')) self.assertEqual( vals, {'max_authors': None, 'max_rating': None, 'num_authors': 0, 'avg_authors': None, 'max_price': None} ) qs = Publisher.objects.filter(pk=5).annotate(num_authors=Count('book__authors'), avg_authors=Avg('book__authors'), max_authors=Max('book__authors'), max_price=Max('book__price'), max_rating=Max('book__rating')).values() self.assertQuerysetEqual( qs, [ {'max_authors': None, 'name': u"Jonno's House of Books", 'num_awards': 0, 'max_price': None, 'num_authors': 0, 'max_rating': None, 'id': 5, 'avg_authors': None} ], lambda p: p ) def test_more_more(self): # Regression for #10113 - Fields mentioned in order_by() must be # included in the GROUP BY. This only becomes a problem when the # order_by introduces a new join. self.assertQuerysetEqual( Book.objects.annotate(num_authors=Count('authors')).order_by('publisher__name', 'name'), [ "Practical Django Projects", "The Definitive Guide to Django: Web Development Done Right", "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp", "Artificial Intelligence: A Modern Approach", "Python Web Development with Django", "Sams Teach Yourself Django in 24 Hours", ], lambda b: b.name ) # Regression for #10127 - Empty select_related() works with annotate qs = Book.objects.filter(rating__lt=4.5).select_related().annotate(Avg('authors__age')) self.assertQuerysetEqual( qs, [ (u'Artificial Intelligence: A Modern Approach', 51.5, u'Prentice Hall', u'Peter Norvig'), (u'Practical Django Projects', 29.0, u'Apress', u'James Bennett'), (u'Python Web Development with Django', Approximate(30.333, places=2), u'Prentice Hall', u'Jeffrey Forcier'), (u'Sams Teach Yourself Django in 24 Hours', 45.0, u'Sams', u'Brad Dayley') ], lambda b: (b.name, b.authors__age__avg, b.publisher.name, b.contact.name) ) # Regression for #10132 - If the values() clause only mentioned extra # (select=) columns, those columns are used for grouping qs = Book.objects.extra(select={'pub':'publisher_id'}).values('pub').annotate(Count('id')).order_by('pub') self.assertQuerysetEqual( qs, [ {'pub': 1, 'id__count': 2}, {'pub': 2, 'id__count': 1}, {'pub': 3, 'id__count': 2}, {'pub': 4, 'id__count': 1} ], lambda b: b ) qs = Book.objects.extra(select={'pub':'publisher_id', 'foo':'pages'}).values('pub').annotate(Count('id')).order_by('pub') self.assertQuerysetEqual( qs, [ {'pub': 1, 'id__count': 2}, {'pub': 2, 'id__count': 1}, {'pub': 3, 'id__count': 2}, {'pub': 4, 'id__count': 1} ], lambda b: b ) # Regression for #10182 - Queries with aggregate calls are correctly # realiased when used in a subquery ids = Book.objects.filter(pages__gt=100).annotate(n_authors=Count('authors')).filter(n_authors__gt=2).order_by('n_authors') self.assertQuerysetEqual( Book.objects.filter(id__in=ids), [ "Python Web Development with Django", ], lambda b: b.name ) def test_duplicate_alias(self): # Regression for #11256 - duplicating a default alias raises ValueError. self.assertRaises(ValueError, Book.objects.all().annotate, Avg('authors__age'), authors__age__avg=Avg('authors__age')) def test_field_name_conflict(self): # Regression for #11256 - providing an aggregate name that conflicts with a field name on the model raises ValueError self.assertRaises(ValueError, Author.objects.annotate, age=Avg('friends__age')) def test_m2m_name_conflict(self): # Regression for #11256 - providing an aggregate name that conflicts with an m2m name on the model raises ValueError self.assertRaises(ValueError, Author.objects.annotate, friends=Count('friends')) def test_values_queryset_non_conflict(self): # Regression for #14707 -- If you're using a values query set, some potential conflicts are avoided. # age is a field on Author, so it shouldn't be allowed as an aggregate. # But age isn't included in the ValuesQuerySet, so it is. results = Author.objects.values('name').annotate(age=Count('book_contact_set')).order_by('name') self.assertEqual(len(results), 9) self.assertEqual(results[0]['name'], u'Adrian Holovaty') self.assertEqual(results[0]['age'], 1) # Same problem, but aggregating over m2m fields results = Author.objects.values('name').annotate(age=Avg('friends__age')).order_by('name') self.assertEqual(len(results), 9) self.assertEqual(results[0]['name'], u'Adrian Holovaty') self.assertEqual(results[0]['age'], 32.0) # Same problem, but colliding with an m2m field results = Author.objects.values('name').annotate(friends=Count('friends')).order_by('name') self.assertEqual(len(results), 9) self.assertEqual(results[0]['name'], u'Adrian Holovaty') self.assertEqual(results[0]['friends'], 2) def test_reverse_relation_name_conflict(self): # Regression for #11256 - providing an aggregate name that conflicts with a reverse-related name on the model raises ValueError self.assertRaises(ValueError, Author.objects.annotate, book_contact_set=Avg('friends__age')) def test_pickle(self): # Regression for #10197 -- Queries with aggregates can be pickled. # First check that pickling is possible at all. No crash = success qs = Book.objects.annotate(num_authors=Count('authors')) pickle.dumps(qs) # Then check that the round trip works. query = qs.query.get_compiler(qs.db).as_sql()[0] qs2 = pickle.loads(pickle.dumps(qs)) self.assertEqual( qs2.query.get_compiler(qs2.db).as_sql()[0], query, ) def test_more_more_more(self): # Regression for #10199 - Aggregate calls clone the original query so # the original query can still be used books = Book.objects.all() books.aggregate(Avg("authors__age")) self.assertQuerysetEqual( books.all(), [ u'Artificial Intelligence: A Modern Approach', u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp', u'Practical Django Projects', u'Python Web Development with Django', u'Sams Teach Yourself Django in 24 Hours', u'The Definitive Guide to Django: Web Development Done Right' ], lambda b: b.name ) # Regression for #10248 - Annotations work with DateQuerySets qs = Book.objects.annotate(num_authors=Count('authors')).filter(num_authors=2).dates('pubdate', 'day') self.assertQuerysetEqual( qs, [ datetime.datetime(1995, 1, 15, 0, 0), datetime.datetime(2007, 12, 6, 0, 0) ], lambda b: b ) # Regression for #10290 - extra selects with parameters can be used for # grouping. qs = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'sheets' : '(pages + %s) / %s'}, select_params=[1, 2]).order_by('sheets').values('sheets') self.assertQuerysetEqual( qs, [ 150, 175, 224, 264, 473, 566 ], lambda b: int(b["sheets"]) ) # Regression for 10425 - annotations don't get in the way of a count() # clause self.assertEqual( Book.objects.values('publisher').annotate(Count('publisher')).count(), 4 ) self.assertEqual( Book.objects.annotate(Count('publisher')).values('publisher').count(), 6 ) publishers = Publisher.objects.filter(id__in=[1, 2]) self.assertEqual( sorted(p.name for p in publishers), [ "Apress", "Sams" ] ) publishers = publishers.annotate(n_books=Count("book")) self.assertEqual( publishers[0].n_books, 2 ) self.assertEqual( sorted(p.name for p in publishers), [ "Apress", "Sams" ] ) books = Book.objects.filter(publisher__in=publishers) self.assertQuerysetEqual( books, [ "Practical Django Projects", "Sams Teach Yourself Django in 24 Hours", "The Definitive Guide to Django: Web Development Done Right", ], lambda b: b.name ) self.assertEqual( sorted(p.name for p in publishers), [ "Apress", "Sams" ] ) # Regression for 10666 - inherited fields work with annotations and # aggregations self.assertEqual( HardbackBook.objects.aggregate(n_pages=Sum('book_ptr__pages')), {'n_pages': 2078} ) self.assertEqual( HardbackBook.objects.aggregate(n_pages=Sum('pages')), {'n_pages': 2078}, ) qs = HardbackBook.objects.annotate(n_authors=Count('book_ptr__authors')).values('name', 'n_authors') self.assertQuerysetEqual( qs, [ {'n_authors': 2, 'name': u'Artificial Intelligence: A Modern Approach'}, {'n_authors': 1, 'name': u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} ], lambda h: h ) qs = HardbackBook.objects.annotate(n_authors=Count('authors')).values('name', 'n_authors') self.assertQuerysetEqual( qs, [ {'n_authors': 2, 'name': u'Artificial Intelligence: A Modern Approach'}, {'n_authors': 1, 'name': u'Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'} ], lambda h: h, ) # Regression for #10766 - Shouldn't be able to reference an aggregate # fields in an an aggregate() call. self.assertRaises( FieldError, lambda: Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age')) ) def test_empty_filter_count(self): self.assertEqual( Author.objects.filter(id__in=[]).annotate(Count("friends")).count(), 0 ) def test_empty_filter_aggregate(self): self.assertEqual( Author.objects.filter(id__in=[]).annotate(Count("friends")).aggregate(Count("pk")), {"pk__count": None} ) def test_annotate_and_join(self): self.assertEqual( Author.objects.annotate(c=Count("friends__name")).exclude(friends__name="Joe").count(), Author.objects.count() ) def test_f_expression_annotation(self): # Books with less than 200 pages per author. qs = Book.objects.values("name").annotate( n_authors=Count("authors") ).filter( pages__lt=F("n_authors") * 200 ).values_list("pk") self.assertQuerysetEqual( Book.objects.filter(pk__in=qs), [ "Python Web Development with Django" ], attrgetter("name") ) def test_values_annotate_values(self): qs = Book.objects.values("name").annotate( n_authors=Count("authors") ).values_list("pk", flat=True) self.assertEqual(list(qs), list(Book.objects.values_list("pk", flat=True))) def test_having_group_by(self): # Test that when a field occurs on the LHS of a HAVING clause that it # appears correctly in the GROUP BY clause qs = Book.objects.values_list("name").annotate( n_authors=Count("authors") ).filter( pages__gt=F("n_authors") ).values_list("name", flat=True) # Results should be the same, all Books have more pages than authors self.assertEqual( list(qs), list(Book.objects.values_list("name", flat=True)) ) def test_annotation_disjunction(self): qs = Book.objects.annotate(n_authors=Count("authors")).filter( Q(n_authors=2) | Q(name="Python Web Development with Django") ) self.assertQuerysetEqual( qs, [ "Artificial Intelligence: A Modern Approach", "Python Web Development with Django", "The Definitive Guide to Django: Web Development Done Right", ], attrgetter("name") ) qs = Book.objects.annotate(n_authors=Count("authors")).filter( Q(name="The Definitive Guide to Django: Web Development Done Right") | (Q(name="Artificial Intelligence: A Modern Approach") & Q(n_authors=3)) ) self.assertQuerysetEqual( qs, [ "The Definitive Guide to Django: Web Development Done Right", ], attrgetter("name") ) qs = Publisher.objects.annotate( rating_sum=Sum("book__rating"), book_count=Count("book") ).filter( Q(rating_sum__gt=5.5) | Q(rating_sum__isnull=True) ).order_by('pk') self.assertQuerysetEqual( qs, [ "Apress", "Prentice Hall", "Jonno's House of Books", ], attrgetter("name") ) qs = Publisher.objects.annotate( rating_sum=Sum("book__rating"), book_count=Count("book") ).filter( Q(pk__lt=F("book_count")) | Q(rating_sum=None) ).order_by("pk") self.assertQuerysetEqual( qs, [ "Apress", "Jonno's House of Books", ], attrgetter("name") ) def test_quoting_aggregate_order_by(self): qs = Book.objects.filter( name="Python Web Development with Django" ).annotate( authorCount=Count("authors") ).order_by("authorCount") self.assertQuerysetEqual( qs, [ ("Python Web Development with Django", 3), ], lambda b: (b.name, b.authorCount) ) @skipUnlessDBFeature('supports_stddev') def test_stddev(self): self.assertEqual( Book.objects.aggregate(StdDev('pages')), {'pages__stddev': Approximate(311.46, 1)} ) self.assertEqual( Book.objects.aggregate(StdDev('rating')), {'rating__stddev': Approximate(0.60, 1)} ) self.assertEqual( Book.objects.aggregate(StdDev('price')), {'price__stddev': Approximate(24.16, 2)} ) self.assertEqual( Book.objects.aggregate(StdDev('pages', sample=True)), {'pages__stddev': Approximate(341.19, 2)} ) self.assertEqual( Book.objects.aggregate(StdDev('rating', sample=True)), {'rating__stddev': Approximate(0.66, 2)} ) self.assertEqual( Book.objects.aggregate(StdDev('price', sample=True)), {'price__stddev': Approximate(26.46, 1)} ) self.assertEqual( Book.objects.aggregate(Variance('pages')), {'pages__variance': Approximate(97010.80, 1)} ) self.assertEqual( Book.objects.aggregate(Variance('rating')), {'rating__variance': Approximate(0.36, 1)} ) self.assertEqual( Book.objects.aggregate(Variance('price')), {'price__variance': Approximate(583.77, 1)} ) self.assertEqual( Book.objects.aggregate(Variance('pages', sample=True)), {'pages__variance': Approximate(116412.96, 1)} ) self.assertEqual( Book.objects.aggregate(Variance('rating', sample=True)), {'rating__variance': Approximate(0.44, 2)} ) self.assertEqual( Book.objects.aggregate(Variance('price', sample=True)), {'price__variance': Approximate(700.53, 2)} )
32,986
Python
.py
726
34.422865
227
0.579019
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,972
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/multiple_database/models.py
from django.conf import settings from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db import models class Review(models.Model): source = models.CharField(max_length=100) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() def __unicode__(self): return self.source class Meta: ordering = ('source',) class PersonManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Person(models.Model): objects = PersonManager() name = models.CharField(max_length=100) def __unicode__(self): return self.name class Meta: ordering = ('name',) # This book manager doesn't do anything interesting; it just # exists to strip out the 'extra_arg' argument to certain # calls. This argument is used to establish that the BookManager # is actually getting used when it should be. class BookManager(models.Manager): def create(self, *args, **kwargs): kwargs.pop('extra_arg', None) return super(BookManager, self).create(*args, **kwargs) def get_or_create(self, *args, **kwargs): kwargs.pop('extra_arg', None) return super(BookManager, self).get_or_create(*args, **kwargs) class Book(models.Model): objects = BookManager() title = models.CharField(max_length=100) published = models.DateField() authors = models.ManyToManyField(Person) editor = models.ForeignKey(Person, null=True, related_name='edited') reviews = generic.GenericRelation(Review) pages = models.IntegerField(default=100) def __unicode__(self): return self.title class Meta: ordering = ('title',) class Pet(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(Person) def __unicode__(self): return self.name class Meta: ordering = ('name',) class UserProfile(models.Model): user = models.OneToOneField(User, null=True) flavor = models.CharField(max_length=100) class Meta: ordering = ('flavor',)
2,243
Python
.py
59
32.864407
72
0.707891
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,973
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/multiple_database/tests.py
import datetime import pickle import sys from StringIO import StringIO from django.conf import settings from django.contrib.auth.models import User from django.core import management from django.db import connections, router, DEFAULT_DB_ALIAS from django.db.models import signals from django.db.utils import ConnectionRouter from django.test import TestCase from models import Book, Person, Pet, Review, UserProfile try: # we only have these models if the user is using multi-db, it's safe the # run the tests without them though. from models import Article, article_using except ImportError: pass class QueryTestCase(TestCase): multi_db = True def test_db_selection(self): "Check that querysets will use the default database by default" self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS) self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS) self.assertEqual(Book.objects.using('other').db, 'other') self.assertEqual(Book.objects.db_manager('other').db, 'other') self.assertEqual(Book.objects.db_manager('other').all().db, 'other') def test_default_creation(self): "Objects created on the default database don't leak onto other databases" # Create a book on the default database using create() Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) # Create a book on the default database using a save dive = Book() dive.title="Dive into Python" dive.published = datetime.date(2009, 5, 4) dive.save() # Check that book exists on the default database, but not on other database try: Book.objects.get(title="Pro Django") Book.objects.using('default').get(title="Pro Django") except Book.DoesNotExist: self.fail('"Dive Into Python" should exist on default database') self.assertRaises(Book.DoesNotExist, Book.objects.using('other').get, title="Pro Django" ) try: Book.objects.get(title="Dive into Python") Book.objects.using('default').get(title="Dive into Python") except Book.DoesNotExist: self.fail('"Dive into Python" should exist on default database') self.assertRaises(Book.DoesNotExist, Book.objects.using('other').get, title="Dive into Python" ) def test_other_creation(self): "Objects created on another database don't leak onto the default database" # Create a book on the second database Book.objects.using('other').create(title="Pro Django", published=datetime.date(2008, 12, 16)) # Create a book on the default database using a save dive = Book() dive.title="Dive into Python" dive.published = datetime.date(2009, 5, 4) dive.save(using='other') # Check that book exists on the default database, but not on other database try: Book.objects.using('other').get(title="Pro Django") except Book.DoesNotExist: self.fail('"Dive Into Python" should exist on other database') self.assertRaises(Book.DoesNotExist, Book.objects.get, title="Pro Django" ) self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title="Pro Django" ) try: Book.objects.using('other').get(title="Dive into Python") except Book.DoesNotExist: self.fail('"Dive into Python" should exist on other database') self.assertRaises(Book.DoesNotExist, Book.objects.get, title="Dive into Python" ) self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title="Dive into Python" ) def test_basic_queries(self): "Queries are constrained to a single database" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4)) self.assertEqual(dive.title, "Dive into Python") self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published=datetime.date(2009, 5, 4)) dive = Book.objects.using('other').get(title__icontains="dive") self.assertEqual(dive.title, "Dive into Python") self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__icontains="dive") dive = Book.objects.using('other').get(title__iexact="dive INTO python") self.assertEqual(dive.title, "Dive into Python") self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__iexact="dive INTO python") dive = Book.objects.using('other').get(published__year=2009) self.assertEqual(dive.title, "Dive into Python") self.assertEqual(dive.published, datetime.date(2009, 5, 4)) self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published__year=2009) years = Book.objects.using('other').dates('published', 'year') self.assertEqual([o.year for o in years], [2009]) years = Book.objects.using('default').dates('published', 'year') self.assertEqual([o.year for o in years], []) months = Book.objects.using('other').dates('published', 'month') self.assertEqual([o.month for o in months], [5]) months = Book.objects.using('default').dates('published', 'month') self.assertEqual([o.month for o in months], []) def test_m2m_separation(self): "M2M fields are constrained to a single database" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Save the author relations pro.authors = [marty] dive.authors = [mark] # Inspect the m2m tables directly. # There should be 1 entry in each database self.assertEqual(Book.authors.through.objects.using('default').count(), 1) self.assertEqual(Book.authors.through.objects.using('other').count(), 1) # Check that queries work across m2m joins self.assertEqual(list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)), [u'Pro Django']) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)), []) self.assertEqual(list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), []) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), [u'Dive into Python']) # Reget the objects to clear caches dive = Book.objects.using('other').get(title="Dive into Python") mark = Person.objects.using('other').get(name="Mark Pilgrim") # Retrive related object by descriptor. Related objects should be database-baound self.assertEqual(list(dive.authors.all().values_list('name', flat=True)), [u'Mark Pilgrim']) self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)), [u'Dive into Python']) def test_m2m_forward_operations(self): "M2M forward manipulations are all constrained to a single DB" # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Save the author relations dive.authors = [mark] # Add a second author john = Person.objects.using('other').create(name="John Smith") self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), []) dive.authors.add(john) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), [u'Dive into Python']) self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), [u'Dive into Python']) # Remove the second author dive.authors.remove(john) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), [u'Dive into Python']) self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), []) # Clear all authors dive.authors.clear() self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), []) self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), []) # Create an author through the m2m interface dive.authors.create(name='Jane Brown') self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), []) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)), [u'Dive into Python']) def test_m2m_reverse_operations(self): "M2M reverse manipulations are all constrained to a single DB" # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Save the author relations dive.authors = [mark] # Create a second book on the other database grease = Book.objects.using('other').create(title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1)) # Add a books to the m2m mark.book_set.add(grease) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), [u'Mark Pilgrim']) self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), [u'Mark Pilgrim']) # Remove a book from the m2m mark.book_set.remove(grease) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), [u'Mark Pilgrim']) self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), []) # Clear the books associated with mark mark.book_set.clear() self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), []) self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), []) # Create a book through the m2m interface mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1)) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), []) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)), [u'Mark Pilgrim']) def test_m2m_cross_database_protection(self): "Operations that involve sharing M2M objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key set with an object from a different database try: marty.book_set = [pro, dive] self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to an m2m with an object from a different database try: marty.book_set.add(dive) self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Set a m2m with an object from a different database try: marty.book_set = [pro, dive] self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to a reverse m2m with an object from a different database try: dive.authors.add(marty) self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Set a reverse m2m with an object from a different database try: dive.authors = [mark, marty] self.fail("Shouldn't be able to assign across databases") except ValueError: pass def test_m2m_deletion(self): "Cascaded deletions of m2m relations issue queries on the right database" # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") dive.authors = [mark] # Check the initial state self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Book.authors.through.objects.using('default').count(), 0) self.assertEqual(Person.objects.using('other').count(), 1) self.assertEqual(Book.objects.using('other').count(), 1) self.assertEqual(Book.authors.through.objects.using('other').count(), 1) # Delete the object on the other database dive.delete(using='other') self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Book.authors.through.objects.using('default').count(), 0) # The person still exists ... self.assertEqual(Person.objects.using('other').count(), 1) # ... but the book has been deleted self.assertEqual(Book.objects.using('other').count(), 0) # ... and the relationship object has also been deleted. self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Now try deletion in the reverse direction. Set up the relation again dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) dive.authors = [mark] # Check the initial state self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Book.authors.through.objects.using('default').count(), 0) self.assertEqual(Person.objects.using('other').count(), 1) self.assertEqual(Book.objects.using('other').count(), 1) self.assertEqual(Book.authors.through.objects.using('other').count(), 1) # Delete the object on the other database mark.delete(using='other') self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Book.authors.through.objects.using('default').count(), 0) # The person has been deleted ... self.assertEqual(Person.objects.using('other').count(), 0) # ... but the book still exists self.assertEqual(Book.objects.using('other').count(), 1) # ... and the relationship object has been deleted. self.assertEqual(Book.authors.through.objects.using('other').count(), 0) def test_foreign_key_separation(self): "FK fields are constrained to a single database" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") george = Person.objects.create(name="George Vilches") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") chris = Person.objects.using('other').create(name="Chris Mills") # Save the author's favourite books pro.editor = george pro.save() dive.editor = chris dive.save() pro = Book.objects.using('default').get(title="Pro Django") self.assertEqual(pro.editor.name, "George Vilches") dive = Book.objects.using('other').get(title="Dive into Python") self.assertEqual(dive.editor.name, "Chris Mills") # Check that queries work across foreign key joins self.assertEqual(list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)), [u'George Vilches']) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)), []) self.assertEqual(list(Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)), []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), [u'Chris Mills']) # Reget the objects to clear caches chris = Person.objects.using('other').get(name="Chris Mills") dive = Book.objects.using('other').get(title="Dive into Python") # Retrive related object by descriptor. Related objects should be database-baound self.assertEqual(list(chris.edited.values_list('title', flat=True)), [u'Dive into Python']) def test_foreign_key_reverse_operations(self): "FK reverse manipulations are all constrained to a single DB" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") chris = Person.objects.using('other').create(name="Chris Mills") # Save the author relations dive.editor = chris dive.save() # Add a second book edited by chris html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), []) chris.edited.add(html5) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), [u'Chris Mills']) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), [u'Chris Mills']) # Remove the second editor chris.edited.remove(html5) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), [u'Chris Mills']) # Clear all edited books chris.edited.clear() self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), []) # Create an author through the m2m interface chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15)) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)), [u'Chris Mills']) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), []) def test_foreign_key_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key with an object from a different database try: dive.editor = marty self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Set a foreign key set with an object from a different database try: marty.edited = [pro, dive] self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to a foreign key set with an object from a different database try: marty.edited.add(dive) self.fail("Shouldn't be able to assign across databases") except ValueError: pass # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. chris = Person(name="Chris Mills") html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) # initially, no db assigned self.assertEqual(chris._state.db, None) self.assertEqual(html5._state.db, None) # old object comes from 'other', so the new object is set to use 'other'... dive.editor = chris html5.editor = mark self.assertEqual(chris._state.db, 'other') self.assertEqual(html5._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)), [u'Mark Pilgrim']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into Python']) # When saved (no using required), new objects goes to 'other' chris.save() html5.save() self.assertEqual(list(Person.objects.using('default').values_list('name',flat=True)), [u'Marty Alchin']) self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)), [u'Chris Mills', u'Mark Pilgrim']) self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), [u'Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into HTML5', u'Dive into Python']) # This also works if you assign the FK in the constructor water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark) self.assertEqual(water._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), [u'Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into HTML5', u'Dive into Python']) # When saved, the new book goes to 'other' water.save() self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), [u'Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title',flat=True)), [u'Dive into HTML5', u'Dive into Python', u'Dive into Water']) def test_foreign_key_deletion(self): "Cascaded deletions of Foreign Key relations issue queries on the right database" mark = Person.objects.using('other').create(name="Mark Pilgrim") fido = Pet.objects.using('other').create(name="Fido", owner=mark) # Check the initial state self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Pet.objects.using('default').count(), 0) self.assertEqual(Person.objects.using('other').count(), 1) self.assertEqual(Pet.objects.using('other').count(), 1) # Delete the person object, which will cascade onto the pet mark.delete(using='other') self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Pet.objects.using('default').count(), 0) # Both the pet and the person have been deleted from the right database self.assertEqual(Person.objects.using('other').count(), 0) self.assertEqual(Pet.objects.using('other').count(), 0) def test_foreign_key_validation(self): "ForeignKey.validate() uses the correct database" mickey = Person.objects.using('other').create(name="Mickey") pluto = Pet.objects.using('other').create(name="Pluto", owner=mickey) self.assertEqual(None, pluto.full_clean()) def test_o2o_separation(self): "OneToOne fields are constrained to a single database" # Create a user and profile on the default database alice = User.objects.db_manager('default').create_user('alice', '[email protected]') alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate') # Create a user and profile on the other database bob = User.objects.db_manager('other').create_user('bob', '[email protected]') bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog') # Retrieve related objects; queries should be database constrained alice = User.objects.using('default').get(username="alice") self.assertEqual(alice.userprofile.flavor, "chocolate") bob = User.objects.using('other').get(username="bob") self.assertEqual(bob.userprofile.flavor, "crunchy frog") # Check that queries work across joins self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='chocolate').values_list('username', flat=True)), [u'alice']) self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='chocolate').values_list('username', flat=True)), []) self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)), []) self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)), [u'bob']) # Reget the objects to clear caches alice_profile = UserProfile.objects.using('default').get(flavor='chocolate') bob_profile = UserProfile.objects.using('other').get(flavor='crunchy frog') # Retrive related object by descriptor. Related objects should be database-baound self.assertEqual(alice_profile.user.username, 'alice') self.assertEqual(bob_profile.user.username, 'bob') def test_o2o_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a user and profile on the default database alice = User.objects.db_manager('default').create_user('alice', '[email protected]') # Create a user and profile on the other database bob = User.objects.db_manager('other').create_user('bob', '[email protected]') # Set a one-to-one relation with an object from a different database alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate') try: bob.userprofile = alice_profile self.fail("Shouldn't be able to assign across databases") except ValueError: pass # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog') new_bob_profile = UserProfile(flavor="spring surprise") charlie = User(username='charlie',email='[email protected]') charlie.set_unusable_password() # initially, no db assigned self.assertEqual(new_bob_profile._state.db, None) self.assertEqual(charlie._state.db, None) # old object comes from 'other', so the new object is set to use 'other'... new_bob_profile.user = bob charlie.userprofile = bob_profile self.assertEqual(new_bob_profile._state.db, 'other') self.assertEqual(charlie._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)), [u'bob']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog']) # When saved (no using required), new objects goes to 'other' charlie.save() bob_profile.save() new_bob_profile.save() self.assertEqual(list(User.objects.using('default').values_list('username',flat=True)), [u'alice']) self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)), [u'bob', u'charlie']) self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), [u'chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog', u'spring surprise']) # This also works if you assign the O2O relation in the constructor denise = User.objects.db_manager('other').create_user('denise','[email protected]') denise_profile = UserProfile(flavor="tofu", user=denise) self.assertEqual(denise_profile._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), [u'chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog', u'spring surprise']) # When saved, the new profile goes to 'other' denise_profile.save() self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), [u'chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)), [u'crunchy frog', u'spring surprise', u'tofu']) def test_generic_key_separation(self): "Generic fields are constrained to a single database" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source="Python Monthly", content_object=pro) # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) review1 = Review.objects.using('default').get(source="Python Monthly") self.assertEqual(review1.content_object.title, "Pro Django") review2 = Review.objects.using('other').get(source="Python Weekly") self.assertEqual(review2.content_object.title, "Dive into Python") # Reget the objects to clear caches dive = Book.objects.using('other').get(title="Dive into Python") # Retrive related object by descriptor. Related objects should be database-bound self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)), [u'Python Weekly']) def test_generic_key_reverse_operations(self): "Generic reverse manipulations are all constrained to a single DB" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) temp = Book.objects.using('other').create(title="Temp", published=datetime.date(2009, 5, 4)) review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp) self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), [u'Python Weekly']) # Add a second review dive.reviews.add(review2) self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), [u'Python Monthly', u'Python Weekly']) # Remove the second author dive.reviews.remove(review1) self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), [u'Python Monthly']) # Clear all reviews dive.reviews.clear() self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), []) # Create an author through the generic interface dive.reviews.create(source='Python Daily') self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), [u'Python Daily']) def test_generic_key_cross_database_protection(self): "Operations that involve sharing generic key objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source="Python Monthly", content_object=pro) # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) # Set a foreign key with an object from a different database try: review1.content_object = dive self.fail("Shouldn't be able to assign across databases") except ValueError: pass # Add to a foreign key set with an object from a different database try: dive.reviews.add(review1) self.fail("Shouldn't be able to assign across databases") except ValueError: pass # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. review3 = Review(source="Python Daily") # initially, no db assigned self.assertEqual(review3._state.db, None) # Dive comes from 'other', so review3 is set to use 'other'... review3.content_object = dive self.assertEqual(review3._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), [u'Python Monthly']) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)), [u'Python Weekly']) # When saved, John goes to 'other' review3.save() self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), [u'Python Monthly']) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source',flat=True)), [u'Python Daily', u'Python Weekly']) def test_generic_key_deletion(self): "Cascaded deletions of Generic Key relations issue queries on the right database" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) review = Review.objects.using('other').create(source="Python Weekly", content_object=dive) # Check the initial state self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Review.objects.using('default').count(), 0) self.assertEqual(Book.objects.using('other').count(), 1) self.assertEqual(Review.objects.using('other').count(), 1) # Delete the Book object, which will cascade onto the pet dive.delete(using='other') self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Review.objects.using('default').count(), 0) # Both the pet and the person have been deleted from the right database self.assertEqual(Book.objects.using('other').count(), 0) self.assertEqual(Review.objects.using('other').count(), 0) def test_ordering(self): "get_next_by_XXX commands stick to a single database" pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) learn = Book.objects.using('other').create(title="Learning Python", published=datetime.date(2008, 7, 16)) self.assertEqual(learn.get_next_by_published().title, "Dive into Python") self.assertEqual(dive.get_previous_by_published().title, "Learning Python") def test_raw(self): "test the raw() method across databases" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book') self.assertEqual(map(lambda o: o.pk, val), [dive.pk]) val = Book.objects.raw('SELECT id FROM multiple_database_book').using('other') self.assertEqual(map(lambda o: o.pk, val), [dive.pk]) def test_select_related(self): "Database assignment is retained if an object is retrieved with select_related()" # Create a book and author on the other database mark = Person.objects.using('other').create(name="Mark Pilgrim") dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4), editor=mark) # Retrieve the Person using select_related() book = Book.objects.using('other').select_related('editor').get(title="Dive into Python") # The editor instance should have a db state self.assertEqual(book.editor._state.db, 'other') def test_subquery(self): """Make sure as_sql works with subqueries and master/slave.""" sub = Person.objects.using('other').filter(name='fff') qs = Book.objects.filter(editor__in=sub) # When you call __str__ on the query object, it doesn't know about using # so it falls back to the default. If the subquery explicitly uses a # different database, an error should be raised. self.assertRaises(ValueError, str, qs.query) # Evaluating the query shouldn't work, either try: for obj in qs: pass self.fail('Iterating over query should raise ValueError') except ValueError: pass def test_related_manager(self): "Related managers return managers, not querysets" mark = Person.objects.using('other').create(name="Mark Pilgrim") # extra_arg is removed by the BookManager's implementation of # create(); but the BookManager's implementation won't get called # unless edited returns a Manager, not a queryset mark.book_set.create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True) mark.book_set.get_or_create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True) mark.edited.create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True) mark.edited.get_or_create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True) class TestRouter(object): # A test router. The behaviour is vaguely master/slave, but the # databases aren't assumed to propagate changes. def db_for_read(self, model, instance=None, **hints): if instance: return instance._state.db or 'other' return 'other' def db_for_write(self, model, **hints): return DEFAULT_DB_ALIAS def allow_relation(self, obj1, obj2, **hints): return obj1._state.db in ('default', 'other') and obj2._state.db in ('default', 'other') def allow_syncdb(self, db, model): return True class AuthRouter(object): """A router to control all database operations on models in the contrib.auth application""" def db_for_read(self, model, **hints): "Point all read operations on auth models to 'default'" if model._meta.app_label == 'auth': # We use default here to ensure we can tell the difference # between a read request and a write request for Auth objects return 'default' return None def db_for_write(self, model, **hints): "Point all operations on auth models to 'other'" if model._meta.app_label == 'auth': return 'other' return None def allow_relation(self, obj1, obj2, **hints): "Allow any relation if a model in Auth is involved" if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth': return True return None def allow_syncdb(self, db, model): "Make sure the auth app only appears on the 'other' db" if db == 'other': return model._meta.app_label == 'auth' elif model._meta.app_label == 'auth': return False return None class WriteRouter(object): # A router that only expresses an opinion on writes def db_for_write(self, model, **hints): return 'writer' class RouterTestCase(TestCase): multi_db = True def setUp(self): # Make the 'other' database appear to be a slave of the 'default' self.old_routers = router.routers router.routers = [TestRouter()] def tearDown(self): # Restore the 'other' database as an independent database router.routers = self.old_routers def test_db_selection(self): "Check that querysets obey the router for db suggestions" self.assertEqual(Book.objects.db, 'other') self.assertEqual(Book.objects.all().db, 'other') self.assertEqual(Book.objects.using('default').db, 'default') self.assertEqual(Book.objects.db_manager('default').db, 'default') self.assertEqual(Book.objects.db_manager('default').all().db, 'default') def test_syncdb_selection(self): "Synchronization behaviour is predicatable" self.assertTrue(router.allow_syncdb('default', User)) self.assertTrue(router.allow_syncdb('default', Book)) self.assertTrue(router.allow_syncdb('other', User)) self.assertTrue(router.allow_syncdb('other', Book)) # Add the auth router to the chain. # TestRouter is a universal synchronizer, so it should have no effect. router.routers = [TestRouter(), AuthRouter()] self.assertTrue(router.allow_syncdb('default', User)) self.assertTrue(router.allow_syncdb('default', Book)) self.assertTrue(router.allow_syncdb('other', User)) self.assertTrue(router.allow_syncdb('other', Book)) # Now check what happens if the router order is the other way around router.routers = [AuthRouter(), TestRouter()] self.assertFalse(router.allow_syncdb('default', User)) self.assertTrue(router.allow_syncdb('default', Book)) self.assertTrue(router.allow_syncdb('other', User)) self.assertFalse(router.allow_syncdb('other', Book)) def test_partial_router(self): "A router can choose to implement a subset of methods" dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) # First check the baseline behaviour self.assertEqual(router.db_for_read(User), 'other') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'default') self.assertEqual(router.db_for_write(Book), 'default') self.assertTrue(router.allow_relation(dive, dive)) self.assertTrue(router.allow_syncdb('default', User)) self.assertTrue(router.allow_syncdb('default', Book)) router.routers = [WriteRouter(), AuthRouter(), TestRouter()] self.assertEqual(router.db_for_read(User), 'default') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'writer') self.assertEqual(router.db_for_write(Book), 'writer') self.assertTrue(router.allow_relation(dive, dive)) self.assertFalse(router.allow_syncdb('default', User)) self.assertTrue(router.allow_syncdb('default', Book)) def test_database_routing(self): marty = Person.objects.using('default').create(name="Marty Alchin") pro = Book.objects.using('default').create(title="Pro Django", published=datetime.date(2008, 12, 16), editor=marty) pro.authors = [marty] # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) # An update query will be routed to the default database Book.objects.filter(title='Pro Django').update(pages=200) try: # By default, the get query will be directed to 'other' Book.objects.get(title='Pro Django') self.fail("Shouldn't be able to find the book") except Book.DoesNotExist: pass # But the same query issued explicitly at a database will work. pro = Book.objects.using('default').get(title='Pro Django') # Check that the update worked. self.assertEqual(pro.pages, 200) # An update query with an explicit using clause will be routed # to the requested database. Book.objects.using('other').filter(title='Dive into Python').update(pages=300) self.assertEqual(Book.objects.get(title='Dive into Python').pages, 300) # Related object queries stick to the same database # as the original object, regardless of the router self.assertEqual(list(pro.authors.values_list('name', flat=True)), [u'Marty Alchin']) self.assertEqual(pro.editor.name, u'Marty Alchin') # get_or_create is a special case. The get needs to be targetted at # the write database in order to avoid potential transaction # consistency problems book, created = Book.objects.get_or_create(title="Pro Django") self.assertFalse(created) book, created = Book.objects.get_or_create(title="Dive Into Python", defaults={'published':datetime.date(2009, 5, 4)}) self.assertTrue(created) # Check the head count of objects self.assertEqual(Book.objects.using('default').count(), 2) self.assertEqual(Book.objects.using('other').count(), 1) # If a database isn't specified, the read database is used self.assertEqual(Book.objects.count(), 1) # A delete query will also be routed to the default database Book.objects.filter(pages__gt=150).delete() # The default database has lost the book. self.assertEqual(Book.objects.using('default').count(), 1) self.assertEqual(Book.objects.using('other').count(), 1) def test_foreign_key_cross_database_protection(self): "Foreign keys can cross databases if they two databases have a common source" # Create a book and author on the default database pro = Book.objects.using('default').create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.using('default').create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key with an object from a different database try: dive.editor = marty except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # ... but they will when the affected object is saved. dive.save() self.assertEqual(dive._state.db, 'default') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') self.assertEqual(dive._state.db, 'other') # Set a foreign key set with an object from a different database try: marty.edited = [pro, dive] except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Assignment implies a save, so database assignments of original objects have changed... self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'default') self.assertEqual(mark._state.db, 'other') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') self.assertEqual(dive._state.db, 'other') # Add to a foreign key set with an object from a different database try: marty.edited.add(dive) except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Add implies a save, so database assignments of original objects have changed... self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'default') self.assertEqual(mark._state.db, 'other') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') # If you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. chris = Person(name="Chris Mills") html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) # initially, no db assigned self.assertEqual(chris._state.db, None) self.assertEqual(html5._state.db, None) # old object comes from 'other', so the new object is set to use the # source of 'other'... self.assertEqual(dive._state.db, 'other') dive.editor = chris html5.editor = mark self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') self.assertEqual(chris._state.db, 'default') self.assertEqual(html5._state.db, 'default') # This also works if you assign the FK in the constructor water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark) self.assertEqual(water._state.db, 'default') # If you create an object through a FK relation, it will be # written to the write database, even if the original object # was on the read database cheesecake = mark.edited.create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15)) self.assertEqual(cheesecake._state.db, 'default') # Same goes for get_or_create, regardless of whether getting or creating cheesecake, created = mark.edited.get_or_create(title='Dive into Cheesecake', published=datetime.date(2010, 3, 15)) self.assertEqual(cheesecake._state.db, 'default') puddles, created = mark.edited.get_or_create(title='Dive into Puddles', published=datetime.date(2010, 3, 15)) self.assertEqual(puddles._state.db, 'default') def test_m2m_cross_database_protection(self): "M2M relations can cross databases if the database share a source" # Create books and authors on the inverse to the usual database pro = Book.objects.using('other').create(pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.using('other').create(pk=1, name="Marty Alchin") dive = Book.objects.using('default').create(pk=2, title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('default').create(pk=2, name="Mark Pilgrim") # Now save back onto the usual database. # This simulates master/slave - the objects exist on both database, # but the _state.db is as it is for all other tests. pro.save(using='default') marty.save(using='default') dive.save(using='other') mark.save(using='other') # Check that we have 2 of both types of object on both databases self.assertEqual(Book.objects.using('default').count(), 2) self.assertEqual(Book.objects.using('other').count(), 2) self.assertEqual(Person.objects.using('default').count(), 2) self.assertEqual(Person.objects.using('other').count(), 2) # Set a m2m set with an object from a different database try: marty.book_set = [pro, dive] except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 2) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Reset relations Book.authors.through.objects.using('default').delete() # Add to an m2m with an object from a different database try: marty.book_set.add(dive) except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 1) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Reset relations Book.authors.through.objects.using('default').delete() # Set a reverse m2m with an object from a different database try: dive.authors = [mark, marty] except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 2) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Reset relations Book.authors.through.objects.using('default').delete() self.assertEqual(Book.authors.through.objects.using('default').count(), 0) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Add to a reverse m2m with an object from a different database try: dive.authors.add(marty) except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments don't change self.assertEqual(marty._state.db, 'default') self.assertEqual(pro._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(mark._state.db, 'other') # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using('default').count(), 1) self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # If you create an object through a M2M relation, it will be # written to the write database, even if the original object # was on the read database alice = dive.authors.create(name='Alice') self.assertEqual(alice._state.db, 'default') # Same goes for get_or_create, regardless of whether getting or creating alice, created = dive.authors.get_or_create(name='Alice') self.assertEqual(alice._state.db, 'default') bob, created = dive.authors.get_or_create(name='Bob') self.assertEqual(bob._state.db, 'default') def test_o2o_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a user and profile on the default database alice = User.objects.db_manager('default').create_user('alice', '[email protected]') # Create a user and profile on the other database bob = User.objects.db_manager('other').create_user('bob', '[email protected]') # Set a one-to-one relation with an object from a different database alice_profile = UserProfile.objects.create(user=alice, flavor='chocolate') try: bob.userprofile = alice_profile except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(alice._state.db, 'default') self.assertEqual(alice_profile._state.db, 'default') self.assertEqual(bob._state.db, 'other') # ... but they will when the affected object is saved. bob.save() self.assertEqual(bob._state.db, 'default') def test_generic_key_cross_database_protection(self): "Generic Key operations can span databases if they share a source" # Create a book and author on the default database pro = Book.objects.using('default' ).create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.using('default' ).create(source="Python Monthly", content_object=pro) # Create a book and author on the other database dive = Book.objects.using('other' ).create(title="Dive into Python", published=datetime.date(2009, 5, 4)) review2 = Review.objects.using('other' ).create(source="Python Weekly", content_object=dive) # Set a generic foreign key with an object from a different database try: review1.content_object = dive except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(pro._state.db, 'default') self.assertEqual(review1._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(review2._state.db, 'other') # ... but they will when the affected object is saved. dive.save() self.assertEqual(review1._state.db, 'default') self.assertEqual(dive._state.db, 'default') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # This isn't a real master-slave database, so restore the original from other dive = Book.objects.using('other').get(title='Dive into Python') self.assertEqual(dive._state.db, 'other') # Add to a generic foreign key set with an object from a different database try: dive.reviews.add(review1) except ValueError: self.fail("Assignment across master/slave databases with a common source should be ok") # Database assignments of original objects haven't changed... self.assertEqual(pro._state.db, 'default') self.assertEqual(review1._state.db, 'default') self.assertEqual(dive._state.db, 'other') self.assertEqual(review2._state.db, 'other') # ... but they will when the affected object is saved. dive.save() self.assertEqual(dive._state.db, 'default') # ...and the source database now has a copy of any object saved try: Book.objects.using('default').get(title='Dive into Python').delete() except Book.DoesNotExist: self.fail('Source database should have a copy of saved object') # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. review3 = Review(source="Python Daily") # initially, no db assigned self.assertEqual(review3._state.db, None) # Dive comes from 'other', so review3 is set to use the source of 'other'... review3.content_object = dive self.assertEqual(review3._state.db, 'default') # If you create an object through a M2M relation, it will be # written to the write database, even if the original object # was on the read database dive = Book.objects.using('other').get(title='Dive into Python') nyt = dive.reviews.create(source="New York Times", content_object=dive) self.assertEqual(nyt._state.db, 'default') def test_m2m_managers(self): "M2M relations are represented by managers, and can be controlled like managers" pro = Book.objects.using('other').create(pk=1, title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.using('other').create(pk=1, name="Marty Alchin") pro.authors = [marty] self.assertEqual(pro.authors.db, 'other') self.assertEqual(pro.authors.db_manager('default').db, 'default') self.assertEqual(pro.authors.db_manager('default').all().db, 'default') self.assertEqual(marty.book_set.db, 'other') self.assertEqual(marty.book_set.db_manager('default').db, 'default') self.assertEqual(marty.book_set.db_manager('default').all().db, 'default') def test_foreign_key_managers(self): "FK reverse relations are represented by managers, and can be controlled like managers" marty = Person.objects.using('other').create(pk=1, name="Marty Alchin") pro = Book.objects.using('other').create(pk=1, title="Pro Django", published=datetime.date(2008, 12, 16), editor=marty) self.assertEqual(marty.edited.db, 'other') self.assertEqual(marty.edited.db_manager('default').db, 'default') self.assertEqual(marty.edited.db_manager('default').all().db, 'default') def test_generic_key_managers(self): "Generic key relations are represented by managers, and can be controlled like managers" pro = Book.objects.using('other').create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.using('other').create(source="Python Monthly", content_object=pro) self.assertEqual(pro.reviews.db, 'other') self.assertEqual(pro.reviews.db_manager('default').db, 'default') self.assertEqual(pro.reviews.db_manager('default').all().db, 'default') def test_subquery(self): """Make sure as_sql works with subqueries and master/slave.""" # Create a book and author on the other database mark = Person.objects.using('other').create(name="Mark Pilgrim") dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4), editor=mark) sub = Person.objects.filter(name='Mark Pilgrim') qs = Book.objects.filter(editor__in=sub) # When you call __str__ on the query object, it doesn't know about using # so it falls back to the default. Don't let routing instructions # force the subquery to an incompatible database. str(qs.query) # If you evaluate the query, it should work, running on 'other' self.assertEqual(list(qs.values_list('title', flat=True)), [u'Dive into Python']) class AuthTestCase(TestCase): multi_db = True def setUp(self): # Make the 'other' database appear to be a slave of the 'default' self.old_routers = router.routers router.routers = [AuthRouter()] def tearDown(self): # Restore the 'other' database as an independent database router.routers = self.old_routers def test_auth_manager(self): "The methods on the auth manager obey database hints" # Create one user using default allocation policy User.objects.create_user('alice', '[email protected]') # Create another user, explicitly specifying the database User.objects.db_manager('default').create_user('bob', '[email protected]') # The second user only exists on the other database alice = User.objects.using('other').get(username='alice') self.assertEqual(alice.username, 'alice') self.assertEqual(alice._state.db, 'other') self.assertRaises(User.DoesNotExist, User.objects.using('default').get, username='alice') # The second user only exists on the default database bob = User.objects.using('default').get(username='bob') self.assertEqual(bob.username, 'bob') self.assertEqual(bob._state.db, 'default') self.assertRaises(User.DoesNotExist, User.objects.using('other').get, username='bob') # That is... there is one user on each database self.assertEqual(User.objects.using('default').count(), 1) self.assertEqual(User.objects.using('other').count(), 1) def test_dumpdata(self): "Check that dumpdata honors allow_syncdb restrictions on the router" User.objects.create_user('alice', '[email protected]') User.objects.db_manager('default').create_user('bob', '[email protected]') # Check that dumping the default database doesn't try to include auth # because allow_syncdb prohibits auth on default new_io = StringIO() management.call_command('dumpdata', 'auth', format='json', database='default', stdout=new_io) command_output = new_io.getvalue().strip() self.assertEqual(command_output, '[]') # Check that dumping the other database does include auth new_io = StringIO() management.call_command('dumpdata', 'auth', format='json', database='other', stdout=new_io) command_output = new_io.getvalue().strip() self.assertTrue('"email": "[email protected]",' in command_output) _missing = object() class UserProfileTestCase(TestCase): def setUp(self): self.old_auth_profile_module = getattr(settings, 'AUTH_PROFILE_MODULE', _missing) settings.AUTH_PROFILE_MODULE = 'multiple_database.UserProfile' def tearDown(self): if self.old_auth_profile_module is _missing: del settings.AUTH_PROFILE_MODULE else: settings.AUTH_PROFILE_MODULE = self.old_auth_profile_module def test_user_profiles(self): alice = User.objects.create_user('alice', '[email protected]') bob = User.objects.db_manager('other').create_user('bob', '[email protected]') alice_profile = UserProfile(user=alice, flavor='chocolate') alice_profile.save() bob_profile = UserProfile(user=bob, flavor='crunchy frog') bob_profile.save() self.assertEqual(alice.get_profile().flavor, 'chocolate') self.assertEqual(bob.get_profile().flavor, 'crunchy frog') class AntiPetRouter(object): # A router that only expresses an opinion on syncdb, # passing pets to the 'other' database def allow_syncdb(self, db, model): "Make sure the auth app only appears on the 'other' db" if db == 'other': return model._meta.object_name == 'Pet' else: return model._meta.object_name != 'Pet' return None class FixtureTestCase(TestCase): multi_db = True fixtures = ['multidb-common', 'multidb'] def setUp(self): # Install the anti-pet router self.old_routers = router.routers router.routers = [AntiPetRouter()] def tearDown(self): # Restore the 'other' database as an independent database router.routers = self.old_routers def test_fixture_loading(self): "Multi-db fixtures are loaded correctly" # Check that "Pro Django" exists on the default database, but not on other database try: Book.objects.get(title="Pro Django") Book.objects.using('default').get(title="Pro Django") except Book.DoesNotExist: self.fail('"Pro Django" should exist on default database') self.assertRaises(Book.DoesNotExist, Book.objects.using('other').get, title="Pro Django" ) # Check that "Dive into Python" exists on the default database, but not on other database try: Book.objects.using('other').get(title="Dive into Python") except Book.DoesNotExist: self.fail('"Dive into Python" should exist on other database') self.assertRaises(Book.DoesNotExist, Book.objects.get, title="Dive into Python" ) self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title="Dive into Python" ) # Check that "Definitive Guide" exists on the both databases try: Book.objects.get(title="The Definitive Guide to Django") Book.objects.using('default').get(title="The Definitive Guide to Django") Book.objects.using('other').get(title="The Definitive Guide to Django") except Book.DoesNotExist: self.fail('"The Definitive Guide to Django" should exist on both databases') def test_pseudo_empty_fixtures(self): "A fixture can contain entries, but lead to nothing in the database; this shouldn't raise an error (ref #14068)" new_io = StringIO() management.call_command('loaddata', 'pets', stdout=new_io, stderr=new_io) command_output = new_io.getvalue().strip() # No objects will actually be loaded self.assertEqual(command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)") class PickleQuerySetTestCase(TestCase): multi_db = True def test_pickling(self): for db in connections: Book.objects.using(db).create(title='Dive into Python', published=datetime.date(2009, 5, 4)) qs = Book.objects.all() self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db) class DatabaseReceiver(object): """ Used in the tests for the database argument in signals (#13552) """ def __call__(self, signal, sender, **kwargs): self._database = kwargs['using'] class WriteToOtherRouter(object): """ A router that sends all writes to the other database. """ def db_for_write(self, model, **hints): return "other" class SignalTests(TestCase): multi_db = True def setUp(self): self.old_routers = router.routers def tearDown(self): router.routser = self.old_routers def _write_to_other(self): "Sends all writes to 'other'." router.routers = [WriteToOtherRouter()] def _write_to_default(self): "Sends all writes to the default DB" router.routers = self.old_routers def test_database_arg_save_and_delete(self): """ Tests that the pre/post_save signal contains the correct database. (#13552) """ # Make some signal receivers pre_save_receiver = DatabaseReceiver() post_save_receiver = DatabaseReceiver() pre_delete_receiver = DatabaseReceiver() post_delete_receiver = DatabaseReceiver() # Make model and connect receivers signals.pre_save.connect(sender=Person, receiver=pre_save_receiver) signals.post_save.connect(sender=Person, receiver=post_save_receiver) signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver) signals.post_delete.connect(sender=Person, receiver=post_delete_receiver) p = Person.objects.create(name='Darth Vader') # Save and test receivers got calls p.save() self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS) self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS) # Delete, and test p.delete() self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS) self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS) # Save again to a different database p.save(using="other") self.assertEqual(pre_save_receiver._database, "other") self.assertEqual(post_save_receiver._database, "other") # Delete, and test p.delete(using="other") self.assertEqual(pre_delete_receiver._database, "other") self.assertEqual(post_delete_receiver._database, "other") def test_database_arg_m2m(self): """ Test that the m2m_changed signal has a correct database arg (#13552) """ # Make a receiver receiver = DatabaseReceiver() # Connect it, and make the models signals.m2m_changed.connect(receiver=receiver) b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) p = Person.objects.create(name="Marty Alchin") # Test addition b.authors.add(p) self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) self._write_to_other() b.authors.add(p) self._write_to_default() self.assertEqual(receiver._database, "other") # Test removal b.authors.remove(p) self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) self._write_to_other() b.authors.remove(p) self._write_to_default() self.assertEqual(receiver._database, "other") # Test addition in reverse p.book_set.add(b) self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) self._write_to_other() p.book_set.add(b) self._write_to_default() self.assertEqual(receiver._database, "other") # Test clearing b.authors.clear() self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) self._write_to_other() b.authors.clear() self._write_to_default() self.assertEqual(receiver._database, "other") class AttributeErrorRouter(object): "A router to test the exception handling of ConnectionRouter" def db_for_read(self, model, **hints): raise AttributeError def db_for_write(self, model, **hints): raise AttributeError class RouterAttributeErrorTestCase(TestCase): multi_db = True def setUp(self): self.old_routers = router.routers router.routers = [AttributeErrorRouter()] def tearDown(self): router.routers = self.old_routers def test_attribute_error_read(self): "Check that the AttributeError from AttributeErrorRouter bubbles up" router.routers = [] # Reset routers so we can save a Book instance b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) router.routers = [AttributeErrorRouter()] # Install our router self.assertRaises(AttributeError, Book.objects.get, pk=b.pk) def test_attribute_error_save(self): "Check that the AttributeError from AttributeErrorRouter bubbles up" dive = Book() dive.title="Dive into Python" dive.published = datetime.date(2009, 5, 4) self.assertRaises(AttributeError, dive.save) def test_attribute_error_delete(self): "Check that the AttributeError from AttributeErrorRouter bubbles up" router.routers = [] # Reset routers so we can save our Book, Person instances b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) p = Person.objects.create(name="Marty Alchin") b.authors = [p] b.editor = p router.routers = [AttributeErrorRouter()] # Install our router self.assertRaises(AttributeError, b.delete) def test_attribute_error_m2m(self): "Check that the AttributeError from AttributeErrorRouter bubbles up" router.routers = [] # Reset routers so we can save our Book, Person instances b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) p = Person.objects.create(name="Marty Alchin") router.routers = [AttributeErrorRouter()] # Install our router self.assertRaises(AttributeError, setattr, b, 'authors', [p]) class ModelMetaRouter(object): "A router to ensure model arguments are real model classes" def db_for_write(self, model, **hints): if not hasattr(model, '_meta'): raise ValueError class RouterModelArgumentTestCase(TestCase): multi_db = True def setUp(self): self.old_routers = router.routers router.routers = [ModelMetaRouter()] def tearDown(self): router.routers = self.old_routers def test_m2m_collection(self): b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) p = Person.objects.create(name="Marty Alchin") # test add b.authors.add(p) # test remove b.authors.remove(p) # test clear b.authors.clear() # test setattr b.authors = [p] # test M2M collection b.delete() def test_foreignkey_collection(self): person = Person.objects.create(name='Bob') pet = Pet.objects.create(owner=person, name='Wart') # test related FK collection person.delete()
85,975
Python
.py
1,499
45.887925
139
0.633552
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,974
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/expressions_regress/models.py
""" Model for testing arithmetic expressions. """ from django.db import models class Number(models.Model): integer = models.IntegerField(db_column='the_integer') float = models.FloatField(null=True, db_column='the_float') def __unicode__(self): return u'%i, %.3f' % (self.integer, self.float) class Experiment(models.Model): name = models.CharField(max_length=24) assigned = models.DateField() completed = models.DateField() start = models.DateTimeField() end = models.DateTimeField() class Meta: ordering = ('name',) def duration(self): return self.end - self.start
637
Python
.py
19
28.842105
63
0.687908
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,975
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/expressions_regress/tests.py
""" Spanning tests for all the operations that F() expressions can perform. """ import datetime from django.conf import settings from django.db import models, connection from django.db.models import F from django.test import TestCase, Approximate, skipUnlessDBFeature from regressiontests.expressions_regress.models import Number, Experiment class ExpressionsRegressTests(TestCase): def setUp(self): Number(integer=-1).save() Number(integer=42).save() Number(integer=1337).save() self.assertEqual(Number.objects.update(float=F('integer')), 3) def test_fill_with_value_from_same_object(self): """ We can fill a value in all objects with an other value of the same object. """ self.assertQuerysetEqual( Number.objects.all(), [ '<Number: -1, -1.000>', '<Number: 42, 42.000>', '<Number: 1337, 1337.000>' ] ) def test_increment_value(self): """ We can increment a value of all objects in a query set. """ self.assertEqual( Number.objects.filter(integer__gt=0) .update(integer=F('integer') + 1), 2) self.assertQuerysetEqual( Number.objects.all(), [ '<Number: -1, -1.000>', '<Number: 43, 42.000>', '<Number: 1338, 1337.000>' ] ) def test_filter_not_equals_other_field(self): """ We can filter for objects, where a value is not equals the value of an other field. """ self.assertEqual( Number.objects.filter(integer__gt=0) .update(integer=F('integer') + 1), 2) self.assertQuerysetEqual( Number.objects.exclude(float=F('integer')), [ '<Number: 43, 42.000>', '<Number: 1338, 1337.000>' ] ) def test_complex_expressions(self): """ Complex expressions of different connection types are possible. """ n = Number.objects.create(integer=10, float=123.45) self.assertEqual(Number.objects.filter(pk=n.pk) .update(float=F('integer') + F('float') * 2), 1) self.assertEqual(Number.objects.get(pk=n.pk).integer, 10) self.assertEqual(Number.objects.get(pk=n.pk).float, Approximate(256.900, places=3)) class ExpressionOperatorTests(TestCase): def setUp(self): self.n = Number.objects.create(integer=42, float=15.5) def test_lefthand_addition(self): # LH Addition of floats and integers Number.objects.filter(pk=self.n.pk).update( integer=F('integer') + 15, float=F('float') + 42.7 ) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 57) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)) def test_lefthand_subtraction(self): # LH Subtraction of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') - 15, float=F('float') - 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 27) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(-27.200, places=3)) def test_lefthand_multiplication(self): # Multiplication of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') * 15, float=F('float') * 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) def test_lefthand_division(self): # LH Division of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') / 2, float=F('float') / 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 21) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(0.363, places=3)) def test_lefthand_modulo(self): # LH Modulo arithmetic on integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') % 20) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 2) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_lefthand_bitwise_and(self): # LH Bitwise ands on integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') & 56) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 40) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) @skipUnlessDBFeature('supports_bitwise_or') def test_lefthand_bitwise_or(self): # LH Bitwise or on integers Number.objects.filter(pk=self.n.pk).update(integer=F('integer') | 48) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 58) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_right_hand_addition(self): # Right hand operators Number.objects.filter(pk=self.n.pk).update(integer=15 + F('integer'), float=42.7 + F('float')) # RH Addition of floats and integers self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 57) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)) def test_right_hand_subtraction(self): Number.objects.filter(pk=self.n.pk).update(integer=15 - F('integer'), float=42.7 - F('float')) # RH Subtraction of floats and integers self.assertEqual(Number.objects.get(pk=self.n.pk).integer, -27) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(27.200, places=3)) def test_right_hand_multiplication(self): # RH Multiplication of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=15 * F('integer'), float=42.7 * F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) def test_right_hand_division(self): # RH Division of floats and integers Number.objects.filter(pk=self.n.pk).update(integer=640 / F('integer'), float=42.7 / F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 15) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(2.755, places=3)) def test_right_hand_modulo(self): # RH Modulo arithmetic on integers Number.objects.filter(pk=self.n.pk).update(integer=69 % F('integer')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 27) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) def test_right_hand_bitwise_and(self): # RH Bitwise ands on integers Number.objects.filter(pk=self.n.pk).update(integer=15 & F('integer')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 10) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) @skipUnlessDBFeature('supports_bitwise_or') def test_right_hand_bitwise_or(self): # RH Bitwise or on integers Number.objects.filter(pk=self.n.pk).update(integer=15 | F('integer')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 47) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(15.500, places=3)) class FTimeDeltaTests(TestCase): def setUp(self): sday = datetime.date(2010, 6, 25) stime = datetime.datetime(2010, 6, 25, 12, 15, 30, 747000) midnight = datetime.time(0) delta0 = datetime.timedelta(0) delta1 = datetime.timedelta(microseconds=253000) delta2 = datetime.timedelta(seconds=44) delta3 = datetime.timedelta(hours=21, minutes=8) delta4 = datetime.timedelta(days=10) # Test data is set so that deltas and delays will be # strictly increasing. self.deltas = [] self.delays = [] self.days_long = [] # e0: started same day as assigned, zero duration end = stime+delta0 e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime, end=end, completed=end.date()) self.deltas.append(delta0) self.delays.append(e0.start- datetime.datetime.combine(e0.assigned, midnight)) self.days_long.append(e0.completed-e0.assigned) # e1: started one day after assigned, tiny duration, data # set so that end time has no fractional seconds, which # tests an edge case on sqlite. This Experiment is only # included in the test data when the DB supports microsecond # precision. if connection.features.supports_microsecond_precision: delay = datetime.timedelta(1) end = stime + delay + delta1 e1 = Experiment.objects.create(name='e1', assigned=sday, start=stime+delay, end=end, completed=end.date()) self.deltas.append(delta1) self.delays.append(e1.start- datetime.datetime.combine(e1.assigned, midnight)) self.days_long.append(e1.completed-e1.assigned) # e2: started three days after assigned, small duration end = stime+delta2 e2 = Experiment.objects.create(name='e2', assigned=sday-datetime.timedelta(3), start=stime, end=end, completed=end.date()) self.deltas.append(delta2) self.delays.append(e2.start- datetime.datetime.combine(e2.assigned, midnight)) self.days_long.append(e2.completed-e2.assigned) # e3: started four days after assigned, medium duration delay = datetime.timedelta(4) end = stime + delay + delta3 e3 = Experiment.objects.create(name='e3', assigned=sday, start=stime+delay, end=end, completed=end.date()) self.deltas.append(delta3) self.delays.append(e3.start- datetime.datetime.combine(e3.assigned, midnight)) self.days_long.append(e3.completed-e3.assigned) # e4: started 10 days after assignment, long duration end = stime + delta4 e4 = Experiment.objects.create(name='e4', assigned=sday-datetime.timedelta(10), start=stime, end=end, completed=end.date()) self.deltas.append(delta4) self.delays.append(e4.start- datetime.datetime.combine(e4.assigned, midnight)) self.days_long.append(e4.completed-e4.assigned) self.expnames = [e.name for e in Experiment.objects.all()] def test_delta_add(self): for i in range(len(self.deltas)): delta = self.deltas[i] test_set = [e.name for e in Experiment.objects.filter(end__lt=F('start')+delta)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(end__lte=F('start')+delta)] self.assertEqual(test_set, self.expnames[:i+1]) def test_delta_subtract(self): for i in range(len(self.deltas)): delta = self.deltas[i] test_set = [e.name for e in Experiment.objects.filter(start__gt=F('end')-delta)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(start__gte=F('end')-delta)] self.assertEqual(test_set, self.expnames[:i+1]) def test_exclude(self): for i in range(len(self.deltas)): delta = self.deltas[i] test_set = [e.name for e in Experiment.objects.exclude(end__lt=F('start')+delta)] self.assertEqual(test_set, self.expnames[i:]) test_set = [e.name for e in Experiment.objects.exclude(end__lte=F('start')+delta)] self.assertEqual(test_set, self.expnames[i+1:]) def test_date_comparison(self): for i in range(len(self.days_long)): days = self.days_long[i] test_set = [e.name for e in Experiment.objects.filter(completed__lt=F('assigned')+days)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(completed__lte=F('assigned')+days)] self.assertEqual(test_set, self.expnames[:i+1]) @skipUnlessDBFeature("supports_mixed_date_datetime_comparisons") def test_mixed_comparisons1(self): for i in range(len(self.delays)): delay = self.delays[i] if not connection.features.supports_microsecond_precision: delay = datetime.timedelta(delay.days, delay.seconds) test_set = [e.name for e in Experiment.objects.filter(assigned__gt=F('start')-delay)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(assigned__gte=F('start')-delay)] self.assertEqual(test_set, self.expnames[:i+1]) def test_mixed_comparisons2(self): delays = [datetime.timedelta(delay.days) for delay in self.delays] for i in range(len(delays)): delay = delays[i] test_set = [e.name for e in Experiment.objects.filter(start__lt=F('assigned')+delay)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(start__lte=F('assigned')+delay+ datetime.timedelta(1))] self.assertEqual(test_set, self.expnames[:i+1]) def test_delta_update(self): for i in range(len(self.deltas)): delta = self.deltas[i] exps = Experiment.objects.all() expected_durations = [e.duration() for e in exps] expected_starts = [e.start+delta for e in exps] expected_ends = [e.end+delta for e in exps] Experiment.objects.update(start=F('start')+delta, end=F('end')+delta) exps = Experiment.objects.all() new_starts = [e.start for e in exps] new_ends = [e.end for e in exps] new_durations = [e.duration() for e in exps] self.assertEqual(expected_starts, new_starts) self.assertEqual(expected_ends, new_ends) self.assertEqual(expected_durations, new_durations) def test_delta_invalid_op_mult(self): raised = False try: r = repr(Experiment.objects.filter(end__lt=F('start')*self.deltas[0])) except TypeError: raised = True self.assertTrue(raised, "TypeError not raised on attempt to multiply datetime by timedelta.") def test_delta_invalid_op_div(self): raised = False try: r = repr(Experiment.objects.filter(end__lt=F('start')/self.deltas[0])) except TypeError: raised = True self.assertTrue(raised, "TypeError not raised on attempt to divide datetime by timedelta.") def test_delta_invalid_op_mod(self): raised = False try: r = repr(Experiment.objects.filter(end__lt=F('start')%self.deltas[0])) except TypeError: raised = True self.assertTrue(raised, "TypeError not raised on attempt to modulo divide datetime by timedelta.") def test_delta_invalid_op_and(self): raised = False try: r = repr(Experiment.objects.filter(end__lt=F('start')&self.deltas[0])) except TypeError: raised = True self.assertTrue(raised, "TypeError not raised on attempt to binary and a datetime with a timedelta.") def test_delta_invalid_op_or(self): raised = False try: r = repr(Experiment.objects.filter(end__lt=F('start')|self.deltas[0])) except TypeError: raised = True self.assertTrue(raised, "TypeError not raised on attempt to binary or a datetime with a timedelta.")
16,681
Python
.py
330
39.230303
109
0.614199
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,976
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_runner/tests.py
""" Tests for django test runner """ import StringIO from django.core.exceptions import ImproperlyConfigured from django.test import simple from django.utils import unittest class DjangoTestRunnerTests(unittest.TestCase): def test_failfast(self): class MockTestOne(unittest.TestCase): def runTest(self): assert False class MockTestTwo(unittest.TestCase): def runTest(self): assert False suite = unittest.TestSuite([MockTestOne(), MockTestTwo()]) mock_stream = StringIO.StringIO() dtr = simple.DjangoTestRunner(verbosity=0, failfast=False, stream=mock_stream) result = dtr.run(suite) self.assertEqual(2, result.testsRun) self.assertEqual(2, len(result.failures)) dtr = simple.DjangoTestRunner(verbosity=0, failfast=True, stream=mock_stream) result = dtr.run(suite) self.assertEqual(1, result.testsRun) self.assertEqual(1, len(result.failures)) class DependencyOrderingTests(unittest.TestCase): def test_simple_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ('s3', ('s3_db', ['charlie'])), ] dependencies = { 'alpha': ['charlie'], 'bravo': ['charlie'], } ordered = simple.dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig,value in ordered] self.assertIn('s1', ordered_sigs) self.assertIn('s2', ordered_sigs) self.assertIn('s3', ordered_sigs) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2')) def test_chained_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ('s3', ('s3_db', ['charlie'])), ] dependencies = { 'alpha': ['bravo'], 'bravo': ['charlie'], } ordered = simple.dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig,value in ordered] self.assertIn('s1', ordered_sigs) self.assertIn('s2', ordered_sigs) self.assertIn('s3', ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2')) # Implied dependencies self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1')) def test_multiple_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ('s3', ('s3_db', ['charlie'])), ('s4', ('s4_db', ['delta'])), ] dependencies = { 'alpha': ['bravo','delta'], 'bravo': ['charlie'], 'delta': ['charlie'], } ordered = simple.dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig,aliases in ordered] self.assertIn('s1', ordered_sigs) self.assertIn('s2', ordered_sigs) self.assertIn('s3', ordered_sigs) self.assertIn('s4', ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s4'), ordered_sigs.index('s1')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2')) self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s4')) # Implicit dependencies self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1')) def test_circular_dependencies(self): raw = [ ('s1', ('s1_db', ['alpha'])), ('s2', ('s2_db', ['bravo'])), ] dependencies = { 'bravo': ['alpha'], 'alpha': ['bravo'], } self.assertRaises(ImproperlyConfigured, simple.dependency_ordered, raw, dependencies=dependencies)
4,102
Python
.py
98
32.469388
106
0.585886
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,977
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/serializers_regress/models.py
""" A test spanning all the capabilities of all the serializers. This class sets up a model for each model field type (except for image types, because of the PIL dependency). """ from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.localflavor.us.models import USStateField, PhoneNumberField # The following classes are for testing basic data # marshalling, including NULL values, where allowed. class BooleanData(models.Model): data = models.BooleanField() class CharData(models.Model): data = models.CharField(max_length=30, null=True) class DateData(models.Model): data = models.DateField(null=True) class DateTimeData(models.Model): data = models.DateTimeField(null=True) class DecimalData(models.Model): data = models.DecimalField(null=True, decimal_places=3, max_digits=5) class EmailData(models.Model): data = models.EmailField(null=True) class FileData(models.Model): data = models.FileField(null=True, upload_to='/foo/bar') class FilePathData(models.Model): data = models.FilePathField(null=True) class FloatData(models.Model): data = models.FloatField(null=True) class IntegerData(models.Model): data = models.IntegerField(null=True) class BigIntegerData(models.Model): data = models.BigIntegerField(null=True) # class ImageData(models.Model): # data = models.ImageField(null=True) class IPAddressData(models.Model): data = models.IPAddressField(null=True) class NullBooleanData(models.Model): data = models.NullBooleanField(null=True) class PhoneData(models.Model): data = PhoneNumberField(null=True) class PositiveIntegerData(models.Model): data = models.PositiveIntegerField(null=True) class PositiveSmallIntegerData(models.Model): data = models.PositiveSmallIntegerField(null=True) class SlugData(models.Model): data = models.SlugField(null=True) class SmallData(models.Model): data = models.SmallIntegerField(null=True) class TextData(models.Model): data = models.TextField(null=True) class TimeData(models.Model): data = models.TimeField(null=True) class USStateData(models.Model): data = USStateField(null=True) class Tag(models.Model): """A tag on an item.""" data = models.SlugField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() class Meta: ordering = ["data"] class GenericData(models.Model): data = models.CharField(max_length=30) tags = generic.GenericRelation(Tag) # The following test classes are all for validation # of related objects; in particular, forward, backward, # and self references. class Anchor(models.Model): """This is a model that can be used as something for other models to point at""" data = models.CharField(max_length=30) class Meta: ordering = ('id',) class UniqueAnchor(models.Model): """This is a model that can be used as something for other models to point at""" data = models.CharField(unique=True, max_length=30) class FKData(models.Model): data = models.ForeignKey(Anchor, null=True) class M2MData(models.Model): data = models.ManyToManyField(Anchor, null=True) class O2OData(models.Model): # One to one field can't be null here, since it is a PK. data = models.OneToOneField(Anchor, primary_key=True) class FKSelfData(models.Model): data = models.ForeignKey('self', null=True) class M2MSelfData(models.Model): data = models.ManyToManyField('self', null=True, symmetrical=False) class FKDataToField(models.Model): data = models.ForeignKey(UniqueAnchor, null=True, to_field='data') class FKDataToO2O(models.Model): data = models.ForeignKey(O2OData, null=True) class M2MIntermediateData(models.Model): data = models.ManyToManyField(Anchor, null=True, through='Intermediate') class Intermediate(models.Model): left = models.ForeignKey(M2MIntermediateData) right = models.ForeignKey(Anchor) extra = models.CharField(max_length=30, blank=True, default="doesn't matter") # The following test classes are for validating the # deserialization of objects that use a user-defined # field as the primary key. # Some of these data types have been commented out # because they can't be used as a primary key on one # or all database backends. class BooleanPKData(models.Model): data = models.BooleanField(primary_key=True) class CharPKData(models.Model): data = models.CharField(max_length=30, primary_key=True) # class DatePKData(models.Model): # data = models.DateField(primary_key=True) # class DateTimePKData(models.Model): # data = models.DateTimeField(primary_key=True) class DecimalPKData(models.Model): data = models.DecimalField(primary_key=True, decimal_places=3, max_digits=5) class EmailPKData(models.Model): data = models.EmailField(primary_key=True) # class FilePKData(models.Model): # data = models.FileField(primary_key=True, upload_to='/foo/bar') class FilePathPKData(models.Model): data = models.FilePathField(primary_key=True) class FloatPKData(models.Model): data = models.FloatField(primary_key=True) class IntegerPKData(models.Model): data = models.IntegerField(primary_key=True) # class ImagePKData(models.Model): # data = models.ImageField(primary_key=True) class IPAddressPKData(models.Model): data = models.IPAddressField(primary_key=True) # This is just a Boolean field with null=True, and we can't test a PK value of NULL. # class NullBooleanPKData(models.Model): # data = models.NullBooleanField(primary_key=True) class PhonePKData(models.Model): data = PhoneNumberField(primary_key=True) class PositiveIntegerPKData(models.Model): data = models.PositiveIntegerField(primary_key=True) class PositiveSmallIntegerPKData(models.Model): data = models.PositiveSmallIntegerField(primary_key=True) class SlugPKData(models.Model): data = models.SlugField(primary_key=True) class SmallPKData(models.Model): data = models.SmallIntegerField(primary_key=True) # class TextPKData(models.Model): # data = models.TextField(primary_key=True) # class TimePKData(models.Model): # data = models.TimeField(primary_key=True) class USStatePKData(models.Model): data = USStateField(primary_key=True) class ComplexModel(models.Model): field1 = models.CharField(max_length=10) field2 = models.CharField(max_length=10) field3 = models.CharField(max_length=10) # Tests for handling fields with pre_save functions, or # models with save functions that modify data class AutoNowDateTimeData(models.Model): data = models.DateTimeField(null=True, auto_now=True) class ModifyingSaveData(models.Model): data = models.IntegerField(null=True) def save(self): "A save method that modifies the data in the object" self.data = 666 super(ModifyingSaveData, self).save(raw) # Tests for serialization of models using inheritance. # Regression for #7202, #7350 class AbstractBaseModel(models.Model): parent_data = models.IntegerField() class Meta: abstract = True class InheritAbstractModel(AbstractBaseModel): child_data = models.IntegerField() class BaseModel(models.Model): parent_data = models.IntegerField() class InheritBaseModel(BaseModel): child_data = models.IntegerField() class ExplicitInheritBaseModel(BaseModel): parent = models.OneToOneField(BaseModel) child_data = models.IntegerField() class LengthModel(models.Model): data = models.IntegerField() def __len__(self): return self.data
7,687
Python
.py
182
38.807692
84
0.768682
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,978
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/serializers_regress/tests.py
""" A test spanning all the capabilities of all the serializers. This class defines sample data and a dynamically generated test case that is capable of testing the capabilities of the serializers. This includes all valid data values, plus forward, backwards and self references. """ import datetime import decimal try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.conf import settings from django.core import serializers, management from django.db import transaction, DEFAULT_DB_ALIAS, connection from django.test import TestCase from django.utils.functional import curry from models import * # A set of functions that can be used to recreate # test data objects of various kinds. # The save method is a raw base model save, to make # sure that the data in the database matches the # exact test case. def data_create(pk, klass, data): instance = klass(id=pk) instance.data = data models.Model.save_base(instance, raw=True) return [instance] def generic_create(pk, klass, data): instance = klass(id=pk) instance.data = data[0] models.Model.save_base(instance, raw=True) for tag in data[1:]: instance.tags.create(data=tag) return [instance] def fk_create(pk, klass, data): instance = klass(id=pk) setattr(instance, 'data_id', data) models.Model.save_base(instance, raw=True) return [instance] def m2m_create(pk, klass, data): instance = klass(id=pk) models.Model.save_base(instance, raw=True) instance.data = data return [instance] def im2m_create(pk, klass, data): instance = klass(id=pk) models.Model.save_base(instance, raw=True) return [instance] def im_create(pk, klass, data): instance = klass(id=pk) instance.right_id = data['right'] instance.left_id = data['left'] if 'extra' in data: instance.extra = data['extra'] models.Model.save_base(instance, raw=True) return [instance] def o2o_create(pk, klass, data): instance = klass() instance.data_id = data models.Model.save_base(instance, raw=True) return [instance] def pk_create(pk, klass, data): instance = klass() instance.data = data models.Model.save_base(instance, raw=True) return [instance] def inherited_create(pk, klass, data): instance = klass(id=pk,**data) # This isn't a raw save because: # 1) we're testing inheritance, not field behaviour, so none # of the field values need to be protected. # 2) saving the child class and having the parent created # automatically is easier than manually creating both. models.Model.save(instance) created = [instance] for klass,field in instance._meta.parents.items(): created.append(klass.objects.get(id=pk)) return created # A set of functions that can be used to compare # test data objects of various kinds def data_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data, instance.data, "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( pk, data, type(data), instance.data, type(instance.data)) ) def generic_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data[0], instance.data) testcase.assertEqual(data[1:], [t.data for t in instance.tags.order_by('id')]) def fk_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data, instance.data_id) def m2m_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data, [obj.id for obj in instance.data.order_by('id')]) def im2m_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) #actually nothing else to check, the instance just should exist def im_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data['left'], instance.left_id) testcase.assertEqual(data['right'], instance.right_id) if 'extra' in data: testcase.assertEqual(data['extra'], instance.extra) else: testcase.assertEqual("doesn't matter", instance.extra) def o2o_compare(testcase, pk, klass, data): instance = klass.objects.get(data=data) testcase.assertEqual(data, instance.data_id) def pk_compare(testcase, pk, klass, data): instance = klass.objects.get(data=data) testcase.assertEqual(data, instance.data) def inherited_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) for key,value in data.items(): testcase.assertEqual(value, getattr(instance,key)) # Define some data types. Each data type is # actually a pair of functions; one to create # and one to compare objects of that type data_obj = (data_create, data_compare) generic_obj = (generic_create, generic_compare) fk_obj = (fk_create, fk_compare) m2m_obj = (m2m_create, m2m_compare) im2m_obj = (im2m_create, im2m_compare) im_obj = (im_create, im_compare) o2o_obj = (o2o_create, o2o_compare) pk_obj = (pk_create, pk_compare) inherited_obj = (inherited_create, inherited_compare) test_data = [ # Format: (data type, PK value, Model Class, data) (data_obj, 1, BooleanData, True), (data_obj, 2, BooleanData, False), (data_obj, 10, CharData, "Test Char Data"), (data_obj, 11, CharData, ""), (data_obj, 12, CharData, "None"), (data_obj, 13, CharData, "null"), (data_obj, 14, CharData, "NULL"), (data_obj, 15, CharData, None), # (We use something that will fit into a latin1 database encoding here, # because that is still the default used on many system setups.) (data_obj, 16, CharData, u'\xa5'), (data_obj, 20, DateData, datetime.date(2006,6,16)), (data_obj, 21, DateData, None), (data_obj, 30, DateTimeData, datetime.datetime(2006,6,16,10,42,37)), (data_obj, 31, DateTimeData, None), (data_obj, 40, EmailData, "[email protected]"), (data_obj, 41, EmailData, None), (data_obj, 42, EmailData, ""), (data_obj, 50, FileData, 'file:///foo/bar/whiz.txt'), # (data_obj, 51, FileData, None), (data_obj, 52, FileData, ""), (data_obj, 60, FilePathData, "/foo/bar/whiz.txt"), (data_obj, 61, FilePathData, None), (data_obj, 62, FilePathData, ""), (data_obj, 70, DecimalData, decimal.Decimal('12.345')), (data_obj, 71, DecimalData, decimal.Decimal('-12.345')), (data_obj, 72, DecimalData, decimal.Decimal('0.0')), (data_obj, 73, DecimalData, None), (data_obj, 74, FloatData, 12.345), (data_obj, 75, FloatData, -12.345), (data_obj, 76, FloatData, 0.0), (data_obj, 77, FloatData, None), (data_obj, 80, IntegerData, 123456789), (data_obj, 81, IntegerData, -123456789), (data_obj, 82, IntegerData, 0), (data_obj, 83, IntegerData, None), #(XX, ImageData (data_obj, 90, IPAddressData, "127.0.0.1"), (data_obj, 91, IPAddressData, None), (data_obj, 100, NullBooleanData, True), (data_obj, 101, NullBooleanData, False), (data_obj, 102, NullBooleanData, None), (data_obj, 110, PhoneData, "212-634-5789"), (data_obj, 111, PhoneData, None), (data_obj, 120, PositiveIntegerData, 123456789), (data_obj, 121, PositiveIntegerData, None), (data_obj, 130, PositiveSmallIntegerData, 12), (data_obj, 131, PositiveSmallIntegerData, None), (data_obj, 140, SlugData, "this-is-a-slug"), (data_obj, 141, SlugData, None), (data_obj, 142, SlugData, ""), (data_obj, 150, SmallData, 12), (data_obj, 151, SmallData, -12), (data_obj, 152, SmallData, 0), (data_obj, 153, SmallData, None), (data_obj, 160, TextData, """This is a long piece of text. It contains line breaks. Several of them. The end."""), (data_obj, 161, TextData, ""), (data_obj, 162, TextData, None), (data_obj, 170, TimeData, datetime.time(10,42,37)), (data_obj, 171, TimeData, None), (data_obj, 180, USStateData, "MA"), (data_obj, 181, USStateData, None), (data_obj, 182, USStateData, ""), (generic_obj, 200, GenericData, ['Generic Object 1', 'tag1', 'tag2']), (generic_obj, 201, GenericData, ['Generic Object 2', 'tag2', 'tag3']), (data_obj, 300, Anchor, "Anchor 1"), (data_obj, 301, Anchor, "Anchor 2"), (data_obj, 302, UniqueAnchor, "UAnchor 1"), (fk_obj, 400, FKData, 300), # Post reference (fk_obj, 401, FKData, 500), # Pre reference (fk_obj, 402, FKData, None), # Empty reference (m2m_obj, 410, M2MData, []), # Empty set (m2m_obj, 411, M2MData, [300,301]), # Post reference (m2m_obj, 412, M2MData, [500,501]), # Pre reference (m2m_obj, 413, M2MData, [300,301,500,501]), # Pre and Post reference (o2o_obj, None, O2OData, 300), # Post reference (o2o_obj, None, O2OData, 500), # Pre reference (fk_obj, 430, FKSelfData, 431), # Pre reference (fk_obj, 431, FKSelfData, 430), # Post reference (fk_obj, 432, FKSelfData, None), # Empty reference (m2m_obj, 440, M2MSelfData, []), (m2m_obj, 441, M2MSelfData, []), (m2m_obj, 442, M2MSelfData, [440, 441]), (m2m_obj, 443, M2MSelfData, [445, 446]), (m2m_obj, 444, M2MSelfData, [440, 441, 445, 446]), (m2m_obj, 445, M2MSelfData, []), (m2m_obj, 446, M2MSelfData, []), (fk_obj, 450, FKDataToField, "UAnchor 1"), (fk_obj, 451, FKDataToField, "UAnchor 2"), (fk_obj, 452, FKDataToField, None), (fk_obj, 460, FKDataToO2O, 300), (im2m_obj, 470, M2MIntermediateData, None), #testing post- and prereferences and extra fields (im_obj, 480, Intermediate, {'right': 300, 'left': 470}), (im_obj, 481, Intermediate, {'right': 300, 'left': 490}), (im_obj, 482, Intermediate, {'right': 500, 'left': 470}), (im_obj, 483, Intermediate, {'right': 500, 'left': 490}), (im_obj, 484, Intermediate, {'right': 300, 'left': 470, 'extra': "extra"}), (im_obj, 485, Intermediate, {'right': 300, 'left': 490, 'extra': "extra"}), (im_obj, 486, Intermediate, {'right': 500, 'left': 470, 'extra': "extra"}), (im_obj, 487, Intermediate, {'right': 500, 'left': 490, 'extra': "extra"}), (im2m_obj, 490, M2MIntermediateData, []), (data_obj, 500, Anchor, "Anchor 3"), (data_obj, 501, Anchor, "Anchor 4"), (data_obj, 502, UniqueAnchor, "UAnchor 2"), (pk_obj, 601, BooleanPKData, True), (pk_obj, 602, BooleanPKData, False), (pk_obj, 610, CharPKData, "Test Char PKData"), # (pk_obj, 620, DatePKData, datetime.date(2006,6,16)), # (pk_obj, 630, DateTimePKData, datetime.datetime(2006,6,16,10,42,37)), (pk_obj, 640, EmailPKData, "[email protected]"), # (pk_obj, 650, FilePKData, 'file:///foo/bar/whiz.txt'), (pk_obj, 660, FilePathPKData, "/foo/bar/whiz.txt"), (pk_obj, 670, DecimalPKData, decimal.Decimal('12.345')), (pk_obj, 671, DecimalPKData, decimal.Decimal('-12.345')), (pk_obj, 672, DecimalPKData, decimal.Decimal('0.0')), (pk_obj, 673, FloatPKData, 12.345), (pk_obj, 674, FloatPKData, -12.345), (pk_obj, 675, FloatPKData, 0.0), (pk_obj, 680, IntegerPKData, 123456789), (pk_obj, 681, IntegerPKData, -123456789), (pk_obj, 682, IntegerPKData, 0), # (XX, ImagePKData (pk_obj, 690, IPAddressPKData, "127.0.0.1"), # (pk_obj, 700, NullBooleanPKData, True), # (pk_obj, 701, NullBooleanPKData, False), (pk_obj, 710, PhonePKData, "212-634-5789"), (pk_obj, 720, PositiveIntegerPKData, 123456789), (pk_obj, 730, PositiveSmallIntegerPKData, 12), (pk_obj, 740, SlugPKData, "this-is-a-slug"), (pk_obj, 750, SmallPKData, 12), (pk_obj, 751, SmallPKData, -12), (pk_obj, 752, SmallPKData, 0), # (pk_obj, 760, TextPKData, """This is a long piece of text. # It contains line breaks. # Several of them. # The end."""), # (pk_obj, 770, TimePKData, datetime.time(10,42,37)), (pk_obj, 780, USStatePKData, "MA"), # (pk_obj, 790, XMLPKData, "<foo></foo>"), (data_obj, 800, AutoNowDateTimeData, datetime.datetime(2006,6,16,10,42,37)), (data_obj, 810, ModifyingSaveData, 42), (inherited_obj, 900, InheritAbstractModel, {'child_data':37,'parent_data':42}), (inherited_obj, 910, ExplicitInheritBaseModel, {'child_data':37,'parent_data':42}), (inherited_obj, 920, InheritBaseModel, {'child_data':37,'parent_data':42}), (data_obj, 1000, BigIntegerData, 9223372036854775807), (data_obj, 1001, BigIntegerData, -9223372036854775808), (data_obj, 1002, BigIntegerData, 0), (data_obj, 1003, BigIntegerData, None), (data_obj, 1004, LengthModel, 0), (data_obj, 1005, LengthModel, 1), ] # Because Oracle treats the empty string as NULL, Oracle is expected to fail # when field.empty_strings_allowed is True and the value is None; skip these # tests. if connection.features.interprets_empty_strings_as_nulls: test_data = [data for data in test_data if not (data[0] == data_obj and data[2]._meta.get_field('data').empty_strings_allowed and data[3] is None)] # Regression test for #8651 -- a FK to an object iwth PK of 0 # This won't work on MySQL since it won't let you create an object # with a primary key of 0, if connection.features.allows_primary_key_0: test_data.extend([ (data_obj, 0, Anchor, "Anchor 0"), (fk_obj, 465, FKData, 0), ]) # Dynamically create serializer tests to ensure that all # registered serializers are automatically tested. class SerializerTests(TestCase): pass def serializerTest(format, self): # Create all the objects defined in the test data objects = [] instance_count = {} for (func, pk, klass, datum) in test_data: objects.extend(func[0](pk, klass, datum)) # Get a count of the number of objects created for each class for klass in instance_count: instance_count[klass] = klass.objects.count() # Add the generic tagged objects to the object list objects.extend(Tag.objects.all()) # Serialize the test database serialized_data = serializers.serialize(format, objects, indent=2) for obj in serializers.deserialize(format, serialized_data): obj.save() # Assert that the deserialized data is the same # as the original source for (func, pk, klass, datum) in test_data: func[1](self, pk, klass, datum) # Assert that the number of objects deserialized is the # same as the number that was serialized. for klass, count in instance_count.items(): self.assertEqual(count, klass.objects.count()) def fieldsTest(format, self): obj = ComplexModel(field1='first', field2='second', field3='third') obj.save_base(raw=True) # Serialize then deserialize the test database serialized_data = serializers.serialize(format, [obj], indent=2, fields=('field1','field3')) result = serializers.deserialize(format, serialized_data).next() # Check that the deserialized object contains data in only the serialized fields. self.assertEqual(result.object.field1, 'first') self.assertEqual(result.object.field2, '') self.assertEqual(result.object.field3, 'third') def streamTest(format, self): obj = ComplexModel(field1='first',field2='second',field3='third') obj.save_base(raw=True) # Serialize the test database to a stream stream = StringIO() serializers.serialize(format, [obj], indent=2, stream=stream) # Serialize normally for a comparison string_data = serializers.serialize(format, [obj], indent=2) # Check that the two are the same self.assertEqual(string_data, stream.getvalue()) stream.close() for format in serializers.get_serializer_formats(): setattr(SerializerTests, 'test_' + format + '_serializer', curry(serializerTest, format)) setattr(SerializerTests, 'test_' + format + '_serializer_fields', curry(fieldsTest, format)) if format != 'python': setattr(SerializerTests, 'test_' + format + '_serializer_stream', curry(streamTest, format))
15,965
Python
.py
357
40.154062
100
0.676722
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,979
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/defer_regress/models.py
""" Regression tests for defer() / only() behavior. """ from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.db import connection, models class Item(models.Model): name = models.CharField(max_length=15) text = models.TextField(default="xyzzy") value = models.IntegerField() other_value = models.IntegerField(default=0) def __unicode__(self): return self.name class RelatedItem(models.Model): item = models.ForeignKey(Item) class Child(models.Model): name = models.CharField(max_length=10) value = models.IntegerField() class Leaf(models.Model): name = models.CharField(max_length=10) child = models.ForeignKey(Child) second_child = models.ForeignKey(Child, related_name="other", null=True) value = models.IntegerField(default=42) def __unicode__(self): return self.name class ResolveThis(models.Model): num = models.FloatField() name = models.CharField(max_length=16)
1,003
Python
.py
28
31.821429
76
0.73423
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,980
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/defer_regress/tests.py
from operator import attrgetter from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.backends.db import SessionStore from django.db import connection from django.db.models.loading import cache from django.test import TestCase from models import ResolveThis, Item, RelatedItem, Child, Leaf class DeferRegressionTest(TestCase): def test_basic(self): # Deferred fields should really be deferred and not accidentally use # the field's default value just because they aren't passed to __init__ Item.objects.create(name="first", value=42) obj = Item.objects.only("name", "other_value").get(name="first") # Accessing "name" doesn't trigger a new database query. Accessing # "value" or "text" should. def test(): self.assertEqual(obj.name, "first") self.assertEqual(obj.other_value, 0) self.assertNumQueries(0, test) def test(): self.assertEqual(obj.value, 42) self.assertNumQueries(1, test) def test(): self.assertEqual(obj.text, "xyzzy") self.assertNumQueries(1, test) def test(): self.assertEqual(obj.text, "xyzzy") self.assertNumQueries(0, test) # Regression test for #10695. Make sure different instances don't # inadvertently share data in the deferred descriptor objects. i = Item.objects.create(name="no I'm first", value=37) items = Item.objects.only("value").order_by("-value") self.assertEqual(items[0].name, "first") self.assertEqual(items[1].name, "no I'm first") RelatedItem.objects.create(item=i) r = RelatedItem.objects.defer("item").get() self.assertEqual(r.item_id, i.id) self.assertEqual(r.item, i) # Some further checks for select_related() and inherited model # behaviour (regression for #10710). c1 = Child.objects.create(name="c1", value=42) c2 = Child.objects.create(name="c2", value=37) Leaf.objects.create(name="l1", child=c1, second_child=c2) obj = Leaf.objects.only("name", "child").select_related()[0] self.assertEqual(obj.child.name, "c1") self.assertQuerysetEqual( Leaf.objects.select_related().only("child__name", "second_child__name"), [ "l1", ], attrgetter("name") ) # Models instances with deferred fields should still return the same # content types as their non-deferred versions (bug #10738). ctype = ContentType.objects.get_for_model c1 = ctype(Item.objects.all()[0]) c2 = ctype(Item.objects.defer("name")[0]) c3 = ctype(Item.objects.only("name")[0]) self.assertTrue(c1 is c2 is c3) # Regression for #10733 - only() can be used on a model with two # foreign keys. results = Leaf.objects.only("name", "child", "second_child").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") results = Leaf.objects.only("name", "child", "second_child", "child__name", "second_child__name").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") # Test for #12163 - Pickling error saving session with unsaved model # instances. SESSION_KEY = '2b1189a188b44ad18c35e1baac6ceead' item = Item() item._deferred = False s = SessionStore(SESSION_KEY) s.clear() s["item"] = item s.save() s = SessionStore(SESSION_KEY) s.modified = True s.save() i2 = s["item"] self.assertFalse(i2._deferred) # Regression for #11936 - loading.get_models should not return deferred # models by default. klasses = sorted( cache.get_models(cache.get_app("defer_regress")), key=lambda klass: klass.__name__ ) self.assertEqual( klasses, [ Child, Item, Leaf, RelatedItem, ResolveThis, ] ) klasses = sorted( map( attrgetter("__name__"), cache.get_models( cache.get_app("defer_regress"), include_deferred=True ), ) ) self.assertEqual( klasses, [ "Child", "Child_Deferred_value", "Item", "Item_Deferred_name", "Item_Deferred_name_other_value_text", "Item_Deferred_name_other_value_value", "Item_Deferred_other_value_text_value", "Item_Deferred_text_value", "Leaf", "Leaf_Deferred_child_id_second_child_id_value", "Leaf_Deferred_name_value", "Leaf_Deferred_second_child_value", "Leaf_Deferred_value", "RelatedItem", "RelatedItem_Deferred_", "RelatedItem_Deferred_item_id", "ResolveThis", ] ) def test_resolve_columns(self): rt = ResolveThis.objects.create(num=5.0, name='Foobar') qs = ResolveThis.objects.defer('num') self.assertEqual(1, qs.count()) self.assertEqual('Foobar', qs[0].name)
5,528
Python
.py
130
31.776923
122
0.590512
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,981
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/conditional_processing/models.py
# -*- coding:utf-8 -*- from datetime import datetime from django.test import TestCase from django.utils import unittest from django.utils.http import parse_etags, quote_etag, parse_http_date FULL_RESPONSE = 'Test conditional get response' LAST_MODIFIED = datetime(2007, 10, 21, 23, 21, 47) LAST_MODIFIED_STR = 'Sun, 21 Oct 2007 23:21:47 GMT' LAST_MODIFIED_NEWER_STR = 'Mon, 18 Oct 2010 16:56:23 GMT' LAST_MODIFIED_INVALID_STR = 'Mon, 32 Oct 2010 16:56:23 GMT' EXPIRED_LAST_MODIFIED_STR = 'Sat, 20 Oct 2007 23:21:47 GMT' ETAG = 'b4246ffc4f62314ca13147c9d4f76974' EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6' class ConditionalGet(TestCase): def assertFullResponse(self, response, check_last_modified=True, check_etag=True): self.assertEqual(response.status_code, 200) self.assertEqual(response.content, FULL_RESPONSE) if check_last_modified: self.assertEqual(response['Last-Modified'], LAST_MODIFIED_STR) if check_etag: self.assertEqual(response['ETag'], '"%s"' % ETAG) def assertNotModified(self, response): self.assertEqual(response.status_code, 304) self.assertEqual(response.content, '') def testWithoutConditions(self): response = self.client.get('/condition/') self.assertFullResponse(response) def testIfModifiedSince(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_NEWER_STR response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_INVALID_STR response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR response = self.client.get('/condition/') self.assertFullResponse(response) def testIfNoneMatch(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/') self.assertFullResponse(response) # Several etags in If-None-Match is a bit exotic but why not? self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s", "%s"' % (ETAG, EXPIRED_ETAG) response = self.client.get('/condition/') self.assertNotModified(response) def testIfMatch(self): self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG response = self.client.put('/condition/etag/', {'data': ''}) self.assertEqual(response.status_code, 200) self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.put('/condition/etag/', {'data': ''}) self.assertEqual(response.status_code, 412) def testBothHeaders(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/') self.assertFullResponse(response) def testSingleCondition1(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/last_modified/') self.assertNotModified(response) response = self.client.get('/condition/etag/') self.assertFullResponse(response, check_last_modified=False) def testSingleCondition2(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/etag/') self.assertNotModified(response) response = self.client.get('/condition/last_modified/') self.assertFullResponse(response, check_etag=False) def testSingleCondition3(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR response = self.client.get('/condition/last_modified/') self.assertFullResponse(response, check_etag=False) def testSingleCondition4(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/etag/') self.assertFullResponse(response, check_last_modified=False) def testSingleCondition5(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/last_modified2/') self.assertNotModified(response) response = self.client.get('/condition/etag2/') self.assertFullResponse(response, check_last_modified=False) def testSingleCondition6(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/etag2/') self.assertNotModified(response) response = self.client.get('/condition/last_modified2/') self.assertFullResponse(response, check_etag=False) def testInvalidETag(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = r'"\"' response = self.client.get('/condition/etag/') self.assertFullResponse(response, check_last_modified=False) class ETagProcessing(unittest.TestCase): def testParsing(self): etags = parse_etags(r'"", "etag", "e\"t\"ag", "e\\tag", W/"weak"') self.assertEqual(etags, ['', 'etag', 'e"t"ag', r'e\tag', 'weak']) def testQuoting(self): quoted_etag = quote_etag(r'e\t"ag') self.assertEqual(quoted_etag, r'"e\\t\"ag"') class HttpDateProcessing(unittest.TestCase): def testParsingRfc1123(self): parsed = parse_http_date('Sun, 06 Nov 1994 08:49:37 GMT') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 06, 8, 49, 37)) def testParsingRfc850(self): parsed = parse_http_date('Sunday, 06-Nov-94 08:49:37 GMT') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 06, 8, 49, 37)) def testParsingAsctime(self): parsed = parse_http_date('Sun Nov 6 08:49:37 1994') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 06, 8, 49, 37))
6,873
Python
.py
127
46.047244
88
0.674059
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,982
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/conditional_processing/urls.py
from django.conf.urls.defaults import * import views urlpatterns = patterns('', ('^$', views.index), ('^last_modified/$', views.last_modified_view1), ('^last_modified2/$', views.last_modified_view2), ('^etag/$', views.etag_view1), ('^etag2/$', views.etag_view2), )
286
Python
.py
9
28.444444
53
0.644928
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,983
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/conditional_processing/views.py
# -*- coding:utf-8 -*- from django.views.decorators.http import condition, etag, last_modified from django.http import HttpResponse from models import FULL_RESPONSE, LAST_MODIFIED, ETAG def index(request): return HttpResponse(FULL_RESPONSE) index = condition(lambda r: ETAG, lambda r: LAST_MODIFIED)(index) def last_modified_view1(request): return HttpResponse(FULL_RESPONSE) last_modified_view1 = condition(last_modified_func=lambda r: LAST_MODIFIED)(last_modified_view1) def last_modified_view2(request): return HttpResponse(FULL_RESPONSE) last_modified_view2 = last_modified(lambda r: LAST_MODIFIED)(last_modified_view2) def etag_view1(request): return HttpResponse(FULL_RESPONSE) etag_view1 = condition(etag_func=lambda r: ETAG)(etag_view1) def etag_view2(request): return HttpResponse(FULL_RESPONSE) etag_view2 = etag(lambda r: ETAG)(etag_view2)
878
Python
.py
19
43.789474
96
0.79108
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,984
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/queryset_pickle/models.py
import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ def standalone_number(self): return 1 class Numbers(object): @staticmethod def get_static_number(self): return 2 @classmethod def get_class_number(self): return 3 def get_member_number(self): return 4 nn = Numbers() class Group(models.Model): name = models.CharField(_('name'), max_length=100) class Event(models.Model): group = models.ForeignKey(Group) class Happening(models.Model): when = models.DateTimeField(blank=True, default=datetime.datetime.now) name = models.CharField(blank=True, max_length=100, default=lambda:"test") number1 = models.IntegerField(blank=True, default=standalone_number) number2 = models.IntegerField(blank=True, default=Numbers.get_static_number) number3 = models.IntegerField(blank=True, default=Numbers.get_class_number) number4 = models.IntegerField(blank=True, default=nn.get_member_number)
1,014
Python
.py
26
34.615385
80
0.747959
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,985
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/queryset_pickle/tests.py
import pickle import datetime from django.test import TestCase from models import Group, Event, Happening class PickleabilityTestCase(TestCase): def assert_pickles(self, qs): self.assertEqual(list(pickle.loads(pickle.dumps(qs))), list(qs)) def test_related_field(self): g = Group.objects.create(name="Ponies Who Own Maybachs") self.assert_pickles(Event.objects.filter(group=g.id)) def test_datetime_callable_default_all(self): self.assert_pickles(Happening.objects.all()) def test_datetime_callable_default_filter(self): self.assert_pickles(Happening.objects.filter(when=datetime.datetime.now())) def test_lambda_as_default(self): self.assert_pickles(Happening.objects.filter(name="test")) def test_standalone_method_as_default(self): self.assert_pickles(Happening.objects.filter(number1=1)) def test_staticmethod_as_default(self): self.assert_pickles(Happening.objects.filter(number2=1)) def test_classmethod_as_default(self): self.assert_pickles(Happening.objects.filter(number3=1)) def test_membermethod_as_default(self): self.assert_pickles(Happening.objects.filter(number4=1))
1,210
Python
.py
24
44.083333
83
0.741056
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,986
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_changelist/models.py
from django.db import models class Parent(models.Model): name = models.CharField(max_length=128) class Child(models.Model): parent = models.ForeignKey(Parent, editable=False, null=True) name = models.CharField(max_length=30, blank=True) class Genre(models.Model): name = models.CharField(max_length=20) class Band(models.Model): name = models.CharField(max_length=20) nr_of_members = models.PositiveIntegerField() genres = models.ManyToManyField(Genre) class Musician(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=30) members = models.ManyToManyField(Musician, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): music = models.ForeignKey(Musician) group = models.ForeignKey(Group) role = models.CharField(max_length=15) class Quartet(Group): pass class ChordsMusician(Musician): pass class ChordsBand(models.Model): name = models.CharField(max_length=30) members = models.ManyToManyField(ChordsMusician, through='Invitation') class Invitation(models.Model): player = models.ForeignKey(ChordsMusician) band = models.ForeignKey(ChordsBand) instrument = models.CharField(max_length=15)
1,353
Python
.py
36
33.333333
74
0.748466
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,987
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_changelist/tests.py
from django.contrib import admin from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.views.main import ChangeList from django.core.paginator import Paginator from django.template import Context, Template from django.test import TransactionTestCase from models import (Child, Parent, Genre, Band, Musician, Group, Quartet, Membership, ChordsMusician, ChordsBand, Invitation) class ChangeListTests(TransactionTestCase): def test_select_related_preserved(self): """ Regression test for #10348: ChangeList.get_query_set() shouldn't overwrite a custom select_related provided by ModelAdmin.queryset(). """ m = ChildAdmin(Child, admin.site) cl = ChangeList(MockRequest(), Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) self.assertEqual(cl.query_set.query.select_related, {'parent': {'name': {}}}) def test_result_list_empty_changelist_value(self): """ Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored for relationship fields """ new_child = Child.objects.create(name='name', parent=None) request = MockRequest() m = ChildAdmin(Child, admin.site) cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="%d" name="_selected_action" /></td><th><a href="%d/">name</a></th><td class="nowrap">(None)</td></tr></tbody>' % (new_child.id, new_child.id) self.assertFalse(table_output.find(row_html) == -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_html(self): """ Verifies that inclusion tag result_list generates a table when with default ModelAdmin settings. """ new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = MockRequest() m = ChildAdmin(Child, admin.site) cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="%d" name="_selected_action" /></td><th><a href="%d/">name</a></th><td class="nowrap">Parent object</td></tr></tbody>' % (new_child.id, new_child.id) self.assertFalse(table_output.find(row_html) == -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_editable_html(self): """ Regression tests for #11791: Inclusion tag result_list generates a table and this checks that the items are nested within the table element tags. Also a regression test for #13599, verifies that hidden fields when list_editable is enabled are rendered in a div outside the table. """ new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = MockRequest() m = ChildAdmin(Child, admin.site) # Test with list_editable fields m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) FormSet = m.get_changelist_formset(request) cl.formset = FormSet(queryset=cl.result_list) template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) # make sure that hidden fields are in the correct place hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></div>' % new_child.id self.assertFalse(table_output.find(hiddenfields_div) == -1, 'Failed to find hidden fields in: %s' % table_output) # make sure that list editable fields are rendered in divs correctly editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />' self.assertFalse('<td>%s</td>' % editable_name_field == -1, 'Failed to find "name" list_editable field in: %s' % table_output) def test_result_list_editable(self): """ Regression test for #14312: list_editable with pagination """ new_parent = Parent.objects.create(name='parent') for i in range(200): new_child = Child.objects.create(name='name %s' % i, parent=new_parent) request = MockRequest() request.GET['p'] = -1 # Anything outside range m = ChildAdmin(Child, admin.site) # Test with list_editable fields m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] self.assertRaises(IncorrectLookupParameters, lambda: \ ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m)) def test_custom_paginator(self): new_parent = Parent.objects.create(name='parent') for i in range(200): new_child = Child.objects.create(name='name %s' % i, parent=new_parent) request = MockRequest() m = ChildAdmin(Child, admin.site) m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] m.paginator = CustomPaginator cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl.get_results(request) self.assertIsInstance(cl.paginator, CustomPaginator) def test_distinct_for_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't apper more than once. Basic ManyToMany. """ blues = Genre.objects.create(name='Blues') band = Band.objects.create(name='B.B. King Review', nr_of_members=11) band.genres.add(blues) band.genres.add(blues) m = BandAdmin(Band, admin.site) cl = ChangeList(MockFilteredRequestA(blues.pk), Band, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl.get_results(MockFilteredRequestA(blues.pk)) # There's only one Group instance self.assertEqual(cl.result_count, 1) def test_distinct_for_through_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't apper more than once. With an intermediate model. """ lead = Musician.objects.create(name='Vox') band = Group.objects.create(name='The Hype') Membership.objects.create(group=band, music=lead, role='lead voice') Membership.objects.create(group=band, music=lead, role='bass player') m = GroupAdmin(Group, admin.site) cl = ChangeList(MockFilteredRequestB(lead.pk), Group, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl.get_results(MockFilteredRequestB(lead.pk)) # There's only one Group instance self.assertEqual(cl.result_count, 1) def test_distinct_for_inherited_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't apper more than once. Model managed in the admin inherits from the one that defins the relationship. """ lead = Musician.objects.create(name='John') four = Quartet.objects.create(name='The Beatles') Membership.objects.create(group=four, music=lead, role='lead voice') Membership.objects.create(group=four, music=lead, role='guitar player') m = QuartetAdmin(Quartet, admin.site) cl = ChangeList(MockFilteredRequestB(lead.pk), Quartet, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl.get_results(MockFilteredRequestB(lead.pk)) # There's only one Quartet instance self.assertEqual(cl.result_count, 1) def test_distinct_for_m2m_to_inherited_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't apper more than once. Target of the relationship inherits from another. """ lead = ChordsMusician.objects.create(name='Player A') three = ChordsBand.objects.create(name='The Chords Trio') Invitation.objects.create(band=three, player=lead, instrument='guitar') Invitation.objects.create(band=three, player=lead, instrument='bass') m = ChordsBandAdmin(ChordsBand, admin.site) cl = ChangeList(MockFilteredRequestB(lead.pk), ChordsBand, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl.get_results(MockFilteredRequestB(lead.pk)) # There's only one ChordsBand instance self.assertEqual(cl.result_count, 1) def test_pagination(self): """ Regression tests for #12893: Pagination in admins changelist doesn't use queryset set by modeladmin. """ parent = Parent.objects.create(name='anything') for i in range(30): Child.objects.create(name='name %s' % i, parent=parent) Child.objects.create(name='filtered %s' % i, parent=parent) request = MockRequest() # Test default queryset m = ChildAdmin(Child, admin.site) cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) self.assertEqual(cl.query_set.count(), 60) self.assertEqual(cl.paginator.count, 60) self.assertEqual(cl.paginator.page_range, [1, 2, 3, 4, 5, 6]) # Test custom queryset m = FilteredChildAdmin(Child, admin.site) cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) self.assertEqual(cl.query_set.count(), 30) self.assertEqual(cl.paginator.count, 30) self.assertEqual(cl.paginator.page_range, [1, 2, 3]) class ChildAdmin(admin.ModelAdmin): list_display = ['name', 'parent'] list_per_page = 10 def queryset(self, request): return super(ChildAdmin, self).queryset(request).select_related("parent__name") class FilteredChildAdmin(admin.ModelAdmin): list_display = ['name', 'parent'] list_per_page = 10 def queryset(self, request): return super(FilteredChildAdmin, self).queryset(request).filter( name__contains='filtered') class MockRequest(object): GET = {} class CustomPaginator(Paginator): def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True): super(CustomPaginator, self).__init__(queryset, 5, orphans=2, allow_empty_first_page=allow_empty_first_page) class BandAdmin(admin.ModelAdmin): list_filter = ['genres'] class GroupAdmin(admin.ModelAdmin): list_filter = ['members'] class QuartetAdmin(admin.ModelAdmin): list_filter = ['members'] class ChordsBandAdmin(admin.ModelAdmin): list_filter = ['members'] class MockFilteredRequestA(object): def __init__(self, pk): self.GET = { 'genres' : pk } class MockFilteredRequestB(object): def __init__(self, pk): self.GET = { 'members': pk }
13,499
Python
.py
249
44.907631
272
0.646872
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,988
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/decorators/tests.py
from sys import version_info try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. from django.contrib.auth.decorators import login_required, permission_required, user_passes_test from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse, HttpRequest from django.utils.decorators import method_decorator from django.utils.functional import allow_lazy, lazy, memoize from django.utils.unittest import TestCase from django.views.decorators.http import require_http_methods, require_GET, require_POST from django.views.decorators.vary import vary_on_headers, vary_on_cookie from django.views.decorators.cache import cache_page, never_cache, cache_control def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" # django.views.decorators.http fully_decorated = require_http_methods(["GET"])(fully_decorated) fully_decorated = require_GET(fully_decorated) fully_decorated = require_POST(fully_decorated) # django.views.decorators.vary fully_decorated = vary_on_headers('Accept-language')(fully_decorated) fully_decorated = vary_on_cookie(fully_decorated) # django.views.decorators.cache fully_decorated = cache_page(60*15)(fully_decorated) fully_decorated = cache_control(private=True)(fully_decorated) fully_decorated = never_cache(fully_decorated) # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 fully_decorated = user_passes_test(lambda u:True)(fully_decorated) fully_decorated = login_required(fully_decorated) fully_decorated = permission_required('change_world')(fully_decorated) # django.contrib.admin.views.decorators fully_decorated = staff_member_required(fully_decorated) # django.utils.functional fully_decorated = memoize(fully_decorated, {}, 1) fully_decorated = allow_lazy(fully_decorated) fully_decorated = lazy(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Tests that django decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__') def test_user_passes_test_composition(self): """ Test that the user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_applied.append('test2') return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser(object): pass class DummyRequest(object): pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ['test2', 'test1']) def test_cache_page_new_style(self): """ Test that we can call cache_page the new way """ def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") def test_cache_page_old_style(self): """ Test that we can call cache_page the old way """ def my_view(request): return "response" my_view_cached = cache_page(my_view, 123) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(my_view, 123, key_prefix="test") self.assertEqual(my_view_cached2(HttpRequest()), "response") my_view_cached3 = cache_page(my_view) self.assertEqual(my_view_cached3(HttpRequest()), "response") my_view_cached4 = cache_page()(my_view) self.assertEqual(my_view_cached4(HttpRequest()), "response") # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wraps(func)(wrapper) myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wraps(func)(wrapper) myattr2_dec_m = method_decorator(myattr2_dec) class MethodDecoratorTests(TestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test(object): @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec @myattr2_dec def func(): pass self.assertEqual(getattr(func, 'myattr', False), True) self.assertEqual(getattr(func, 'myattr2', False), True) # Now check method_decorator class Test(object): @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass self.assertEqual(getattr(Test().method, 'myattr', False), True) self.assertEqual(getattr(Test().method, 'myattr2', False), True) self.assertEqual(getattr(Test.method, 'myattr', False), True) self.assertEqual(getattr(Test.method, 'myattr2', False), True) self.assertEqual(Test.method.__doc__, 'A method') self.assertEqual(Test.method.im_func.__name__, 'method')
6,377
Python
.py
146
37.041096
96
0.689922
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,989
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/settings_tests/tests.py
from django.conf import settings from django.utils import unittest from django.conf import settings, UserSettingsHolder, global_settings class SettingsTests(unittest.TestCase): # # Regression tests for #10130: deleting settings. # def test_settings_delete(self): settings.TEST = 'test' self.assertEqual('test', settings.TEST) del settings.TEST self.assertRaises(AttributeError, getattr, settings, 'TEST') def test_settings_delete_wrapped(self): self.assertRaises(TypeError, delattr, settings, '_wrapped') class TrailingSlashURLTests(unittest.TestCase): settings_module = settings def setUp(self): self._original_media_url = self.settings_module.MEDIA_URL def tearDown(self): self.settings_module.MEDIA_URL = self._original_media_url def test_blank(self): """ If blank, no PendingDeprecationWarning error will be raised, even though it doesn't end in a slash. """ self.settings_module.MEDIA_URL = '' self.assertEqual('', self.settings_module.MEDIA_URL) def test_end_slash(self): """ MEDIA_URL works if you end in a slash. """ self.settings_module.MEDIA_URL = '/foo/' self.assertEqual('/foo/', self.settings_module.MEDIA_URL) self.settings_module.MEDIA_URL = 'http://media.foo.com/' self.assertEqual('http://media.foo.com/', self.settings_module.MEDIA_URL) def test_no_end_slash(self): """ MEDIA_URL raises an PendingDeprecationWarning error if it doesn't end in a slash. """ import warnings warnings.filterwarnings('error', 'If set, MEDIA_URL must end with a slash', PendingDeprecationWarning) def setattr_settings(settings_module, attr, value): setattr(settings_module, attr, value) self.assertRaises(PendingDeprecationWarning, setattr_settings, self.settings_module, 'MEDIA_URL', '/foo') self.assertRaises(PendingDeprecationWarning, setattr_settings, self.settings_module, 'MEDIA_URL', 'http://media.foo.com') def test_double_slash(self): """ If a MEDIA_URL ends in more than one slash, presume they know what they're doing. """ self.settings_module.MEDIA_URL = '/stupid//' self.assertEqual('/stupid//', self.settings_module.MEDIA_URL) self.settings_module.MEDIA_URL = 'http://media.foo.com/stupid//' self.assertEqual('http://media.foo.com/stupid//', self.settings_module.MEDIA_URL)
2,686
Python
.py
60
35.4
110
0.643788
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,990
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/introspection/models.py
from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() facebook_user_id = models.BigIntegerField() def __unicode__(self): return u"%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter) def __unicode__(self): return self.headline class Meta: ordering = ('headline',)
586
Python
.py
16
31.375
59
0.689046
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,991
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/introspection/tests.py
from django.conf import settings from django.db import connection, DEFAULT_DB_ALIAS from django.test import TestCase, skipUnlessDBFeature from django.utils import functional from models import Reporter, Article # # The introspection module is optional, so methods tested here might raise # NotImplementedError. This is perfectly acceptable behavior for the backend # in question, but the tests need to handle this without failing. Ideally we'd # skip these tests, but until #4788 is done we'll just ignore them. # # The easiest way to accomplish this is to decorate every test case with a # wrapper that ignores the exception. # # The metaclass is just for fun. # def ignore_not_implemented(func): def _inner(*args, **kwargs): try: return func(*args, **kwargs) except NotImplementedError: return None functional.update_wrapper(_inner, func) return _inner class IgnoreNotimplementedError(type): def __new__(cls, name, bases, attrs): for k,v in attrs.items(): if k.startswith('test'): attrs[k] = ignore_not_implemented(v) return type.__new__(cls, name, bases, attrs) class IntrospectionTests(TestCase): __metaclass__ = IgnoreNotimplementedError def test_table_names(self): tl = connection.introspection.table_names() self.assertTrue(Reporter._meta.db_table in tl, "'%s' isn't in table_list()." % Reporter._meta.db_table) self.assertTrue(Article._meta.db_table in tl, "'%s' isn't in table_list()." % Article._meta.db_table) def test_django_table_names(self): cursor = connection.cursor() cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);'); tl = connection.introspection.django_table_names() cursor.execute("DROP TABLE django_ixn_test_table;") self.assertTrue('django_ixn_testcase_table' not in tl, "django_table_names() returned a non-Django table") def test_installed_models(self): tables = [Article._meta.db_table, Reporter._meta.db_table] models = connection.introspection.installed_models(tables) self.assertEqual(models, set([Article, Reporter])) def test_sequence_list(self): sequences = connection.introspection.sequence_list() expected = {'table': Reporter._meta.db_table, 'column': 'id'} self.assertTrue(expected in sequences, 'Reporter sequence not found in sequence_list()') def test_get_table_description_names(self): cursor = connection.cursor() desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) self.assertEqual([r[0] for r in desc], [f.column for f in Reporter._meta.fields]) def test_get_table_description_types(self): cursor = connection.cursor() desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table) self.assertEqual( [datatype(r[1], r) for r in desc], ['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField'] ) # Regression test for #9991 - 'real' types in postgres @skipUnlessDBFeature('has_real_datatype') def test_postgresql_real_type(self): cursor = connection.cursor() cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);") desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table') cursor.execute('DROP TABLE django_ixn_real_test_table;') self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField') def test_get_relations(self): cursor = connection.cursor() relations = connection.introspection.get_relations(cursor, Article._meta.db_table) # Older versions of MySQL don't have the chops to report on this stuff, # so just skip it if no relations come back. If they do, though, we # should test that the response is correct. if relations: # That's {field_index: (field_index_other_table, other_table)} self.assertEqual(relations, {3: (0, Reporter._meta.db_table)}) def test_get_indexes(self): cursor = connection.cursor() indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table) self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False}) def datatype(dbtype, description): """Helper to convert a data type into a string.""" dt = connection.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
4,699
Python
.py
94
42.244681
99
0.676112
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,992
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_inline_admin/models.py
from django.db import models from django.contrib import admin from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType class Episode(models.Model): name = models.CharField(max_length=100) class Media(models.Model): """ Media that can associated to any object. """ content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() url = models.URLField(verify_exists=False) def __unicode__(self): return self.url class MediaInline(generic.GenericTabularInline): model = Media class EpisodeAdmin(admin.ModelAdmin): inlines = [ MediaInline, ] admin.site.register(Episode, EpisodeAdmin) # # These models let us test the different GenericInline settings at # different urls in the admin site. # # # Generic inline with extra = 0 # class EpisodeExtra(Episode): pass class MediaExtraInline(generic.GenericTabularInline): model = Media extra = 0 admin.site.register(EpisodeExtra, inlines=[MediaExtraInline]) # # Generic inline with extra and max_num # class EpisodeMaxNum(Episode): pass class MediaMaxNumInline(generic.GenericTabularInline): model = Media extra = 5 max_num = 2 admin.site.register(EpisodeMaxNum, inlines=[MediaMaxNumInline]) # # Generic inline with exclude # class EpisodeExclude(Episode): pass class MediaExcludeInline(generic.GenericTabularInline): model = Media exclude = ['url'] admin.site.register(EpisodeExclude, inlines=[MediaExcludeInline]) # # Generic inline with unique_together # class Category(models.Model): name = models.CharField(max_length=50) class PhoneNumber(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') phone_number = models.CharField(max_length=30) category = models.ForeignKey(Category, null=True, blank=True) class Meta: unique_together = (('content_type', 'object_id', 'phone_number',),) class Contact(models.Model): name = models.CharField(max_length=50) phone_numbers = generic.GenericRelation(PhoneNumber) class PhoneNumberInline(generic.GenericTabularInline): model = PhoneNumber admin.site.register(Contact, inlines=[PhoneNumberInline]) admin.site.register(Category) # # Generic inline with can_delete=False # class EpisodePermanent(Episode): pass class MediaPermanentInline(generic.GenericTabularInline): model = Media can_delete = False admin.site.register(EpisodePermanent, inlines=[MediaPermanentInline])
2,687
Python
.py
84
28.690476
75
0.773893
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,993
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_inline_admin/urls.py
from django.conf.urls.defaults import * from django.contrib import admin urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), )
147
Python
.py
5
27.4
43
0.744681
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,994
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/generic_inline_admin/tests.py
# coding: utf-8 from django.conf import settings from django.contrib.contenttypes.generic import generic_inlineformset_factory from django.test import TestCase # local test models from models import Episode, EpisodeExtra, EpisodeMaxNum, EpisodeExclude, \ Media, EpisodePermanent, MediaPermanentInline, Category class GenericAdminViewTest(TestCase): fixtures = ['users.xml'] def setUp(self): # set TEMPLATE_DEBUG to True to ensure {% include %} will raise # exceptions since that is how inlines are rendered and #9498 will # bubble up if it is an issue. self.original_template_debug = settings.TEMPLATE_DEBUG settings.TEMPLATE_DEBUG = True self.client.login(username='super', password='secret') # Can't load content via a fixture (since the GenericForeignKey # relies on content type IDs, which will vary depending on what # other tests have been run), thus we do it here. e = Episode.objects.create(name='This Week in Django') self.episode_pk = e.pk m = Media(content_object=e, url='http://example.com/podcast.mp3') m.save() self.mp3_media_pk = m.pk m = Media(content_object=e, url='http://example.com/logo.png') m.save() self.png_media_pk = m.pk def tearDown(self): self.client.logout() settings.TEMPLATE_DEBUG = self.original_template_debug def testBasicAddGet(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/add/') self.assertEqual(response.status_code, 200) def testBasicEditGet(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk) self.assertEqual(response.status_code, 200) def testBasicAddPost(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": u"This Week in Django", # inline data "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": u"1", "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": u"0", "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": u"0", } response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/episode/add/', post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def testBasicEditPost(self): """ A smoke test to ensure POST on edit_view works. """ post_data = { "name": u"This Week in Django", # inline data "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": u"3", "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": u"2", "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": u"0", "generic_inline_admin-media-content_type-object_id-0-id": u"%d" % self.mp3_media_pk, "generic_inline_admin-media-content_type-object_id-0-url": u"http://example.com/podcast.mp3", "generic_inline_admin-media-content_type-object_id-1-id": u"%d" % self.png_media_pk, "generic_inline_admin-media-content_type-object_id-1-url": u"http://example.com/logo.png", "generic_inline_admin-media-content_type-object_id-2-id": u"", "generic_inline_admin-media-content_type-object_id-2-url": u"", } url = '/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk response = self.client.post(url, post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def testGenericInlineFormset(self): EpisodeMediaFormSet = generic_inlineformset_factory(Media, can_delete=False, extra=3) e = Episode.objects.get(name='This Week in Django') # Works with no queryset formset = EpisodeMediaFormSet(instance=e) self.assertEqual(len(formset.forms), 5) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/podcast.mp3" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.mp3_media_pk) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>' % self.png_media_pk) self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-2-url" type="text" name="generic_inline_admin-media-content_type-object_id-2-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-2-id" id="id_generic_inline_admin-media-content_type-object_id-2-id" /></p>') # A queryset can be used to alter display ordering formset = EpisodeMediaFormSet(instance=e, queryset=Media.objects.order_by('url')) self.assertEqual(len(formset.forms), 5) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.png_media_pk) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" value="http://example.com/podcast.mp3" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>' % self.mp3_media_pk) self.assertEqual(formset.forms[2].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-2-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-2-url" type="text" name="generic_inline_admin-media-content_type-object_id-2-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-2-id" id="id_generic_inline_admin-media-content_type-object_id-2-id" /></p>') # Works with a queryset that omits items formset = EpisodeMediaFormSet(instance=e, queryset=Media.objects.filter(url__endswith=".png")) self.assertEqual(len(formset.forms), 4) self.assertEqual(formset.forms[0].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-0-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-0-url" type="text" name="generic_inline_admin-media-content_type-object_id-0-url" value="http://example.com/logo.png" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-0-id" value="%s" id="id_generic_inline_admin-media-content_type-object_id-0-id" /></p>' % self.png_media_pk) self.assertEqual(formset.forms[1].as_p(), '<p><label for="id_generic_inline_admin-media-content_type-object_id-1-url">Url:</label> <input id="id_generic_inline_admin-media-content_type-object_id-1-url" type="text" name="generic_inline_admin-media-content_type-object_id-1-url" maxlength="200" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-1-id" id="id_generic_inline_admin-media-content_type-object_id-1-id" /></p>') def testGenericInlineFormsetFactory(self): # Regression test for #10522. inline_formset = generic_inlineformset_factory(Media, exclude=('url',)) # Regression test for #12340. e = Episode.objects.get(name='This Week in Django') formset = inline_formset(instance=e) self.assertTrue(formset.get_queryset().ordered) class GenericInlineAdminParametersTest(TestCase): fixtures = ['users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def _create_object(self, model): """ Create a model with an attached Media object via GFK. We can't load content via a fixture (since the GenericForeignKey relies on content type IDs, which will vary depending on what other tests have been run), thus we do it here. """ e = model.objects.create(name='This Week in Django') Media.objects.create(content_object=e, url='http://example.com/podcast.mp3') return e def testNoParam(self): """ With one initial form, extra (default) at 3, there should be 4 forms. """ e = self._create_object(Episode) response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/%s/' % e.pk) formset = response.context['inline_admin_formsets'][0].formset self.assertEqual(formset.total_form_count(), 4) self.assertEqual(formset.initial_form_count(), 1) def testExtraParam(self): """ With extra=0, there should be one form. """ e = self._create_object(EpisodeExtra) response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episodeextra/%s/' % e.pk) formset = response.context['inline_admin_formsets'][0].formset self.assertEqual(formset.total_form_count(), 1) self.assertEqual(formset.initial_form_count(), 1) def testMaxNumParam(self): """ With extra=5 and max_num=2, there should be only 2 forms. """ e = self._create_object(EpisodeMaxNum) inline_form_data = '<input type="hidden" name="generic_inline_admin-media-content_type-object_id-TOTAL_FORMS" value="2" id="id_generic_inline_admin-media-content_type-object_id-TOTAL_FORMS" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-INITIAL_FORMS" value="1" id="id_generic_inline_admin-media-content_type-object_id-INITIAL_FORMS" />' response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episodemaxnum/%s/' % e.pk) formset = response.context['inline_admin_formsets'][0].formset self.assertEqual(formset.total_form_count(), 2) self.assertEqual(formset.initial_form_count(), 1) def testExcludeParam(self): """ Generic inline formsets should respect include. """ e = self._create_object(EpisodeExclude) response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episodeexclude/%s/' % e.pk) formset = response.context['inline_admin_formsets'][0].formset self.assertFalse('url' in formset.forms[0], 'The formset has excluded "url" field.') class GenericInlineAdminWithUniqueTogetherTest(TestCase): fixtures = ['users.xml'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def testAdd(self): category_id = Category.objects.create(name='male').pk post_data = { "name": u"John Doe", # inline data "generic_inline_admin-phonenumber-content_type-object_id-TOTAL_FORMS": u"1", "generic_inline_admin-phonenumber-content_type-object_id-INITIAL_FORMS": u"0", "generic_inline_admin-phonenumber-content_type-object_id-MAX_NUM_FORMS": u"0", "generic_inline_admin-phonenumber-content_type-object_id-0-id": "", "generic_inline_admin-phonenumber-content_type-object_id-0-phone_number": "555-555-5555", "generic_inline_admin-phonenumber-content_type-object_id-0-category": "%s" % category_id, } response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/contact/add/') self.assertEqual(response.status_code, 200) response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data) self.assertEqual(response.status_code, 302) # redirect somewhere class NoInlineDeletionTest(TestCase): def test_no_deletion(self): fake_site = object() inline = MediaPermanentInline(EpisodePermanent, fake_site) fake_request = object() formset = inline.get_formset(fake_request) self.assertFalse(formset.can_delete)
13,477
Python
.py
184
64.380435
527
0.685393
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,995
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_util/models.py
from django.db import models class Article(models.Model): """ A simple Article model for testing """ site = models.ForeignKey('sites.Site', related_name="admin_articles") title = models.CharField(max_length=100) title2 = models.CharField(max_length=100, verbose_name="another name") created = models.DateTimeField() def test_from_model(self): return "nothing" def test_from_model_with_override(self): return "nothing" test_from_model_with_override.short_description = "not What you Expect" class Count(models.Model): num = models.PositiveSmallIntegerField() parent = models.ForeignKey('self', null=True) def __unicode__(self): return unicode(self.num) class Event(models.Model): date = models.DateTimeField(auto_now_add=True) class Location(models.Model): event = models.OneToOneField(Event, verbose_name='awesome event') class Guest(models.Model): event = models.OneToOneField(Event) name = models.CharField(max_length=255) class Meta: verbose_name = "awesome guest"
1,081
Python
.py
28
33.571429
75
0.715517
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,996
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_util/tests.py
from datetime import datetime from django.conf import settings from django.contrib import admin from django.contrib.admin.util import display_for_field, label_for_field, lookup_field from django.contrib.admin.util import NestedObjects from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE from django.contrib.sites.models import Site from django.db import models, DEFAULT_DB_ALIAS from django.test import TestCase from django.utils import unittest from django.utils.formats import localize from models import Article, Count, Event, Location class NestedObjectsTests(TestCase): """ Tests for ``NestedObject`` utility collection. """ def setUp(self): self.n = NestedObjects(using=DEFAULT_DB_ALIAS) self.objs = [Count.objects.create(num=i) for i in range(5)] def _check(self, target): self.assertEqual(self.n.nested(lambda obj: obj.num), target) def _connect(self, i, j): self.objs[i].parent = self.objs[j] self.objs[i].save() def _collect(self, *indices): self.n.collect([self.objs[i] for i in indices]) def test_unrelated_roots(self): self._connect(2, 1) self._collect(0) self._collect(1) self._check([0, 1, [2]]) def test_siblings(self): self._connect(1, 0) self._connect(2, 0) self._collect(0) self._check([0, [1, 2]]) def test_non_added_parent(self): self._connect(0, 1) self._collect(0) self._check([0]) def test_cyclic(self): self._connect(0, 2) self._connect(1, 0) self._connect(2, 1) self._collect(0) self._check([0, [1, [2]]]) def test_queries(self): self._connect(1, 0) self._connect(2, 0) # 1 query to fetch all children of 0 (1 and 2) # 1 query to fetch all children of 1 and 2 (none) # Should not require additional queries to populate the nested graph. self.assertNumQueries(2, self._collect, 0) class UtilTests(unittest.TestCase): def test_values_from_lookup_field(self): """ Regression test for #12654: lookup_field """ SITE_NAME = 'example.com' TITLE_TEXT = 'Some title' CREATED_DATE = datetime.min ADMIN_METHOD = 'admin method' SIMPLE_FUNCTION = 'function' INSTANCE_ATTRIBUTE = 'attr' class MockModelAdmin(object): def get_admin_value(self, obj): return ADMIN_METHOD simple_function = lambda obj: SIMPLE_FUNCTION article = Article( site=Site(domain=SITE_NAME), title=TITLE_TEXT, created=CREATED_DATE, ) article.non_field = INSTANCE_ATTRIBUTE verifications = ( ('site', SITE_NAME), ('created', localize(CREATED_DATE)), ('title', TITLE_TEXT), ('get_admin_value', ADMIN_METHOD), (simple_function, SIMPLE_FUNCTION), ('test_from_model', article.test_from_model()), ('non_field', INSTANCE_ATTRIBUTE) ) mock_admin = MockModelAdmin() for name, value in verifications: field, attr, resolved_value = lookup_field(name, article, mock_admin) if field is not None: resolved_value = display_for_field(resolved_value, field) self.assertEqual(value, resolved_value) def test_null_display_for_field(self): """ Regression test for #12550: display_for_field should handle None value. """ display_value = display_for_field(None, models.CharField()) self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE) display_value = display_for_field(None, models.CharField( choices=( (None, "test_none"), ) )) self.assertEqual(display_value, "test_none") display_value = display_for_field(None, models.DateField()) self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE) display_value = display_for_field(None, models.TimeField()) self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE) # Regression test for #13071: NullBooleanField has special # handling. display_value = display_for_field(None, models.NullBooleanField()) expected = u'<img src="%simg/admin/icon-unknown.gif" alt="None" />' % settings.ADMIN_MEDIA_PREFIX self.assertEqual(display_value, expected) display_value = display_for_field(None, models.DecimalField()) self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE) display_value = display_for_field(None, models.FloatField()) self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE) def test_label_for_field(self): """ Tests for label_for_field """ self.assertEqual( label_for_field("title", Article), "title" ) self.assertEqual( label_for_field("title2", Article), "another name" ) self.assertEqual( label_for_field("title2", Article, return_attr=True), ("another name", None) ) self.assertEqual( label_for_field("__unicode__", Article), "article" ) self.assertEqual( label_for_field("__str__", Article), "article" ) self.assertRaises( AttributeError, lambda: label_for_field("unknown", Article) ) def test_callable(obj): return "nothing" self.assertEqual( label_for_field(test_callable, Article), "Test callable" ) self.assertEqual( label_for_field(test_callable, Article, return_attr=True), ("Test callable", test_callable) ) self.assertEqual( label_for_field("test_from_model", Article), "Test from model" ) self.assertEqual( label_for_field("test_from_model", Article, return_attr=True), ("Test from model", Article.test_from_model) ) self.assertEqual( label_for_field("test_from_model_with_override", Article), "not What you Expect" ) self.assertEqual( label_for_field(lambda x: "nothing", Article), "--" ) class MockModelAdmin(object): def test_from_model(self, obj): return "nothing" test_from_model.short_description = "not Really the Model" self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin), "not Really the Model" ) self.assertEqual( label_for_field("test_from_model", Article, model_admin = MockModelAdmin, return_attr = True ), ("not Really the Model", MockModelAdmin.test_from_model) ) def test_related_name(self): """ Regression test for #13963 """ self.assertEqual( label_for_field('location', Event, return_attr=True), ('location', None), ) self.assertEqual( label_for_field('event', Location, return_attr=True), ('awesome event', None), ) self.assertEqual( label_for_field('guest', Event, return_attr=True), ('awesome guest', None), )
7,534
Python
.py
200
28.045
105
0.59545
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,997
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/localflavor/tests.py
from django.test import TestCase from django.utils import unittest # just import your tests here from us.tests import *
121
Python
.py
4
29
33
0.836207
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,998
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/localflavor/us/models.py
from django.db import models from django.contrib.localflavor.us.models import USStateField from django.contrib.localflavor.us.models import USPostalCodeField # When creating models you need to remember to add a app_label as # 'localflavor', so your model can be found class USPlace(models.Model): state = USStateField(blank=True) state_req = USStateField() state_default = USStateField(default="CA", blank=True) postal_code = USPostalCodeField(blank=True) name = models.CharField(max_length=20) class Meta: app_label = 'localflavor'
567
Python
.py
13
40
66
0.769928
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,999
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/localflavor/us/tests.py
from django.test import TestCase from forms import USPlaceForm class USLocalflavorTests(TestCase): def setUp(self): self.form = USPlaceForm({'state':'GA', 'state_req':'NC', 'postal_code': 'GA', 'name':'impossible'}) def test_get_display_methods(self): """Test that the get_*_display() methods are added to the model instances.""" place = self.form.save() self.assertEqual(place.get_state_display(), 'Georgia') self.assertEqual(place.get_state_req_display(), 'North Carolina') def test_required(self): """Test that required USStateFields throw appropriate errors.""" form = USPlaceForm({'state':'GA', 'name':'Place in GA'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['state_req'], [u'This field is required.']) def test_field_blank_option(self): """Test that the empty option is there.""" state_select_html = """\ <select name="state" id="id_state"> <option value="">---------</option> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AS">American Samoa</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="AA">Armed Forces Americas</option> <option value="AE">Armed Forces Europe</option> <option value="AP">Armed Forces Pacific</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DE">Delaware</option> <option value="DC">District of Columbia</option> <option value="FL">Florida</option> <option value="GA" selected="selected">Georgia</option> <option value="GU">Guam</option> <option value="HI">Hawaii</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="IA">Iowa</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="ME">Maine</option> <option value="MD">Maryland</option> <option value="MA">Massachusetts</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MS">Mississippi</option> <option value="MO">Missouri</option> <option value="MT">Montana</option> <option value="NE">Nebraska</option> <option value="NV">Nevada</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NY">New York</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="MP">Northern Mariana Islands</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="PR">Puerto Rico</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VT">Vermont</option> <option value="VI">Virgin Islands</option> <option value="VA">Virginia</option> <option value="WA">Washington</option> <option value="WV">West Virginia</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </select>""" self.assertEqual(str(self.form['state']), state_select_html) def test_full_postal_code_list(self): """Test that the full USPS code field is really the full list.""" usps_select_html = """\ <select name="postal_code" id="id_postal_code"> <option value="">---------</option> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AS">American Samoa</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="AA">Armed Forces Americas</option> <option value="AE">Armed Forces Europe</option> <option value="AP">Armed Forces Pacific</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DE">Delaware</option> <option value="DC">District of Columbia</option> <option value="FM">Federated States of Micronesia</option> <option value="FL">Florida</option> <option value="GA" selected="selected">Georgia</option> <option value="GU">Guam</option> <option value="HI">Hawaii</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="IA">Iowa</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="ME">Maine</option> <option value="MH">Marshall Islands</option> <option value="MD">Maryland</option> <option value="MA">Massachusetts</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MS">Mississippi</option> <option value="MO">Missouri</option> <option value="MT">Montana</option> <option value="NE">Nebraska</option> <option value="NV">Nevada</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NY">New York</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="MP">Northern Mariana Islands</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PW">Palau</option> <option value="PA">Pennsylvania</option> <option value="PR">Puerto Rico</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VT">Vermont</option> <option value="VI">Virgin Islands</option> <option value="VA">Virginia</option> <option value="WA">Washington</option> <option value="WV">West Virginia</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </select>""" self.assertEqual(str(self.form['postal_code']), usps_select_html)
6,153
Python
.py
150
39.053333
107
0.728076
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)