hash
stringlengths
64
64
content
stringlengths
0
1.51M
c43ae25d1bb3ac6e960eaa43f31fd5e7649ae64675a3c18f5dab7e73e6a4d771
import datetime from django.core.exceptions import ValidationError from django.forms import DurationField from django.test import SimpleTestCase from django.utils import translation from django.utils.duration import duration_string from . import FormFieldAssertionsMixin class DurationFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_durationfield_clean(self): f = DurationField() self.assertEqual(datetime.timedelta(seconds=30), f.clean('30')) self.assertEqual(datetime.timedelta(minutes=15, seconds=30), f.clean('15:30')) self.assertEqual(datetime.timedelta(hours=1, minutes=15, seconds=30), f.clean('1:15:30')) self.assertEqual( datetime.timedelta(days=1, hours=1, minutes=15, seconds=30, milliseconds=300), f.clean('1 1:15:30.3') ) def test_overflow(self): msg = "The number of days must be between {min_days} and {max_days}.".format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ) f = DurationField() with self.assertRaisesMessage(ValidationError, msg): f.clean('1000000000 00:00:00') with self.assertRaisesMessage(ValidationError, msg): f.clean('-1000000000 00:00:00') def test_overflow_translation(self): msg = "Le nombre de jours doit être entre {min_days} et {max_days}.".format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ) with translation.override('fr'): with self.assertRaisesMessage(ValidationError, msg): DurationField().clean('1000000000 00:00:00') def test_durationfield_render(self): self.assertWidgetRendersTo( DurationField(initial=datetime.timedelta(hours=1)), '<input id="id_f" type="text" name="f" value="01:00:00" required>', ) def test_durationfield_integer_value(self): f = DurationField() self.assertEqual(datetime.timedelta(0, 10800), f.clean(10800)) def test_durationfield_prepare_value(self): field = DurationField() td = datetime.timedelta(minutes=15, seconds=30) self.assertEqual(field.prepare_value(td), duration_string(td)) self.assertEqual(field.prepare_value('arbitrary'), 'arbitrary') self.assertIsNone(field.prepare_value(None))
313da6aeca2bc388b6d8ea8c1b2cf52f1ef2c76f694631fc6c8b39ee919f7038
import uuid from django.forms import UUIDField, ValidationError from django.test import SimpleTestCase class UUIDFieldTest(SimpleTestCase): def test_uuidfield_1(self): field = UUIDField() value = field.clean('550e8400e29b41d4a716446655440000') self.assertEqual(value, uuid.UUID('550e8400e29b41d4a716446655440000')) def test_clean_value_with_dashes(self): field = UUIDField() value = field.clean('550e8400-e29b-41d4-a716-446655440000') self.assertEqual(value, uuid.UUID('550e8400e29b41d4a716446655440000')) def test_uuidfield_2(self): field = UUIDField(required=False) value = field.clean('') self.assertIsNone(value) def test_uuidfield_3(self): field = UUIDField() with self.assertRaisesMessage(ValidationError, 'Enter a valid UUID.'): field.clean('550e8400') def test_uuidfield_4(self): field = UUIDField() value = field.prepare_value(uuid.UUID('550e8400e29b41d4a716446655440000')) self.assertEqual(value, '550e8400-e29b-41d4-a716-446655440000')
7c69be2262de9f85cbd1afe141d6b12220fdc90b654cbb3a98113d09fe438c03
import datetime from collections import Counter from unittest import mock from django.forms import ( BaseForm, CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField, ValidationError, formsets, ) from django.forms.formsets import BaseFormSet, all_valid, formset_factory from django.forms.utils import ErrorList from django.forms.widgets import HiddenInput from django.test import SimpleTestCase class Choice(Form): choice = CharField() votes = IntegerField() 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']) # A FormSet that takes a list of favorite drinks and raises an error if # there are any duplicates. FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3) class CustomKwargForm(Form): def __init__(self, *args, custom_kwarg, **kwargs): self.custom_kwarg = custom_kwarg super().__init__(*args, **kwargs) class FormsFormsetTestCase(SimpleTestCase): def make_choiceformset( self, formset_data=None, formset_class=ChoiceFormSet, total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs): """ Make a ChoiceFormset from the given formset_data. The data should be given as a list of (choice, votes) tuples. """ kwargs.setdefault('prefix', 'choices') kwargs.setdefault('auto_id', False) if formset_data is None: return formset_class(**kwargs) if total_forms is None: total_forms = len(formset_data) def prefixed(*args): args = (kwargs['prefix'],) + args return '-'.join(args) data = { prefixed('TOTAL_FORMS'): str(total_forms), prefixed('INITIAL_FORMS'): str(initial_forms), prefixed('MAX_NUM_FORMS'): str(max_num_forms), prefixed('MIN_NUM_FORMS'): str(min_num_forms), } for i, (choice, votes) in enumerate(formset_data): data[prefixed(str(i), 'choice')] = choice data[prefixed(str(i), 'votes')] = votes return formset_class(data, **kwargs) def test_basic_formset(self): """ A FormSet constructor takes the same arguments as Form. Create a FormSet for adding data. By default, it displays 1 blank form. """ formset = self.make_choiceformset() self.assertHTMLEqual( 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-MIN_NUM_FORMS" value="0"> <input type="hidden" name="choices-MAX_NUM_FORMS" value="1000"> <tr><th>Choice:</th><td><input type="text" name="choices-0-choice"></td></tr> <tr><th>Votes:</th><td><input type="number" name="choices-0-votes"></td></tr>""" ) # FormSet are treated similarly to Forms. 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, cleaned_data # and errors will be a list of dicts rather than a single dict. formset = self.make_choiceformset([('Calexico', '100')]) self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}]) # If a FormSet wasn't passed any data, is_valid() and has_changed() # return False. formset = self.make_choiceformset() self.assertFalse(formset.is_valid()) self.assertFalse(formset.has_changed()) def test_form_kwargs_formset(self): """ Custom kwargs set on the formset instance are passed to the underlying forms. """ FormSet = formset_factory(CustomKwargForm, extra=2) formset = FormSet(form_kwargs={'custom_kwarg': 1}) for form in formset: self.assertTrue(hasattr(form, 'custom_kwarg')) self.assertEqual(form.custom_kwarg, 1) def test_form_kwargs_formset_dynamic(self): """Form kwargs can be passed dynamically in a formset.""" class DynamicBaseFormSet(BaseFormSet): def get_form_kwargs(self, index): return {'custom_kwarg': index} DynamicFormSet = formset_factory(CustomKwargForm, formset=DynamicBaseFormSet, extra=2) formset = DynamicFormSet(form_kwargs={'custom_kwarg': 'ignored'}) for i, form in enumerate(formset): self.assertTrue(hasattr(form, 'custom_kwarg')) self.assertEqual(form.custom_kwarg, i) def test_form_kwargs_empty_form(self): FormSet = formset_factory(CustomKwargForm) formset = FormSet(form_kwargs={'custom_kwarg': 1}) self.assertTrue(hasattr(formset.empty_form, 'custom_kwarg')) self.assertEqual(formset.empty_form.custom_kwarg, 1) def test_formset_validation(self): # FormSet instances can also have an error attribute if validation failed for # any of the forms. formset = self.make_choiceformset([('Calexico', '')]) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'votes': ['This field is required.']}]) def test_formset_validation_count(self): """ A formset's ManagementForm is validated once per FormSet.is_valid() call and each form of the formset is cleaned once. """ def make_method_counter(func): """Add a counter to func for the number of times it's called.""" counter = Counter() counter.call_count = 0 def mocked_func(*args, **kwargs): counter.call_count += 1 return func(*args, **kwargs) return mocked_func, counter mocked_is_valid, is_valid_counter = make_method_counter(formsets.ManagementForm.is_valid) mocked_full_clean, full_clean_counter = make_method_counter(BaseForm.full_clean) formset = self.make_choiceformset([('Calexico', '100'), ('Any1', '42'), ('Any2', '101')]) with mock.patch('django.forms.formsets.ManagementForm.is_valid', mocked_is_valid), \ mock.patch('django.forms.forms.BaseForm.full_clean', mocked_full_clean): self.assertTrue(formset.is_valid()) self.assertEqual(is_valid_counter.call_count, 1) self.assertEqual(full_clean_counter.call_count, 4) def test_formset_has_changed(self): """ FormSet.has_changed() is True if any data is passed to its forms, even if the formset didn't validate. """ blank_formset = self.make_choiceformset([('', '')]) self.assertFalse(blank_formset.has_changed()) # invalid formset invalid_formset = self.make_choiceformset([('Calexico', '')]) self.assertFalse(invalid_formset.is_valid()) self.assertTrue(invalid_formset.has_changed()) # valid formset valid_formset = self.make_choiceformset([('Calexico', '100')]) self.assertTrue(valid_formset.is_valid()) self.assertTrue(valid_formset.has_changed()) def test_formset_initial_data(self): """ A FormSet can be prefilled with existing data by providing a list of dicts to the `initial` argument. By default, an extra blank form is included. """ formset = self.make_choiceformset(initial=[{'choice': 'Calexico', 'votes': 100}]) self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li>""" ) def test_blank_form_unfilled(self): """A form that's displayed as blank may be submitted as blank.""" formset = self.make_choiceformset([('Calexico', '100'), ('', '')], initial_forms=1) self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}, {}]) def test_second_form_partially_filled(self): """ If at least one field is filled out on a blank form, it will be validated. """ formset = self.make_choiceformset([('Calexico', '100'), ('The Decemberists', '')], initial_forms=1) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {'votes': ['This field is required.']}]) def test_delete_prefilled_data(self): """ Deleting prefilled data is an error. Removing data from form fields isn't the proper way to delete it. """ formset = self.make_choiceformset([('', ''), ('', '')], initial_forms=1) self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [{'votes': ['This field is required.'], 'choice': ['This field is required.']}, {}] ) def test_displaying_more_than_one_blank_form(self): """ More than 1 empty form can be displayed using formset_factory's `extra` argument. """ ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(auto_id=False, prefix='choices') self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""" ) # Since every form was displayed as blank, they are also accepted as # blank. This may seem a little strange, but min_num is used 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-MIN_NUM_FORMS': '0', # min number of forms '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_min_num_displaying_more_than_one_blank_form(self): """" More than 1 empty form can also be displayed using formset_factory's min_num argument. It will (essentially) increment the extra argument. """ ChoiceFormSet = formset_factory(Choice, extra=1, min_num=1) formset = ChoiceFormSet(auto_id=False, prefix='choices') # Min_num forms are required; extra forms can be empty. self.assertFalse(formset.forms[0].empty_permitted) self.assertTrue(formset.forms[1].empty_permitted) self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li>""" ) def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self): """More than 1 empty form can be displayed using min_num.""" ChoiceFormSet = formset_factory(Choice, extra=0, min_num=3) formset = ChoiceFormSet(auto_id=False, prefix='choices') self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""" ) def test_single_form_completed(self): """Just one form may be completed.""" data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms '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': 'Calexico'}, {}, {}]) def test_formset_validate_max_flag(self): """ If validate_max is set and max_num is less than TOTAL_FORMS in the data, a ValidationError is raised. MAX_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 1 or fewer forms.']) def test_formset_validate_min_flag(self): """ If validate_min is set and min_num is more than TOTAL_FORMS in the data, a ValidationError is raised. MIN_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 3 or more forms.']) def test_formset_validate_min_unchanged_forms(self): """ min_num validation doesn't consider unchanged forms with initial data as "empty". """ initial = [ {'choice': 'Zero', 'votes': 0}, {'choice': 'One', 'votes': 0}, ] data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '2', 'choices-MIN_NUM_FORMS': '0', 'choices-MAX_NUM_FORMS': '2', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', # changed from initial } ChoiceFormSet = formset_factory(Choice, min_num=2, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices', initial=initial) self.assertFalse(formset.forms[0].has_changed()) self.assertTrue(formset.forms[1].has_changed()) self.assertTrue(formset.is_valid()) def test_formset_validate_min_excludes_empty_forms(self): data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '0', } ChoiceFormSet = formset_factory(Choice, extra=2, min_num=1, validate_min=True, can_delete=True) formset = ChoiceFormSet(data, prefix='choices') self.assertFalse(formset.has_changed()) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 1 or more forms.']) def test_second_form_partially_filled_2(self): """A partially completed form is invalid.""" data = { 'choices-TOTAL_FORMS': '3', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms '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': ['This field is required.']}, {}]) def test_more_initial_data(self): """ The extra argument works when the formset is pre-filled with initial data. """ initial = [{'choice': 'Calexico', 'votes': 100}] ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li> <li>Choice: <input type="text" name="choices-3-choice"></li> <li>Votes: <input type="number" name="choices-3-votes"></li>""" ) # Retrieving an empty form works. Tt shows up in the form list. self.assertTrue(formset.empty_form.empty_permitted) self.assertHTMLEqual( formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice"></li> <li>Votes: <input type="number" name="choices-__prefix__-votes"></li>""" ) def test_formset_with_deletion(self): """ formset_factory's can_delete argument adds a boolean "delete" field to each form. When that boolean field is True, the form will be in formset.deleted_forms. """ ChoiceFormSet = formset_factory(Choice, can_delete=True) initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" 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="number" 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="number" name="choices-2-votes"></li> <li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>""" ) # To delete something, 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-MIN_NUM_FORMS': '0', # min number of forms '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': 'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, {}, ] ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}] ) def test_formset_with_deletion_remove_deletion_flag(self): """ If a form is filled with something and can_delete is also checked, that form's errors shouldn't 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 'choices-MIN_NUM_FORMS': '0', # min number of forms '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 the deletion flag is removed, validation is enabled. data['check-1-DELETE'] = '' formset = CheckFormSet(data, prefix='check') self.assertFalse(formset.is_valid()) def test_formset_with_deletion_invalid_deleted_form(self): """ deleted_forms works on a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory(form=FavoriteDrinkForm, can_delete=True) formset = FavoriteDrinkFormset({ 'form-0-name': '', 'form-0-DELETE': 'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1, }) self.assertTrue(formset.is_valid()) self.assertEqual(formset._errors, []) self.assertEqual(len(formset.deleted_forms), 1) def test_formsets_with_ordering(self): """ formset_factory's can_order argument adds an integer field to each form. 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 its order to 0. """ ChoiceFormSet = formset_factory(Choice, can_order=True) initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Order: <input type="number" name="choices-0-ORDER" value="1"></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie"></li> <li>Votes: <input type="number" name="choices-1-votes" value="900"></li> <li>Order: <input type="number" name="choices-1-ORDER" value="2"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li> <li>Order: <input type="number" 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-MIN_NUM_FORMS': '0', # min number of forms '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()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {'votes': 500, 'ORDER': 0, 'choice': 'The Decemberists'}, {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'}, {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'}, ], ) def test_formsets_with_order_custom_widget(self): class OrderingAttributFormSet(BaseFormSet): ordering_widget = HiddenInput class OrderingMethodFormSet(BaseFormSet): def get_ordering_widget(self): return HiddenInput(attrs={'class': 'ordering'}) tests = ( (OrderingAttributFormSet, '<input type="hidden" name="form-0-ORDER">'), (OrderingMethodFormSet, '<input class="ordering" type="hidden" name="form-0-ORDER">'), ) for formset_class, order_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory(ArticleForm, formset=formset_class, can_order=True) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), ( '<li>Title: <input type="text" name="form-0-title"></li>' '<li>Pub date: <input type="text" name="form-0-pub_date">' '%s</li>' % order_html ), ) def test_empty_ordered_fields(self): """ Ordering fields are allowed to be left blank. If they are left blank, they'll 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-MIN_NUM_FORMS': '0', # min number of forms '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()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'}, {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'}, {'votes': 500, 'ORDER': None, 'choice': 'The Decemberists'}, {'votes': 50, 'ORDER': None, 'choice': 'Basia Bulat'}, ], ) def test_ordering_blank_fieldsets(self): """Ordering works 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-MIN_NUM_FORMS': '0', # min number of forms '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()) self.assertEqual(formset.ordered_forms, []) def test_formset_with_ordering_and_deletion(self): """FormSets with ordering + deletion.""" ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) initial = [ {'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}, {'choice': 'The Decemberists', 'votes': 500}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') self.assertHTMLEqual( '\n'.join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Order: <input type="number" 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="number" name="choices-1-votes" value="900"></li> <li>Order: <input type="number" 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="number" name="choices-2-votes" value="500"></li> <li>Order: <input type="number" 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="number" name="choices-3-votes"></li> <li>Order: <input type="number" 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-MIN_NUM_FORMS': '0', # min number of forms '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()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': 'The Decemberists'}, {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': 'Calexico'}, ], ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}] ) def test_invalid_deleted_form_with_ordering(self): """ Can get ordered_forms from a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory(form=FavoriteDrinkForm, can_delete=True, can_order=True) formset = FavoriteDrinkFormset({ 'form-0-name': '', 'form-0-DELETE': 'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1 }) self.assertTrue(formset.is_valid()) self.assertEqual(formset.ordered_forms, []) def test_clean_hook(self): """ FormSets have a clean() hook for doing extra validation that isn't tied to any form. It follows the same pattern as the clean() hook on Forms. """ # 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-MIN_NUM_FORMS': '0', # min number of forms '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.') # The valid case still works. data['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 with max_num.""" # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the extra parameter. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( '\n'.join(str(form) for form in formset.forms), """<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() self.assertEqual(formset.forms, []) def test_limited_max_forms_two(self): LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( '\n'.join(str(form) for form in formset.forms), """<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>""" ) def test_limiting_extra_lest_than_max_num(self): """max_num has no effect when extra is less than max_num.""" LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( '\n'.join(str(form) for form in formset.forms), """<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): # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the initial and extra # parameters. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) formset = LimitedFavoriteDrinkFormSet(initial=[{'name': 'Fernet and Coke'}]) self.assertHTMLEqual( '\n'.join(str(form) for form in formset.forms), """<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, regardless of extra, unless initial data is present. """ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0) formset = LimitedFavoriteDrinkFormSet() self.assertEqual(formset.forms, []) def test_max_num_zero_with_initial(self): # initial trumps max_num initial = [ {'name': 'Fernet and Coke'}, {'name': 'Bloody Mary'}, ] LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0) formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( '\n'.join(str(form) for form in formset.forms), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke"></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></td></tr>""" ) def test_more_initial_than_max_num(self): """ More initial forms than max_num results in all initial forms being displayed (but 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) self.assertHTMLEqual( '\n'.join(str(form) for form in formset.forms), """<tr><th><label for="id_form-0-name">Name:</label></th> <td><input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic"></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th> <td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></td></tr> <tr><th><label for="id_form-2-name">Name:</label></th> <td><input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke"></td></tr>""" ) def test_more_initial_form_result_in_one(self): """ One form from initial and extra=3 with max_num=2 results in the one initial form and one extra. """ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2) formset = LimitedFavoriteDrinkFormSet(initial=[{'name': 'Gin Tonic'}]) self.assertHTMLEqual( '\n'.join(str(form) for form in formset.forms), """<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_management_form_prefix(self): """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-MIN_NUM_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_non_form_errors(self): data = { 'drinks-TOTAL_FORMS': '2', # the number of forms rendered 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data 'drinks-MIN_NUM_FORMS': '0', # min number of forms '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(), ['You may only specify a drink once.']) def test_formset_iteration(self): """Formset instances are iterable.""" ChoiceFormset = formset_factory(Choice, extra=3) formset = ChoiceFormset() # An iterated formset yields formset.forms. forms = list(formset) self.assertEqual(forms, formset.forms) self.assertEqual(len(formset), len(forms)) # A formset may be indexed to retrieve its forms. self.assertEqual(formset[0], forms[0]) with self.assertRaises(IndexError): formset[3] # Formsets can override the default iteration order class BaseReverseFormSet(BaseFormSet): def __iter__(self): return reversed(self.forms) def __getitem__(self, idx): return super().__getitem__(len(self) - idx - 1) ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() # __iter__() modifies the 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)) def test_formset_nonzero(self): """A formsets without any forms evaluates as True.""" ChoiceFormset = formset_factory(Choice, extra=0) formset = ChoiceFormset() self.assertEqual(len(formset.forms), 0) self.assertTrue(formset) def test_formset_splitdatetimefield(self): """ Formset works with SplitDateTimeField(initial=datetime.datetime.now). """ class SplitDateTimeForm(Form): when = SplitDateTimeField(initial=datetime.datetime.now) SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-0-when_0': '1904-06-16', 'form-0-when_1': '15:51:33', } formset = SplitDateTimeFormSet(data) self.assertTrue(formset.is_valid()) def test_formset_error_class(self): """Formset's forms use the formset's error_class.""" class CustomErrorList(ErrorList): pass formset = FavoriteDrinksFormSet(error_class=CustomErrorList) self.assertEqual(formset.forms[0].error_class, CustomErrorList) def test_formset_calls_forms_is_valid(self): """Formsets call is_valid() on each form.""" class AnotherChoice(Choice): def is_valid(self): self.is_valid_called = True return super().is_valid() AnotherChoiceFormSet = formset_factory(AnotherChoice) data = { 'choices-TOTAL_FORMS': '1', # number of forms rendered 'choices-INITIAL_FORMS': '0', # number of forms with initial data 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', } formset = AnotherChoiceFormSet(data, auto_id=False, prefix='choices') self.assertTrue(formset.is_valid()) self.assertTrue(all(form.is_valid_called for form in formset.forms)) def test_hard_limit_on_instantiated_forms(self): """A formset has a hard limit on the number of forms instantiated.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 2 ChoiceFormSet = formset_factory(Choice, max_num=1) # someone fiddles with the mgmt form data... formset = ChoiceFormSet( { 'choices-TOTAL_FORMS': '4', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '4', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', 'choices-2-choice': 'Two', 'choices-2-votes': '2', 'choices-3-choice': 'Three', 'choices-3-votes': '3', }, prefix='choices', ) # But we still only instantiate 3 forms self.assertEqual(len(formset.forms), 3) # and the formset isn't valid self.assertFalse(formset.is_valid()) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_increase_hard_limit(self): """Can increase the built-in forms limit via a higher max_num.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 3 # for this form, we want a limit of 4 ChoiceFormSet = formset_factory(Choice, max_num=4) formset = ChoiceFormSet( { 'choices-TOTAL_FORMS': '4', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '4', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', 'choices-2-choice': 'Two', 'choices-2-votes': '2', 'choices-3-choice': 'Three', 'choices-3-votes': '3', }, prefix='choices', ) # Four forms are instantiated and no exception is raised self.assertEqual(len(formset.forms), 4) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_non_form_errors_run_full_clean(self): """ If non_form_errors() is called without calling is_valid() first, it should ensure that full_clean() is called. """ class BaseCustomFormSet(BaseFormSet): def clean(self): raise ValidationError("This is a non-form error") ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) data = { 'choices-TOTAL_FORMS': '1', 'choices-INITIAL_FORMS': '0', } formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertIsInstance(formset.non_form_errors(), ErrorList) self.assertEqual(list(formset.non_form_errors()), ['This is a non-form error']) def test_validate_max_ignores_forms_marked_for_deletion(self): class CheckForm(Form): field = IntegerField() data = { 'check-TOTAL_FORMS': '2', 'check-INITIAL_FORMS': '0', 'check-MAX_NUM_FORMS': '1', 'check-0-field': '200', 'check-0-DELETE': '', 'check-1-field': '50', 'check-1-DELETE': 'on', } CheckFormSet = formset_factory(CheckForm, max_num=1, validate_max=True, can_delete=True) formset = CheckFormSet(data, prefix='check') self.assertTrue(formset.is_valid()) def test_formset_total_error_count(self): """A valid formset should have 0 total errors.""" data = [ # formset_data, expected error count ([('Calexico', '100')], 0), ([('Calexico', '')], 1), ([('', 'invalid')], 2), ([('Calexico', '100'), ('Calexico', '')], 1), ([('Calexico', ''), ('Calexico', '')], 2), ] for formset_data, expected_error_count in data: formset = self.make_choiceformset(formset_data) self.assertEqual(formset.total_error_count(), expected_error_count) def test_formset_total_error_count_with_non_form_errors(self): data = { 'choices-TOTAL_FORMS': '2', # the number of forms rendered 'choices-INITIAL_FORMS': '0', # the number of forms with initial data 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertEqual(formset.total_error_count(), 1) data['choices-1-votes'] = '' formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertEqual(formset.total_error_count(), 2) def test_html_safe(self): formset = self.make_choiceformset() self.assertTrue(hasattr(formset, '__html__')) self.assertEqual(str(formset), formset.__html__()) class FormsetAsTagTests(SimpleTestCase): def setUp(self): data = { 'choices-TOTAL_FORMS': '1', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', 'choices-MAX_NUM_FORMS': '0', 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', } self.formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.management_form_html = ( '<input type="hidden" name="choices-TOTAL_FORMS" value="1">' '<input type="hidden" name="choices-INITIAL_FORMS" value="0">' '<input type="hidden" name="choices-MIN_NUM_FORMS" value="0">' '<input type="hidden" name="choices-MAX_NUM_FORMS" value="0">' ) def test_as_table(self): self.assertHTMLEqual( self.formset.as_table(), self.management_form_html + ( '<tr><th>Choice:</th><td>' '<input type="text" name="choices-0-choice" value="Calexico"></td></tr>' '<tr><th>Votes:</th><td>' '<input type="number" name="choices-0-votes" value="100"></td></tr>' ) ) def test_as_p(self): self.assertHTMLEqual( self.formset.as_p(), self.management_form_html + ( '<p>Choice: <input type="text" name="choices-0-choice" value="Calexico"></p>' '<p>Votes: <input type="number" name="choices-0-votes" value="100"></p>' ) ) def test_as_ul(self): self.assertHTMLEqual( self.formset.as_ul(), self.management_form_html + ( '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li>' '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' ) ) class ArticleForm(Form): title = CharField() pub_date = DateField() ArticleFormSet = formset_factory(ArticleForm) class TestIsBoundBehavior(SimpleTestCase): def test_no_data_raises_validation_error(self): msg = 'ManagementForm data is missing or has been tampered with' with self.assertRaisesMessage(ValidationError, msg): ArticleFormSet({}).is_valid() def test_with_management_data_attrs_work_fine(self): data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '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_caught_by_formset(self): data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-0-title': 'Test', 'form-0-pub_date': '1904-06-16', 'form-1-title': 'Test', 'form-1-pub_date': '', # <-- this date is missing but required } formset = ArticleFormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual([{}, {'pub_date': ['This field is required.']}], formset.errors) def test_empty_forms_are_unbound(self): data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-0-title': 'Test', 'form-0-pub_date': '1904-06-16', } unbound_formset = ArticleFormSet() bound_formset = ArticleFormSet(data) empty_forms = [ unbound_formset.empty_form, 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.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p()) class TestEmptyFormSet(SimpleTestCase): def test_empty_formset_is_valid(self): """An empty formset still calls clean()""" class EmptyFsetWontValidate(BaseFormSet): def clean(self): raise ValidationError('Clean method called') 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()) def test_empty_formset_media(self): """Media is available on empty formset.""" class MediaForm(Form): class Media: js = ('some-file.js',) self.assertIn('some-file.js', str(formset_factory(MediaForm, extra=0)().media)) def test_empty_formset_is_multipart(self): """is_multipart() works with an empty formset.""" class FileForm(Form): file = FileField() self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart()) class AllValidTests(SimpleTestCase): def test_valid(self): data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', 'choices-1-votes': '1', } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix='choices') formset2 = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertIs(all_valid((formset1, formset2)), True) expected_errors = [{}, {}] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors) def test_invalid(self): """all_valid() validates all forms, even when some are invalid.""" data = { 'choices-TOTAL_FORMS': '2', 'choices-INITIAL_FORMS': '0', 'choices-MIN_NUM_FORMS': '0', 'choices-0-choice': 'Zero', 'choices-0-votes': '', 'choices-1-choice': 'One', 'choices-1-votes': '', } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix='choices') formset2 = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertIs(all_valid((formset1, formset2)), False) expected_errors = [{'votes': ['This field is required.']}, {'votes': ['This field is required.']}] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors)
d87423cbd8e18911287e603878444a1b9dcfdae8517c19efc53dada22ad00b93
import copy from django.core.exceptions import ValidationError from django.forms.utils import ErrorDict, ErrorList, flatatt from django.test import SimpleTestCase from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy class FormsUtilsTestCase(SimpleTestCase): # Tests for forms/utils.py module. def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({'id': "header"}), ' id="header"') self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"') self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': "required"}), ' class="news" required="required" title="Read this"' ) self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': True}), ' class="news" title="Read this" required' ) self.assertEqual( flatatt({'class': "news", 'title': "Read this", 'required': False}), ' class="news" title="Read this"' ) self.assertEqual(flatatt({'class': None}), '') self.assertEqual(flatatt({}), '') def test_flatatt_no_side_effects(self): """ flatatt() does not modify the dict passed in. """ attrs = {'foo': 'bar', 'true': True, 'false': False} attrs_copy = copy.copy(attrs) self.assertEqual(attrs, attrs_copy) first_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, ' foo="bar" true') second_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, second_run) def test_validation_error(self): ################### # ValidationError # ################### # Can take a string. self.assertHTMLEqual( str(ErrorList(ValidationError("There was an error.").messages)), '<ul class="errorlist"><li>There was an error.</li></ul>' ) # Can take a unicode string. self.assertHTMLEqual( str(ErrorList(ValidationError("Not \u03C0.").messages)), '<ul class="errorlist"><li>Not π.</li></ul>' ) # Can take a lazy string. self.assertHTMLEqual( str(ErrorList(ValidationError(gettext_lazy("Error.")).messages)), '<ul class="errorlist"><li>Error.</li></ul>' ) # Can take a list. self.assertHTMLEqual( str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>' ) # Can take a dict. self.assertHTMLEqual( str(ErrorList(sorted(ValidationError({'error_1': "1. Error one.", 'error_2': "2. Error two."}).messages))), '<ul class="errorlist"><li>1. Error one.</li><li>2. Error two.</li></ul>' ) # Can take a mixture in a list. self.assertHTMLEqual( str(ErrorList(sorted(ValidationError([ "1. First error.", "2. Not \u03C0.", gettext_lazy("3. Error."), { 'error_1': "4. First dict error.", 'error_2': "5. Second dict error.", }, ]).messages))), '<ul class="errorlist">' '<li>1. First error.</li>' '<li>2. Not π.</li>' '<li>3. Error.</li>' '<li>4. First dict error.</li>' '<li>5. Second dict error.</li>' '</ul>' ) class VeryBadError: def __str__(self): return "A very bad error." # Can take a non-string. self.assertHTMLEqual( 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.assertHTMLEqual( 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.assertHTMLEqual( str(ErrorList([mark_safe(example)])), '<ul class="errorlist"><li>Example of link: ' '<a href="http://www.example.com/">example</a></li></ul>' ) self.assertHTMLEqual( str(ErrorDict({'name': example})), '<ul class="errorlist"><li>nameExample of link: ' '&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>' ) self.assertHTMLEqual( str(ErrorDict({'name': mark_safe(example)})), '<ul class="errorlist"><li>nameExample of link: ' '<a href="http://www.example.com/">example</a></li></ul>' ) def test_error_dict_copy(self): e = ErrorDict() e['__all__'] = ErrorList([ ValidationError( message='message %(i)s', params={'i': 1}, ), ValidationError( message='message %(i)s', params={'i': 2}, ), ]) e_copy = copy.copy(e) self.assertEqual(e, e_copy) self.assertEqual(e.as_data(), e_copy.as_data()) e_deepcopy = copy.deepcopy(e) self.assertEqual(e, e_deepcopy) def test_error_dict_html_safe(self): e = ErrorDict() e['username'] = 'Invalid username.' self.assertTrue(hasattr(ErrorDict, '__html__')) self.assertEqual(str(e), e.__html__()) def test_error_list_html_safe(self): e = ErrorList(['Invalid username.']) self.assertTrue(hasattr(ErrorList, '__html__')) self.assertEqual(str(e), e.__html__())
8a9206f535f3198b6aa9065b8b9106f51d78ccb8989f5dd036ff52512d2db49d
from django.contrib.admin.tests import AdminSeleniumTestCase from django.test import override_settings from django.urls import reverse from ..models import Article @override_settings(ROOT_URLCONF='forms_tests.urls') class LiveWidgetTests(AdminSeleniumTestCase): available_apps = ['forms_tests'] + AdminSeleniumTestCase.available_apps def test_textarea_trailing_newlines(self): """ A roundtrip on a ModelForm doesn't alter the TextField value """ article = Article.objects.create(content="\nTst\n") self.selenium.get(self.live_server_url + reverse('article_form', args=[article.pk])) self.selenium.find_element_by_id('submit').click() article = Article.objects.get(pk=article.pk) self.assertEqual(article.content, "\r\nTst\r\n")
96ee814d2ad971655f4338ac6c958ce6adbf0a256bbb31efd222206405ecbb7e
from django.forms import CharField, Form, Media, MultiWidget, TextInput from django.template import Context, Template from django.test import SimpleTestCase, override_settings @override_settings( STATIC_URL='http://media.example.com/static/', ) class FormsMediaTestCase(SimpleTestCase): """Tests for the media handling on widgets and forms""" 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>""" ) self.assertEqual( repr(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'])" ) 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/css1', '/path/to/css3') } 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="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # 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_deduplication(self): # A deduplication test applied directly to a Media object, to confirm # that the deduplication doesn't only happen at the point of merging # two or more media objects. media = Media( css={'all': ('/path/to/css1', '/path/to/css1')}, js=('/path/to/js1', '/path/to/js1'), ) self.assertEqual(str(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().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().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="/other/path" 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="/other/js"></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_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="/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"> <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="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></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="/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"> <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="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></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="/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"> <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="/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/css1', '/path/to/css3') } 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().__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="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></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/css1', '/path/to/css3') } 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="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></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="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></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="/some/form/css" 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="/some/form/javascript"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # Media works in templates 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="/some/form/javascript"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> <script type="text/javascript" src="/path/to/js4"></script> <script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> <link href="/some/form/css" 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">""" ) def test_html_safe(self): media = Media(css={'all': ['/path/to/css']}, js=['/path/to/js']) self.assertTrue(hasattr(Media, '__html__')) self.assertEqual(str(media), media.__html__()) def test_merge(self): test_values = ( (([1, 2], [3, 4]), [1, 3, 2, 4]), (([1, 2], [2, 3]), [1, 2, 3]), (([2, 3], [1, 2]), [1, 2, 3]), (([1, 3], [2, 3]), [1, 2, 3]), (([1, 2], [1, 3]), [1, 2, 3]), (([1, 2], [3, 2]), [1, 3, 2]), (([1, 2], [1, 2]), [1, 2]), ([[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]], [1, 5, 8, 2, 6, 3, 7, 9]), ((), []), (([1, 2],), [1, 2]), ) for lists, expected in test_values: with self.subTest(lists=lists): self.assertEqual(Media.merge(*lists), expected) def test_merge_warning(self): msg = 'Detected duplicate Media files in an opposite order: [1, 2], [2, 1]' with self.assertWarnsMessage(RuntimeWarning, msg): self.assertEqual(Media.merge([1, 2], [2, 1]), [1, 2]) def test_merge_js_three_way(self): """ The relative order of scripts is preserved in a three-way merge. """ widget1 = Media(js=['color-picker.js']) widget2 = Media(js=['text-editor.js']) widget3 = Media(js=['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) merged = widget1 + widget2 + widget3 self.assertEqual(merged._js, ['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) def test_merge_js_three_way2(self): # The merge prefers to place 'c' before 'b' and 'g' before 'h' to # preserve the original order. The preference 'c'->'b' is overridden by # widget3's media, but 'g'->'h' survives in the final ordering. widget1 = Media(js=['a', 'c', 'f', 'g', 'k']) widget2 = Media(js=['a', 'b', 'f', 'h', 'k']) widget3 = Media(js=['b', 'c', 'f', 'k']) merged = widget1 + widget2 + widget3 self.assertEqual(merged._js, ['a', 'b', 'c', 'f', 'g', 'h', 'k']) def test_merge_css_three_way(self): widget1 = Media(css={'screen': ['c.css'], 'all': ['d.css', 'e.css']}) widget2 = Media(css={'screen': ['a.css']}) widget3 = Media(css={'screen': ['a.css', 'b.css', 'c.css'], 'all': ['e.css']}) merged = widget1 + widget2 # c.css comes before a.css because widget1 + widget2 establishes this # order. self.assertEqual(merged._css, {'screen': ['c.css', 'a.css'], 'all': ['d.css', 'e.css']}) merged = merged + widget3 # widget3 contains an explicit ordering of c.css and a.css. self.assertEqual(merged._css, {'screen': ['a.css', 'b.css', 'c.css'], 'all': ['d.css', 'e.css']})
cb49e00554fff9491f1f78eca5bd87265b3b30d179518a679cbd229757d8fc75
import copy import datetime import json import uuid from django.core.exceptions import NON_FIELD_ERRORS from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import MaxValueValidator, RegexValidator from django.forms import ( BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField, DateTimeField, EmailField, FileField, FloatField, Form, HiddenInput, ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput, MultiValueField, NullBooleanField, PasswordInput, RadioSelect, Select, SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeField, ValidationError, forms, ) from django.forms.renderers import DjangoTemplates, get_default_renderer from django.forms.utils import ErrorList from django.http import QueryDict from django.template import Context, Template from django.test import SimpleTestCase from django.utils.datastructures import MultiValueDict from django.utils.safestring import mark_safe 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 MultiValueDictLike(dict): def getlist(self, key): return [self[key]] class FormsTestCase(SimpleTestCase): # 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': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertHTMLEqual(p.errors.as_ul(), '') self.assertEqual(p.errors.as_text(), '') self.assertEqual(p.cleaned_data["first_name"], 'John') self.assertEqual(p.cleaned_data["last_name"], 'Lennon') self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertHTMLEqual( str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" required>' ) self.assertHTMLEqual( str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" required>' ) self.assertHTMLEqual( str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required>' ) msg = "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, first_name, last_name." with self.assertRaisesMessage(KeyError, msg): p['nonexistentfield'] form_output = [] for boundfield in p: form_output.append(str(boundfield)) self.assertHTMLEqual( '\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" required> <input type="text" name="last_name" value="Lennon" id="id_last_name" required> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" required>""" ) form_output = [] for boundfield in p: form_output.append([boundfield.label, boundfield.data]) self.assertEqual(form_output, [ ['First name', 'John'], ['Last name', 'Lennon'], ['Birthday', '1940-10-9'] ]) self.assertHTMLEqual( 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" required></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" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></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'], ['This field is required.']) self.assertEqual(p.errors['last_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {}) self.assertHTMLEqual( 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" required></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" required></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" required></td></tr>""" ) self.assertHTMLEqual( 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" required></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" required></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" required></td></tr>""" ) self.assertHTMLEqual( 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" required></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" required></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" required></li>""" ) self.assertHTMLEqual( 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" required></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" required></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" required></p>""" ) def test_empty_querydict_args(self): data = QueryDict() files = QueryDict() p = Person(data, files) self.assertIs(p.data, data) self.assertIs(p.files, files) 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()) with self.assertRaises(AttributeError): p.cleaned_data self.assertHTMLEqual( str(p), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""" ) self.assertHTMLEqual( 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" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""" ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""" ) def test_unicode_values(self): # Unicode values are handled properly. p = Person({ 'first_name': 'John', 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9' }) self.assertHTMLEqual( p.as_table(), '<tr><th><label for="id_first_name">First name:</label></th><td>' '<input type="text" name="first_name" value="John" id="id_first_name" required></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" required></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" required></td></tr>' ) self.assertHTMLEqual( p.as_ul(), '<li><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" required></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" required></li>\n' '<li><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></li>' ) self.assertHTMLEqual( p.as_p(), '<p><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" required></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" required></p>\n' '<p><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></p>' ) p = Person({'last_name': 'Lennon'}) self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertFalse(p.is_valid()) self.assertEqual( p.errors, {'birthday': ['This field is required.'], 'first_name': ['This field is required.']} ) self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'}) self.assertEqual(p['first_name'].errors, ['This field is required.']) self.assertHTMLEqual( p['first_name'].errors.as_ul(), '<ul class="errorlist"><li>This field is required.</li></ul>' ) self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.') p = Person() self.assertHTMLEqual( str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" required>', ) self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" required>') self.assertHTMLEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" required>') 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': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9', 'extra1': 'hello', 'extra2': 'hello', } p = Person(data) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') self.assertEqual(p.cleaned_data['last_name'], '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': 'John', 'last_name': 'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['nick_name'], '') self.assertEqual(f.cleaned_data['first_name'], 'John') self.assertEqual(f.cleaned_data['last_name'], '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': 'John', 'last_name': 'Lennon'} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertIsNone(f.cleaned_data['birth_date']) self.assertEqual(f.cleaned_data['first_name'], 'John') self.assertEqual(f.cleaned_data['last_name'], '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.assertHTMLEqual( 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" required></td></tr> <tr><th><label for="last_name_id">Last name:</label></th><td> <input type="text" name="last_name" id="last_name_id" required></td></tr> <tr><th><label for="birthday_id">Birthday:</label></th><td> <input type="text" name="birthday" id="birthday_id" required></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></li> <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></li> <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></li>""" ) self.assertHTMLEqual( p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></p> <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></p> <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></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.assertHTMLEqual( p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></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.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></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.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></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.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""" ) def test_various_boolean_values(self): class SignupForm(Form): email = EmailField() get_spam = BooleanField() f = SignupForm(auto_id=False) self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" required>') self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required>') f = SignupForm({'email': '[email protected]', 'get_spam': True}, auto_id=False) self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" value="[email protected]" required>') self.assertHTMLEqual( str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required>', ) # 'True' or 'true' should be rendered without a value attribute f = SignupForm({'email': '[email protected]', 'get_spam': 'True'}, auto_id=False) self.assertHTMLEqual( str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required>', ) f = SignupForm({'email': '[email protected]', 'get_spam': 'true'}, auto_id=False) self.assertHTMLEqual( str(f['get_spam']), '<input checked type="checkbox" name="get_spam" required>') # A value of 'False' or 'false' should be rendered unchecked f = SignupForm({'email': '[email protected]', 'get_spam': 'False'}, auto_id=False) self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required>') f = SignupForm({'email': '[email protected]', 'get_spam': 'false'}, auto_id=False) self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" required>') # A value of '0' should be interpreted as a True value (#16820) f = SignupForm({'email': '[email protected]', 'get_spam': '0'}) self.assertTrue(f.is_valid()) self.assertTrue(f.cleaned_data.get('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.assertHTMLEqual(str(f['subject']), '<input type="text" name="subject" required>') self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="10" cols="40" required></textarea>') # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: self.assertHTMLEqual( f['subject'].as_textarea(), '<textarea name="subject" rows="10" cols="40" required></textarea>', ) self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required>') self.assertHTMLEqual(f['message'].as_hidden(), '<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.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="80" cols="20" required></textarea>') # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" required>') f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False) self.assertHTMLEqual( f['subject'].as_textarea(), '<textarea rows="10" cols="40" name="subject" required>Hello</textarea>' ) self.assertHTMLEqual( f['message'].as_text(), '<input type="text" name="message" value="I love you." required>', ) self.assertHTMLEqual(f['message'].as_hidden(), '<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.assertHTMLEqual(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.assertHTMLEqual(str(f['language']), """<select name="language"> <option value="P" 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. class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')]) f = FrameworkForm(auto_id=False) self.assertHTMLEqual(str(f['language']), """<select name="language" required> <option value="" 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.assertHTMLEqual(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.assertHTMLEqual(str(f['language']), """<select class="foo" name="language"> <option value="P" 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.assertHTMLEqual(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.assertHTMLEqual(str(f['language']), """<select class="foo" name="language"> <option value="P" 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.assertHTMLEqual(str(f['language']), """<select name="language"> </select>""") f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] self.assertHTMLEqual(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.assertHTMLEqual(str(f['language']), """<ul> <li><label><input type="radio" name="language" value="P" required> Python</label></li> <li><label><input type="radio" name="language" value="J" required> Java</label></li> </ul>""") self.assertHTMLEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required></td></tr> <tr><th>Language:</th><td><ul> <li><label><input type="radio" name="language" value="P" required> Python</label></li> <li><label><input type="radio" name="language" value="J" required> Java</label></li> </ul></td></tr>""") self.assertHTMLEqual(f.as_ul(), """<li>Name: <input type="text" name="name" required></li> <li>Language: <ul> <li><label><input type="radio" name="language" value="P" required> Python</label></li> <li><label><input type="radio" name="language" value="J" required> 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.assertHTMLEqual( str(f['language']), """<ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> 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.assertHTMLEqual( f.as_table(), """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" required></td></tr> <tr><th><label for="id_language_0">Language:</label></th><td><ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> Java</label></li> </ul></td></tr>""" ) self.assertHTMLEqual( f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li><label for="id_language_0">Language:</label> <ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> Java</label></li> </ul></li>""" ) self.assertHTMLEqual( f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p><label for="id_language_0">Language:</label> <ul id="id_language"> <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required> Python</label></li> <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required> Java</label></li> </ul></p>""" ) # Test iterating on individual radios in a template t = Template('{% for radio in form.language %}<div class="myradio">{{ radio }}</div>{% endfor %}') self.assertHTMLEqual( t.render(Context({'form': f})), """<div class="myradio"><label for="id_language_0"> <input id="id_language_0" name="language" type="radio" value="P" required> Python</label></div> <div class="myradio"><label for="id_language_1"> <input id="id_language_1" name="language" type="radio" value="J" required> Java</label></div>""" ) def test_form_with_iterable_boundfield(self): class BeatleForm(Form): name = ChoiceField( choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect, ) f = BeatleForm(auto_id=False) self.assertHTMLEqual( '\n'.join(str(bf) for bf in f['name']), """<label><input type="radio" name="name" value="john" required> John</label> <label><input type="radio" name="name" value="paul" required> Paul</label> <label><input type="radio" name="name" value="george" required> George</label> <label><input type="radio" name="name" value="ringo" required> Ringo</label>""" ) self.assertHTMLEqual( '\n'.join('<div>%s</div>' % bf for bf in f['name']), """<div><label><input type="radio" name="name" value="john" required> John</label></div> <div><label><input type="radio" name="name" value="paul" required> Paul</label></div> <div><label><input type="radio" name="name" value="george" required> George</label></div> <div><label><input type="radio" name="name" value="ringo" required> Ringo</label></div>""" ) def test_form_with_iterable_boundfield_id(self): class BeatleForm(Form): name = ChoiceField( choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect, ) fields = list(BeatleForm()['name']) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, 'id_name_0') self.assertEqual(fields[0].choice_label, 'John') self.assertHTMLEqual( fields[0].tag(), '<input type="radio" name="name" value="john" id="id_name_0" required>' ) self.assertHTMLEqual( str(fields[0]), '<label for="id_name_0"><input type="radio" name="name" ' 'value="john" id="id_name_0" required> John</label>' ) self.assertEqual(fields[1].id_for_label, 'id_name_1') self.assertEqual(fields[1].choice_label, 'Paul') self.assertHTMLEqual( fields[1].tag(), '<input type="radio" name="name" value="paul" id="id_name_1" required>' ) self.assertHTMLEqual( str(fields[1]), '<label for="id_name_1"><input type="radio" name="name" ' 'value="paul" id="id_name_1" required> Paul</label>' ) def test_iterable_boundfield_select(self): class BeatleForm(Form): name = ChoiceField(choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')]) fields = list(BeatleForm(auto_id=False)['name']) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, 'id_name_0') self.assertEqual(fields[0].choice_label, 'John') self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>') self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>') def test_form_with_noniterable_boundfield(self): # You can iterate over any BoundField, not just those with widget=RadioSelect. class BeatleForm(Form): name = CharField() f = BeatleForm(auto_id=False) self.assertHTMLEqual('\n'.join(str(bf) for bf in f['name']), '<input type="text" name="name" required>') def test_boundfield_slice(self): class BeatleForm(Form): name = ChoiceField( choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect, ) f = BeatleForm() bf = f['name'] self.assertEqual( [str(item) for item in bf[1:]], [str(bf[1]), str(bf[2]), str(bf[3])], ) def test_boundfield_bool(self): """BoundField without any choices (subwidgets) evaluates to True.""" class TestForm(Form): name = ChoiceField(choices=[]) self.assertIs(bool(TestForm()['name']), True) def test_forms_with_multiple_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.assertHTMLEqual(str(f['composers']), """<select multiple name="composers" required> </select>""") class SongForm(Form): name = CharField() composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) f = SongForm(auto_id=False) self.assertHTMLEqual(str(f['composers']), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P">Paul McCartney</option> </select>""") f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) self.assertHTMLEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" required>') self.assertHTMLEqual(str(f['composers']), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P" selected>Paul McCartney</option> </select>""") def test_form_with_disabled_fields(self): class PersonForm(Form): name = CharField() birthday = DateField(disabled=True) class PersonFormFieldInitial(Form): name = CharField() birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16)) # Disabled fields are generally not transmitted by user agents. # The value from the form's initial data is used. f1 = PersonForm({'name': 'John Doe'}, initial={'birthday': datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial({'name': 'John Doe'}) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'} ) # Values provided in the form's data are ignored. data = {'name': 'John Doe', 'birthday': '1984-11-10'} f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {'birthday': datetime.date(1974, 8, 16), 'name': 'John Doe'} ) # Initial data remains present on invalid forms. data = {} f1 = PersonForm(data, initial={'birthday': datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertFalse(form.is_valid()) self.assertEqual(form['birthday'].value(), datetime.date(1974, 8, 16)) 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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual( str(f['when']), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" required>' '<input type="text" name="when_1" value="01:01" id="id_when_1" required>' ) self.assertHTMLEqual( 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_multiple_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.assertHTMLEqual(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.assertHTMLEqual(str(f['composers']), """<ul> <li><label><input 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.assertHTMLEqual(str(f['composers']), """<ul> <li><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></li> <li><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></li> </ul>""") # Test iterating on individual checkboxes in a template t = Template('{% for checkbox in form.composers %}<div class="mycheckbox">{{ checkbox }}</div>{% endfor %}') self.assertHTMLEqual(t.render(Context({'form': f})), """<div class="mycheckbox"><label> <input checked name="composers" type="checkbox" value="J"> John Lennon</label></div> <div class="mycheckbox"><label> <input checked name="composers" type="checkbox" value="P"> Paul McCartney</label></div>""") 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.assertHTMLEqual( str(f['composers']), """<ul id="composers_id"> <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 and # MultiValueDict 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({'name': ['Yesterday'], 'composers': ['J', 'P']}) f = SongForm(data) self.assertEqual(f.errors, {}) # SelectMultiple uses ducktyping so that MultiValueDictLike.getlist() # is called. f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J']) 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({'name': ['Yesterday'], 'composers': ['J', 'P']}), auto_id=False) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" required> <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'], ['This field is required.']) f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J']) self.assertEqual(f.cleaned_data['name'], 'Yesterday') f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J', 'P']) self.assertEqual(f.cleaned_data['name'], 'Yesterday') # MultipleHiddenInput uses ducktyping so that # MultiValueDictLike.getlist() is called. f = SongForm(MultiValueDictLike({'name': 'Yesterday', 'composers': 'J'})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['composers'], ['J']) 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.assertHTMLEqual( f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"><li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul> <input type="text" name="special_name" value="Nothing to escape" required></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" required></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.assertHTMLEqual( f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"><li>Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul> <input type="text" name="special_name" value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required></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;" required></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('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'], ['This field is required.']) self.assertEqual(f.errors['password1'], ['This field is required.']) self.assertEqual(f.errors['password2'], ['This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) self.assertEqual(f.errors['password2'], ['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'], 'adrian') self.assertEqual(f.cleaned_data['password1'], 'foo') self.assertEqual(f.cleaned_data['password2'], 'foo') # Another way of doing multiple-field validation is by implementing the # Form's clean() method. Usually ValidationError raised by that method # will not be associated with a particular field and will have a # special-case association with the field named '__all__'. It's # possible to associate the errors to particular field with the # Form.add_error() method or by passing a dictionary that maps each # field to one or more errors. # # 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): # Test raising a ValidationError as NON_FIELD_ERRORS. if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']): raise ValidationError('Please make sure your passwords match.') # Test raising ValidationError that targets multiple fields. errors = {} if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE': errors['password1'] = 'Forbidden value.' if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE': errors['password2'] = ['Forbidden value.'] if errors: raise ValidationError(errors) # Test Form.add_error() if self.cleaned_data.get('password1') == 'FORBIDDEN_VALUE2': self.add_error(None, 'Non-field error 1.') self.add_error('password1', 'Forbidden value 2.') if self.cleaned_data.get('password2') == 'FORBIDDEN_VALUE2': self.add_error('password2', 'Forbidden value 2.') raise ValidationError('Non-field error 2.') return self.cleaned_data f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertHTMLEqual( 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" required></td></tr> <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password2" required></td></tr>""" ) self.assertEqual(f.errors['username'], ['This field is required.']) self.assertEqual(f.errors['password1'], ['This field is required.']) self.assertEqual(f.errors['password2'], ['This field is required.']) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.']) self.assertHTMLEqual( f.as_table(), """<tr><td colspan="2"> <ul class="errorlist nonfield"><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" required></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr>""" ) self.assertHTMLEqual( f.as_ul(), """<li><ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></li> <li>Username: <input type="text" name="username" value="adrian" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Password2: <input type="password" name="password2" required></li>""" ) f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['username'], 'adrian') self.assertEqual(f.cleaned_data['password1'], 'foo') self.assertEqual(f.cleaned_data['password2'], 'foo') f = UserRegistration({ 'username': 'adrian', 'password1': 'FORBIDDEN_VALUE', 'password2': 'FORBIDDEN_VALUE', }, auto_id=False) self.assertEqual(f.errors['password1'], ['Forbidden value.']) self.assertEqual(f.errors['password2'], ['Forbidden value.']) f = UserRegistration({ 'username': 'adrian', 'password1': 'FORBIDDEN_VALUE2', 'password2': 'FORBIDDEN_VALUE2', }, auto_id=False) self.assertEqual(f.errors['__all__'], ['Non-field error 1.', 'Non-field error 2.']) self.assertEqual(f.errors['password1'], ['Forbidden value 2.']) self.assertEqual(f.errors['password2'], ['Forbidden value 2.']) with self.assertRaisesMessage(ValueError, "has no field named"): f.add_error('missing_field', 'Some error.') def test_update_error_dict(self): class CodeForm(Form): code = CharField(max_length=10) def clean(self): try: raise ValidationError({'code': [ValidationError('Code error 1.')]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({'code': [ValidationError('Code error 2.')]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({'code': forms.ErrorList(['Code error 3.'])}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError('Non-field error 1.') except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError([ValidationError('Non-field error 2.')]) except ValidationError as e: self._errors = e.update_error_dict(self._errors) # The newly added list of errors is an instance of ErrorList. for field, error_list in self._errors.items(): if not isinstance(error_list, self.error_class): self._errors[field] = self.error_class(error_list) form = CodeForm({'code': 'hello'}) # Trigger validation. self.assertFalse(form.is_valid()) # update_error_dict didn't lose track of the ErrorDict type. self.assertIsInstance(form._errors, forms.ErrorDict) self.assertEqual(dict(form.errors), { 'code': ['Code error 1.', 'Code error 2.', 'Code error 3.'], NON_FIELD_ERRORS: ['Non-field error 1.', 'Non-field error 2.'], }) def test_has_error(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput, min_length=5) 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( 'Please make sure your passwords match.', code='password_mismatch', ) f = UserRegistration(data={}) self.assertTrue(f.has_error('password1')) self.assertTrue(f.has_error('password1', 'required')) self.assertFalse(f.has_error('password1', 'anything')) f = UserRegistration(data={'password1': 'Hi', 'password2': 'Hi'}) self.assertTrue(f.has_error('password1')) self.assertTrue(f.has_error('password1', 'min_length')) self.assertFalse(f.has_error('password1', 'anything')) self.assertFalse(f.has_error('password2')) self.assertFalse(f.has_error('password2', 'anything')) f = UserRegistration(data={'password1': 'Bonjour', 'password2': 'Hello'}) self.assertFalse(f.has_error('password1')) self.assertFalse(f.has_error('password1', 'required')) self.assertTrue(f.has_error(NON_FIELD_ERRORS)) self.assertTrue(f.has_error(NON_FIELD_ERRORS, 'password_mismatch')) self.assertFalse(f.has_error(NON_FIELD_ERRORS, 'anything')) 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().__init__(*args, **kwargs) self.fields['birthday'] = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th><td><input type="text" name="birthday" required></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.assertHTMLEqual( my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""" ) field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></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.assertHTMLEqual( my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr> <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""" ) field_list = [('field3', CharField()), ('field4', CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></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().__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': 'reuired'}, {'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().__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)) # Similarly, choices do not persist from one Form instance to the next. # Refs #15127. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male'))) def __init__(self, allow_unspec_gender=False, *args, **kwargs): super().__init__(*args, **kwargs) if allow_unspec_gender: self.fields['gender'].choices += (('u', 'Unspecified'),) f = Person() self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')]) f = Person(allow_unspec_gender=True) self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')]) f = Person() self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')]) def test_validators_independence(self): """ The list of form field validators can be modified without polluting other forms. """ class MyForm(Form): myfield = CharField(max_length=25) f1 = MyForm() f2 = MyForm() f1.fields['myfield'].validators[0] = MaxValueValidator(12) self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0]) 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.assertHTMLEqual( p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th> <td><input type="text" name="birthday" required><input type="hidden" name="hidden_text"></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required><input type="hidden" name="hidden_text"></li>""" ) self.assertHTMLEqual( p.as_p(), """<p>First name: <input type="text" name="first_name" required></p> <p>Last name: <input type="text" name="last_name" required></p> <p>Birthday: <input type="text" name="birthday" required><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.assertHTMLEqual( 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" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></li>""" ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <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.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"> <ul class="errorlist nonfield"><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" required></td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" required></td></tr> <tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></td></tr>""" ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li> <li>First name: <input type="text" name="first_name" value="John" required></li> <li>Last name: <input type="text" name="last_name" value="Lennon" required></li> <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></li>""" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul> <p>First name: <input type="text" name="first_name" value="John" required></p> <p>Last name: <input type="text" name="last_name" value="Lennon" required></p> <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <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.assertHTMLEqual(p.as_table(), '<input type="hidden" name="foo"><input type="hidden" name="bar">') self.assertHTMLEqual(p.as_ul(), '<input type="hidden" name="foo"><input type="hidden" name="bar">') self.assertHTMLEqual(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.assertHTMLEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> <tr><th>Field5:</th><td><input type="text" name="field5" required></td></tr> <tr><th>Field6:</th><td><input type="text" name="field6" required></td></tr> <tr><th>Field7:</th><td><input type="text" name="field7" required></td></tr> <tr><th>Field8:</th><td><input type="text" name="field8" required></td></tr> <tr><th>Field9:</th><td><input type="text" name="field9" required></td></tr> <tr><th>Field10:</th><td><input type="text" name="field10" required></td></tr> <tr><th>Field11:</th><td><input type="text" name="field11" required></td></tr> <tr><th>Field12:</th><td><input type="text" name="field12" required></td></tr> <tr><th>Field13:</th><td><input type="text" name="field13" required></td></tr> <tr><th>Field14:</th><td><input type="text" name="field14" required></td></tr>""") def test_explicit_field_order(self): class TestFormParent(Form): field1 = CharField() field2 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field_order = ['field6', 'field5', 'field4', 'field2', 'field1'] class TestForm(TestFormParent): field3 = CharField() field_order = ['field2', 'field4', 'field3', 'field5', 'field6'] class TestFormRemove(TestForm): field1 = None class TestFormMissing(TestForm): field_order = ['field2', 'field4', 'field3', 'field5', 'field6', 'field1'] field1 = None class TestFormInit(TestFormParent): field3 = CharField() field_order = None def __init__(self, **kwargs): super().__init__(**kwargs) self.order_fields(field_order=TestForm.field_order) p = TestFormParent() self.assertEqual(list(p.fields), TestFormParent.field_order) p = TestFormRemove() self.assertEqual(list(p.fields), TestForm.field_order) p = TestFormMissing() self.assertEqual(list(p.fields), TestForm.field_order) p = TestForm() self.assertEqual(list(p.fields), TestFormMissing.field_order) p = TestFormInit() order = [*TestForm.field_order, 'field1'] self.assertEqual(list(p.fields), order) TestForm.field_order = ['unknown'] p = TestForm() self.assertEqual(list(p.fields), ['field1', 'field2', 'field4', 'field5', 'field6', 'field3']) 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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" maxlength="10" required></li> <li>Realname: <input type="text" name="realname" maxlength="10" required></li> <li>Address: <input type="text" name="address" required></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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" maxlength="10" required></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='Contraseña (de nuevo)') p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Contraseña (de nuevo): <input type="password" name="password2" required></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.assertHTMLEqual( Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" required></p> <p>What is your name? <input type="text" name="q2" required></p> <p>The answer to life is: <input type="text" name="q3" required></p> <p>Answer this question! <input type="text" name="q4" required></p> <p>The last question. Period. <input type="text" name="q5" required></p>""" ) self.assertHTMLEqual( Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p> <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p> <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p> <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p> <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p>""" ) # 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.assertHTMLEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""") p = UserRegistration(auto_id='id_%s') self.assertHTMLEqual( p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) p = UserRegistration(auto_id='id_%s') self.assertHTMLEqual( p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></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') answer = CharField(label='Secret answer', label_suffix=' =') f = FavoriteForm(auto_id=False) self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal: <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""") f = FavoriteForm(auto_id=False, label_suffix='?') self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal? <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""") f = FavoriteForm(auto_id=False, label_suffix='') self.assertHTMLEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""") f = FavoriteForm(auto_id=False, label_suffix='\u2192') self.assertHTMLEqual( f.as_ul(), '<li>Favorite color? <input type="text" name="color" required></li>\n' '<li>Favorite animal\u2192 <input type="text" name="animal" required></li>\n' '<li>Secret answer = <input type="text" name="answer" required></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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': ''}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': 'foo'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></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'], ['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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) p = UserRegistration(initial={'username': 'stephane'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""" ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': ''}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""" ) p = UserRegistration({'username': 'foo'}, initial={'username': 'django'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></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'], ['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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" 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.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""" ) p = UserRegistration({'username': ''}, initial={'username': initial_django}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""" ) p = UserRegistration( {'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" 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'], ['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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b" selected>bar</option> <option value="w" selected>whiz</option> </select></li>""" ) p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li>""" ) def test_get_initial_for_field(self): class PersonForm(Form): first_name = CharField(initial='John') last_name = CharField(initial='Doe') age = IntegerField() occupation = CharField(initial=lambda: 'Unknown') form = PersonForm(initial={'first_name': 'Jane'}) self.assertEqual(form.get_initial_for_field(form.fields['age'], 'age'), None) self.assertEqual(form.get_initial_for_field(form.fields['last_name'], 'last_name'), 'Doe') # Form.initial overrides Field.initial. self.assertEqual(form.get_initial_for_field(form.fields['first_name'], 'first_name'), 'Jane') # Callables are evaluated. self.assertEqual(form.get_initial_for_field(form.fields['occupation'], 'occupation'), 'Unknown') def test_changed_data(self): class Person(Form): first_name = CharField(initial='Hans') last_name = CharField(initial='Greatel') birthday = DateField(initial=datetime.date(1974, 8, 16)) p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16'}) self.assertTrue(p.is_valid()) self.assertNotIn('first_name', p.changed_data) self.assertIn('last_name', p.changed_data) self.assertNotIn('birthday', p.changed_data) # A field raising ValidationError is always in changed_data class PedanticField(forms.Field): def to_python(self, value): raise ValidationError('Whatever') class Person2(Person): pedantic = PedanticField(initial='whatever', show_hidden_initial=True) p = Person2(data={ 'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16', 'initial-pedantic': 'whatever', }) self.assertFalse(p.is_valid()) self.assertIn('pedantic', p.changed_data) 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.assertIsNone(bound['username'].value()) self.assertEqual(unbound['username'].value(), 'djangonaut') self.assertEqual(bound['password'].value(), 'foo') self.assertIsNone(unbound['password'].value()) def test_boundfield_initial_called_once(self): """ Multiple calls to BoundField().value() in an unbound form should return the same result each time (#24391). """ class MyForm(Form): name = CharField(max_length=10, initial=uuid.uuid4) form = MyForm() name = form['name'] self.assertEqual(name.value(), name.value()) # BoundField is also cached self.assertIs(form['name'], name) def test_boundfield_value_disabled_callable_initial(self): class PersonForm(Form): name = CharField(initial=lambda: 'John Doe', disabled=True) # Without form data. form = PersonForm() self.assertEqual(form['name'].value(), 'John Doe') # With form data. As the field is disabled, the value should not be # affected by the form data. form = PersonForm({}) self.assertEqual(form['name'].value(), 'John Doe') def test_custom_boundfield(self): class CustomField(CharField): def get_bound_field(self, form, name): return (form, name) class SampleForm(Form): name = CustomField() f = SampleForm() self.assertEqual(f['name'], (f, 'name')) def test_initial_datetime_values(self): now = datetime.datetime.now() # Nix microseconds (since they should be ignored). #22502 now_no_ms = now.replace(microsecond=0) if now == now_no_ms: now = now.replace(microsecond=1) def delayed_now(): return now def delayed_now_time(): return now.time() class HiddenInputWithoutMicrosec(HiddenInput): supports_microseconds = False class TextInputWithoutMicrosec(TextInput): supports_microseconds = False class DateTimeForm(Form): auto_timestamp = DateTimeField(initial=delayed_now) auto_time_only = TimeField(initial=delayed_now_time) supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput) hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput) hi_without_microsec = DateTimeField(initial=delayed_now, widget=HiddenInputWithoutMicrosec) ti_without_microsec = DateTimeField(initial=delayed_now, widget=TextInputWithoutMicrosec) unbound = DateTimeForm() self.assertEqual(unbound['auto_timestamp'].value(), now_no_ms) self.assertEqual(unbound['auto_time_only'].value(), now_no_ms.time()) self.assertEqual(unbound['supports_microseconds'].value(), now) self.assertEqual(unbound['hi_default_microsec'].value(), now) self.assertEqual(unbound['hi_without_microsec'].value(), now_no_ms) self.assertEqual(unbound['ti_without_microsec'].value(), now_no_ms) def test_datetime_clean_initial_callable_disabled(self): now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456) class DateTimeForm(forms.Form): dt = DateTimeField(initial=lambda: now, disabled=True) form = DateTimeForm({}) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {'dt': now}) def test_datetime_changed_data_callable_with_microseconds(self): class DateTimeForm(forms.Form): dt = DateTimeField(initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True) form = DateTimeForm({'dt': '2006-10-25 14:30:45'}) self.assertEqual(form.changed_data, []) 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='Wählen Sie mit Bedacht.') p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""" ) self.assertHTMLEqual( p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></p> <p>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required><br> <span class="helptext">e.g., [email protected]</span></td></tr> <tr><th>Password:</th><td><input type="password" name="password" required><br> <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""" ) # The help text is displayed whether or not data is provided for the form. p = UserRegistration({'username': 'foo'}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required> <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" required> <span class="helptext">Wählen Sie mit Bedacht.</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.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <input type="hidden" name="next" value="/"></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.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""" ) m = Musician(auto_id=False) self.assertHTMLEqual( m.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Instrument: <input type="text" name="instrument" required></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.assertHTMLEqual(b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required></li> <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Haircut type: <input type="text" name="haircut_type" required></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': 'John', 'person1-last_name': 'Lennon', 'person1-birthday': '1940-10-9' } p = Person(data, prefix='person1') self.assertHTMLEqual( 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" required></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" required></li> <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li>""" ) self.assertHTMLEqual( str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required>' ) self.assertHTMLEqual( str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required>' ) self.assertHTMLEqual( str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required>' ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') self.assertEqual(p.cleaned_data['last_name'], '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': '', 'person1-last_name': '', 'person1-birthday': '' } p = Person(data, prefix='person1') self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['last_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) self.assertEqual(p['first_name'].errors, ['This field is required.']) # Accessing a nonexistent field. with self.assertRaises(KeyError): p['person1-first_name'].errors # 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': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9' } p = Person(data, prefix='person1') self.assertEqual(p.errors['first_name'], ['This field is required.']) self.assertEqual(p.errors['last_name'], ['This field is required.']) self.assertEqual(p.errors['birthday'], ['This field is required.']) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { 'person1-first_name': 'John', 'person1-last_name': 'Lennon', 'person1-birthday': '1940-10-9', 'person2-first_name': 'Jim', 'person2-last_name': 'Morrison', 'person2-birthday': '1943-12-8' } p1 = Person(data, prefix='person1') self.assertTrue(p1.is_valid()) self.assertEqual(p1.cleaned_data['first_name'], 'John') self.assertEqual(p1.cleaned_data['last_name'], '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'], 'Jim') self.assertEqual(p2.cleaned_data['last_name'], '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 '%s-prefix-%s' % (self.prefix, field_name) if self.prefix else field_name p = Person(prefix='foo') self.assertHTMLEqual( 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" required></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" required></li> <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li>""" ) data = { 'foo-prefix-first_name': 'John', 'foo-prefix-last_name': 'Lennon', 'foo-prefix-birthday': '1940-10-9' } p = Person(data, prefix='foo') self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data['first_name'], 'John') self.assertEqual(p.cleaned_data['last_name'], 'Lennon') self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) def test_class_prefix(self): # Prefix can be also specified at the class level. class Person(Form): first_name = CharField() prefix = 'foo' p = Person() self.assertEqual(p.prefix, 'foo') p = Person(prefix='bar') self.assertEqual(p.prefix, 'bar') 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': 'Joe'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': '1'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': '2'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': '3'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': True}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': False}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': 'unknown'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': 'true'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""") p = Person({'name': 'Joe', 'is_cool': 'false'}, auto_id=False) self.assertHTMLEqual(str(p['is_cool']), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" 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.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>', ) f = FileForm(data={}, files={}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="file" name="file1" required></td></tr>' ) f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'')}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td>' '<ul class="errorlist"><li>The submitted file is empty.</li></ul>' '<input type="file" name="file1" required></td></tr>' ) f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False) self.assertHTMLEqual( 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" required></td></tr>' ) f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', b'some content')}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>', ) self.assertTrue(f.is_valid()) file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode()) f = FileForm(data={}, files={'file1': file1}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>', ) # A required file field with initial data should not contain the # required HTML attribute. The file input is left blank by the user to # keep the existing, initial value. f = FileForm(initial={'file1': 'resume.txt'}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_filefield_initial_callable(self): class FileForm(forms.Form): file1 = forms.FileField(initial=lambda: 'resume.txt') f = FileForm({}) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data['file1'], 'resume.txt') 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('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' % sorted(form.cleaned_data.items()) t = Template( '<form method="post">\n' '<table>\n{{ form }}\n</table>\n<input type="submit" required>\n</form>' ) return t.render(Context({'form': form})) # Case 1: GET (an empty form, with no errors).) self.assertHTMLEqual(my_function('GET', {}), """<form method="post"> <table> <tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr> </table> <input type="submit" required> </form>""") # Case 2: POST with erroneous data (a redisplayed form, with errors).) self.assertHTMLEqual( my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form method="post"> <table> <tr><td colspan="2"><ul class="errorlist nonfield"><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" required></td></tr> <tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr> </table> <input type="submit" required> </form>""" ) # Case 3: POST with valid data (the success message).) self.assertEqual( my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: [('password1', 'secret'), ('password2', 'secret'), ('username', 'adrian')]" ) 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('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> {{ 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" required> </form>''') self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p><label>Your username: <input type="text" name="username" maxlength="10" required></label></p> <p><label>Password: <input type="password" name="password1" required></label></p> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </form>""") self.assertHTMLEqual( t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required></label></p> <ul class="errorlist"><li>This field is required.</li></ul><p> <label>Password: <input type="password" name="password1" required></label></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </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> <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" required> </form>''') self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p><label>Username: <input type="text" name="username" maxlength="10" required></label></p> <p><label>Password1: <input type="password" name="password1" required></label></p> <p><label>Password2: <input type="password" name="password2" required></label></p> <input type="submit" required> </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> <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" required> </form>''') self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p>Username: <input type="text" name="username" maxlength="10" required></p> <p>Password1: <input type="password" name="password1" required></p> <p>Password2: <input type="password" name="password2" required></p> <input type="submit" required> </form>""") self.assertHTMLEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form> <p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></p> <p><label for="id_password1">Password1:</label> <input type="password" name="password1" id="id_password1" required></p> <p><label for="id_password2">Password2:</label> <input type="password" name="password2" id="id_password2" required></p> <input type="submit" required> </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> <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" required> </form>''') self.assertHTMLEqual( t.render(Context({'form': UserRegistration(auto_id=False)})), """<form> <p>Username: <input type="text" name="username" maxlength="10" required><br> Good luck picking a username that doesn&#x27;t already exist.</p> <p>Password1: <input type="password" name="password1" required></p> <p>Password2: <input type="password" name="password2" required></p> <input type="submit" required> </form>""" ) self.assertEqual( Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), '' ) # 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> {{ 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" required> </form>''') self.assertHTMLEqual( t.render(Context({ 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) })), """<form> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required></label></p> <p><label>Password: <input type="password" name="password1" required></label></p> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </form>""" ) t = Template('''<form> {{ 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" required> </form>''') self.assertHTMLEqual( t.render(Context({ 'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) })), """<form> <ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul> <p><label>Your username: <input type="text" name="username" value="django" maxlength="10" required></label></p> <p><label>Password: <input type="password" name="password1" required></label></p> <p><label>Password (again): <input type="password" name="password2" required></label></p> <input type="submit" required> </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 # argument 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': ['This field is required.'], 'artist': ['This field is required.']}) self.assertEqual(form.cleaned_data, {}) # Now let's show what happens when empty_permitted=True and the form is empty. form = SongForm(data, empty_permitted=True, use_required_attribute=False) 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': ['This field is required.']}) self.assertEqual(form.cleaned_data, {'artist': 'The Doors'}) # 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, use_required_attribute=False) 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, use_required_attribute=False) self.assertTrue(form.is_valid()) def test_empty_permitted_and_use_required_attribute(self): msg = ( 'The empty_permitted and use_required_attribute arguments may not ' 'both be True.' ) with self.assertRaisesMessage(ValueError, msg): Person(empty_permitted=True, use_required_attribute=True) 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.assertHTMLEqual( MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th>' '<td><input id="id_field1" type="text" name="field1" maxlength="50" required>' '<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.assertHTMLEqual( p.as_ul(), """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li class="required"><label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></li> <li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li> <li class="required error"><ul class="errorlist"><li>This field is required.</li></ul> <label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p class="required"><label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></p> <p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p> <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr class="required error"> <th><label class="required" 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" required></td></tr> <tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th> <td><select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></td></tr> <tr><th><label for="id_email">Email:</label></th><td> <input type="email" name="email" id="id_email"></td></tr> <tr class="required error"><th><label class="required" for="id_age">Age:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="number" name="age" id="id_age" required></td></tr>""" ) def test_label_has_required_css_class(self): """ #17922 - required_css_class is added to the label_tag() of required fields. """ class SomeForm(Form): required_css_class = 'required' field = CharField(max_length=10) field2 = IntegerField(required=False) f = SomeForm({'field': 'test'}) self.assertHTMLEqual(f['field'].label_tag(), '<label for="id_field" class="required">Field:</label>') self.assertHTMLEqual( f['field'].label_tag(attrs={'class': 'foo'}), '<label for="id_field" class="foo required">Field:</label>' ) self.assertHTMLEqual(f['field2'].label_tag(), '<label for="id_field2">Field2:</label>') def test_label_split_datetime_not_displayed(self): class EventForm(Form): happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) form = EventForm() self.assertHTMLEqual( form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0">' '<input type="hidden" name="happened_at_1" id="id_happened_at_1">' ) def test_multivalue_field_validation(self): def bad_names(value): if value == 'bad value': raise ValidationError('bad value not allowed') class NameField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (CharField(label='First name', max_length=10), CharField(label='Last name', max_length=10)) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return ' '.join(data_list) class NameForm(Form): name = NameField(validators=[bad_names]) form = NameForm(data={'name': ['bad', 'value']}) form.full_clean() self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {'name': ['bad value not allowed']}) form = NameForm(data={'name': ['should be overly', 'long for the field names']}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { 'name': [ 'Ensure this value has at most 10 characters (it has 16).', 'Ensure this value has at most 10 characters (it has 24).', ], } ) form = NameForm(data={'name': ['fname', 'lname']}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {'name': 'fname lname'}) def test_multivalue_deep_copy(self): """ #19298 -- MultiValueField needs to override the default as it needs to deep-copy subfields: """ class ChoicesField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( ChoiceField(label='Rank', choices=((1, 1), (2, 2))), CharField(label='Name', max_length=10), ) super().__init__(fields=fields, *args, **kwargs) field = ChoicesField() field2 = copy.deepcopy(field) self.assertIsInstance(field2, ChoicesField) self.assertIsNot(field2.fields, field.fields) self.assertIsNot(field2.fields[0].choices, field.fields[0].choices) def test_multivalue_initial_data(self): """ #23674 -- invalid initial data should not break form.changed_data() """ class DateAgeField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (DateField(label="Date"), IntegerField(label="Age")) super().__init__(fields=fields, *args, **kwargs) class DateAgeForm(Form): date_age = DateAgeField() data = {"date_age": ["1998-12-06", 16]} form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]}) self.assertTrue(form.has_changed()) def test_multivalue_optional_subfields(self): class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = ( CharField(label='Country Code', validators=[ RegexValidator(r'^\+[0-9]{1,2}$', message='Enter a valid country code.')]), CharField(label='Phone Number'), CharField(label='Extension', error_messages={'incomplete': 'Enter an extension.'}), CharField(label='Label', required=False, help_text='E.g. home, work.'), ) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return '%s.%s ext. %s (label: %s)' % tuple(data_list) return None # An empty value for any field will raise a `required` error on a # required `MultiValueField`. f = PhoneField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(['+61']) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(['+61', '287654321', '123']) self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home'])) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) # Empty values for fields will NOT raise a `required` error on an # optional `MultiValueField` f = PhoneField(required=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) self.assertEqual('+61. ext. (label: )', f.clean(['+61'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home'])) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) # For a required `MultiValueField` with `require_all_fields=False`, a # `required` error will only be raised if all fields are empty. Fields # can individually be required or optional. An empty value for any # required field will raise an `incomplete` error. f = PhoneField(require_all_fields=False) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean('') with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"): f.clean(['', '', '', 'Home']) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) # For an optional `MultiValueField` with `require_all_fields=False`, we # don't get any `required` error but we still get `incomplete` errors. f = PhoneField(required=False, require_all_fields=False) self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"): f.clean(['', '', '', 'Home']) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) def test_custom_empty_values(self): """ Form fields can customize what is considered as an empty value for themselves (#19997). """ class CustomJSONField(CharField): empty_values = [None, ''] def to_python(self, value): # Fake json.loads if value == '{}': return {} return super().to_python(value) class JSONForm(forms.Form): json = CustomJSONField() form = JSONForm(data={'json': '{}'}) form.full_clean() self.assertEqual(form.cleaned_data, {'json': {}}) def test_boundfield_label_tag(self): class SomeForm(Form): field = CharField() boundfield = SomeForm()['field'] testcases = [ # (args, kwargs, expected) # without anything: just print the <label> ((), {}, '<label for="id_field">Field:</label>'), # passing just one argument: overrides the field's label (('custom',), {}, '<label for="id_field">custom:</label>'), # the overridden label is escaped (('custom&',), {}, '<label for="id_field">custom&amp;:</label>'), ((mark_safe('custom&'),), {}, '<label for="id_field">custom&:</label>'), # Passing attrs to add extra attributes on the <label> ((), {'attrs': {'class': 'pretty'}}, '<label for="id_field" class="pretty">Field:</label>') ] for args, kwargs, expected in testcases: with self.subTest(args=args, kwargs=kwargs): self.assertHTMLEqual(boundfield.label_tag(*args, **kwargs), expected) def test_boundfield_label_tag_no_id(self): """ If a widget has no id, label_tag just returns the text with no surrounding <label>. """ class SomeForm(Form): field = CharField() boundfield = SomeForm(auto_id='')['field'] self.assertHTMLEqual(boundfield.label_tag(), 'Field:') self.assertHTMLEqual(boundfield.label_tag('Custom&'), 'Custom&amp;:') def test_boundfield_label_tag_custom_widget_id_for_label(self): class CustomIdForLabelTextInput(TextInput): def id_for_label(self, id): return 'custom_' + id class EmptyIdForLabelTextInput(TextInput): def id_for_label(self, id): return None class SomeForm(Form): custom = CharField(widget=CustomIdForLabelTextInput) empty = CharField(widget=EmptyIdForLabelTextInput) form = SomeForm() self.assertHTMLEqual(form['custom'].label_tag(), '<label for="custom_id_custom">Custom:</label>') self.assertHTMLEqual(form['empty'].label_tag(), '<label>Empty:</label>') def test_boundfield_empty_label(self): class SomeForm(Form): field = CharField(label='') boundfield = SomeForm()['field'] self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>') def test_boundfield_id_for_label(self): class SomeForm(Form): field = CharField(label='') self.assertEqual(SomeForm()['field'].id_for_label, 'id_field') def test_boundfield_id_for_label_override_by_attrs(self): """ If an id is provided in `Widget.attrs`, it overrides the generated ID, unless it is `None`. """ class SomeForm(Form): field = CharField(widget=TextInput(attrs={'id': 'myCustomID'})) field_none = CharField(widget=TextInput(attrs={'id': None})) form = SomeForm() self.assertEqual(form['field'].id_for_label, 'myCustomID') self.assertEqual(form['field_none'].id_for_label, 'id_field_none') def test_label_tag_override(self): """ BoundField label_suffix (if provided) overrides Form label_suffix """ class SomeForm(Form): field = CharField() boundfield = SomeForm(label_suffix='!')['field'] self.assertHTMLEqual(boundfield.label_tag(label_suffix='$'), '<label for="id_field">Field$</label>') def test_field_name(self): """#5749 - `field_name` may be used as a key in _html_output().""" class SomeForm(Form): some_field = CharField() def as_p(self): return self._html_output( normal_row='<p id="p_%(field_name)s"></p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual(form.as_p(), '<p id="p_some_field"></p>') def test_field_without_css_classes(self): """ `css_classes` may be used as a key in _html_output() (empty classes). """ class SomeForm(Form): some_field = CharField() def as_p(self): return self._html_output( normal_row='<p class="%(css_classes)s"></p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual(form.as_p(), '<p class=""></p>') def test_field_with_css_class(self): """ `css_classes` may be used as a key in _html_output() (class comes from required_css_class in this case). """ class SomeForm(Form): some_field = CharField() required_css_class = 'foo' def as_p(self): return self._html_output( normal_row='<p class="%(css_classes)s"></p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual(form.as_p(), '<p class="foo"></p>') def test_field_name_with_hidden_input(self): """ BaseForm._html_output() should merge all the hidden input fields and put them in the last row. """ class SomeForm(Form): hidden1 = CharField(widget=HiddenInput) custom = CharField() hidden2 = CharField(widget=HiddenInput) def as_p(self): return self._html_output( normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>', error_row='%s', row_ender='</p>', help_text_html=' %s', errors_on_separate_row=True, ) form = SomeForm() self.assertHTMLEqual( form.as_p(), '<p><input id="id_custom" name="custom" type="text" required> custom' '<input id="id_hidden1" name="hidden1" type="hidden">' '<input id="id_hidden2" name="hidden2" type="hidden"></p>' ) def test_field_name_with_hidden_input_and_non_matching_row_ender(self): """ BaseForm._html_output() should merge all the hidden input fields and put them in the last row ended with the specific row ender. """ class SomeForm(Form): hidden1 = CharField(widget=HiddenInput) custom = CharField() hidden2 = CharField(widget=HiddenInput) def as_p(self): return self._html_output( normal_row='<p%(html_class_attr)s>%(field)s %(field_name)s</p>', error_row='%s', row_ender='<hr><hr>', help_text_html=' %s', errors_on_separate_row=True ) form = SomeForm() self.assertHTMLEqual( form.as_p(), '<p><input id="id_custom" name="custom" type="text" required> custom</p>\n' '<input id="id_hidden1" name="hidden1" type="hidden">' '<input id="id_hidden2" name="hidden2" type="hidden"><hr><hr>' ) def test_error_dict(self): class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError('Non-field error.', code='secret', params={'a': 1, 'b': 2}) form = MyForm({}) self.assertIs(form.is_valid(), False) errors = form.errors.as_text() control = [ '* foo\n * This field is required.', '* bar\n * This field is required.', '* __all__\n * Non-field error.', ] for error in control: self.assertIn(error, errors) errors = form.errors.as_ul() control = [ '<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul></li>', ] for error in control: self.assertInHTML(error, errors) errors = form.errors.get_json_data() control = { 'foo': [{'code': 'required', 'message': 'This field is required.'}], 'bar': [{'code': 'required', 'message': 'This field is required.'}], '__all__': [{'code': 'secret', 'message': 'Non-field error.'}] } self.assertEqual(errors, control) self.assertEqual(json.dumps(errors), form.errors.as_json()) def test_error_dict_as_json_escape_html(self): """#21962 - adding html escape flag to ErrorDict""" class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( '<p>Non-field error.</p>', code='secret', params={'a': 1, 'b': 2}, ) control = { 'foo': [{'code': 'required', 'message': 'This field is required.'}], 'bar': [{'code': 'required', 'message': 'This field is required.'}], '__all__': [{'code': 'secret', 'message': '<p>Non-field error.</p>'}] } form = MyForm({}) self.assertFalse(form.is_valid()) errors = json.loads(form.errors.as_json()) self.assertEqual(errors, control) escaped_error = '&lt;p&gt;Non-field error.&lt;/p&gt;' self.assertEqual( form.errors.get_json_data(escape_html=True)['__all__'][0]['message'], escaped_error ) errors = json.loads(form.errors.as_json(escape_html=True)) control['__all__'][0]['message'] = escaped_error self.assertEqual(errors, control) def test_error_list(self): e = ErrorList() e.append('Foo') e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'})) self.assertIsInstance(e, list) self.assertIn('Foo', e) self.assertIn('Foo', forms.ValidationError(e)) self.assertEqual( e.as_text(), '* Foo\n* Foobar' ) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) errors = e.get_json_data() self.assertEqual( errors, [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}] ) self.assertEqual(json.dumps(errors), e.as_json()) def test_error_list_class_not_specified(self): e = ErrorList() e.append('Foo') e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'})) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_class_has_one_class_specified(self): e = ErrorList(error_class='foobar-error-class') e.append('Foo') e.append(ValidationError('Foo%(bar)s', code='foobar', params={'bar': 'bar'})) self.assertEqual( e.as_ul(), '<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_with_hidden_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField(widget=HiddenInput) p = Person({'first_name': 'John'}) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></li><li> <label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></li>""" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></td></tr>""" ) def test_error_list_with_non_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField() def clean(self): raise ValidationError('Generic validation error') p = Person({'first_name': 'John', 'last_name': 'Lennon'}) self.assertHTMLEqual( str(p.non_field_errors()), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>' ) self.assertHTMLEqual( p.as_ul(), """<li> <ul class="errorlist nonfield"><li>Generic validation error</li></ul></li> <li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></li> <li><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""" ) self.assertHTMLEqual( p.non_field_errors().as_text(), '* Generic validation error' ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>Generic validation error</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></p> <p><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""" ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"><li>Generic validation error</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></td></tr>""" ) def test_errorlist_override(self): class DivErrorList(ErrorList): def __str__(self): return self.as_divs() def as_divs(self): if not self: return '' return '<div class="errorlist">%s</div>' % ''.join( '<div class="error">%s</div>' % e for e in self) class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = {'email': 'invalid'} f = CommentForm(data, auto_id=False, error_class=DivErrorList) self.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50"></p> <div class="errorlist"><div class="error">Enter a valid email address.</div></div> <p>Email: <input type="email" name="email" value="invalid" required></p> <div class="errorlist"><div class="error">This field is required.</div></div> <p>Comment: <input type="text" name="comment" required></p>""") def test_error_escaping(self): class TestForm(Form): hidden = CharField(widget=HiddenInput(), required=False) visible = CharField() def clean_hidden(self): raise ValidationError('Foo & "bar"!') clean_visible = clean_hidden form = TestForm({'hidden': 'a', 'visible': 'b'}) form.is_valid() self.assertHTMLEqual( form.as_ul(), '<li><ul class="errorlist nonfield"><li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>' '<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>' '<label for="id_visible">Visible:</label> ' '<input type="text" name="visible" value="b" id="id_visible" required>' '<input type="hidden" name="hidden" value="a" id="id_hidden"></li>' ) def test_baseform_repr(self): """ BaseForm.__repr__() should contain some basic information about the form. """ p = Person() self.assertEqual(repr(p), "<Person bound=False, valid=Unknown, fields=(first_name;last_name;birthday)>") p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}) self.assertEqual(repr(p), "<Person bound=True, valid=Unknown, fields=(first_name;last_name;birthday)>") p.is_valid() self.assertEqual(repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>") p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'}) p.is_valid() self.assertEqual(repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>") def test_baseform_repr_dont_trigger_validation(self): """ BaseForm.__repr__() shouldn't trigger the form validation. """ p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'}) repr(p) with self.assertRaises(AttributeError): p.cleaned_data self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'}) 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'], 'sirrobin') def test_changing_cleaned_data_nothing_returned(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): self.cleaned_data['username'] = self.cleaned_data['username'].lower() # don't return anything f = UserForm({'username': 'SirRobin', 'password': 'blue'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['username'], 'sirrobin') def test_changing_cleaned_data_in_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data # Return a different dict. We have not changed self.cleaned_data. return { 'username': data['username'].lower(), 'password': 'this_is_not_a_secret', } f = UserForm({'username': 'SirRobin', 'password': 'blue'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['username'], 'sirrobin') 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()) def test_html_safe(self): class SimpleForm(Form): username = CharField() form = SimpleForm() self.assertTrue(hasattr(SimpleForm, '__html__')) self.assertEqual(str(form), form.__html__()) self.assertTrue(hasattr(form['username'], '__html__')) self.assertEqual(str(form['username']), form['username'].__html__()) def test_use_required_attribute_true(self): class MyForm(Form): use_required_attribute = True f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" required></p>' '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>' '</textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></p>', ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> ' '<input id="id_f1" maxlength="30" name="f1" type="text" required></li>' '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>' '</textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></li>', ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text" required></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th>' '<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>' '</textarea></td></tr>' '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></td></tr>', ) def test_use_required_attribute_false(self): class MyForm(Form): use_required_attribute = False f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></p>' '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">' '</textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></p>', ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></li>' '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">' '</textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></li>', ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th><td><textarea cols="40" id="id_f3" name="f3" rows="10">' '</textarea></td></tr>' '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' '</select></td></tr>', ) def test_only_hidden_fields(self): # 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.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield">' '<li>(Hidden field data) This field is required.</li></ul>\n<p> ' '<input type="hidden" name="data" id="id_data"></p>' ) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield">' '<li>(Hidden field data) This field is required.</li></ul>' '<input type="hidden" name="data" id="id_data"></td></tr>' ) def test_field_named_data(self): class DataForm(Form): data = CharField(max_length=10) f = DataForm({'data': 'xyzzy'}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {'data': 'xyzzy'}) def test_empty_data_files_multi_value_dict(self): p = Person() self.assertIsInstance(p.data, MultiValueDict) self.assertIsInstance(p.files, MultiValueDict) class CustomRenderer(DjangoTemplates): pass class RendererTests(SimpleTestCase): def test_default(self): form = Form() self.assertEqual(form.renderer, get_default_renderer()) def test_kwarg_instance(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_kwarg_class(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_attribute_instance(self): class CustomForm(Form): default_renderer = DjangoTemplates() form = CustomForm() self.assertEqual(form.renderer, CustomForm.default_renderer) def test_attribute_class(self): class CustomForm(Form): default_renderer = CustomRenderer form = CustomForm() self.assertTrue(isinstance(form.renderer, CustomForm.default_renderer)) def test_attribute_override(self): class CustomForm(Form): default_renderer = DjangoTemplates() custom = CustomRenderer() form = CustomForm(renderer=custom) self.assertEqual(form.renderer, custom)
70c9da618460d968cff06847222372b3f66d3422aeb9b901ba1da7a20433d381
import mimetypes import unittest from os import path from urllib.parse import quote from django.conf.urls.static import static from django.core.exceptions import ImproperlyConfigured from django.http import FileResponse, HttpResponseNotModified from django.test import SimpleTestCase, override_settings from django.utils.http import http_date from django.views.static import was_modified_since from .. import urls from ..urls import media_dir @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') class StaticTests(SimpleTestCase): """Tests django views in django/views/static.py""" prefix = 'site_media' def test_serve(self): "The static view can serve static media" media_files = ['file.txt', 'file.txt.gz', '%2F.txt'] for filename in media_files: response = self.client.get('/%s/%s' % (self.prefix, quote(filename))) response_content = b''.join(response) file_path = path.join(media_dir, filename) with open(file_path, 'rb') as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response['Content-Length'])) self.assertEqual(mimetypes.guess_type(file_path)[1], response.get('Content-Encoding', None)) def test_chunked(self): "The static view should stream files in chunks to avoid large memory usage" response = self.client.get('/%s/%s' % (self.prefix, 'long-line.txt')) first_chunk = next(response.streaming_content) self.assertEqual(len(first_chunk), FileResponse.block_size) second_chunk = next(response.streaming_content) response.close() # strip() to prevent OS line endings from causing differences self.assertEqual(len(second_chunk.strip()), 1449) def test_unknown_mime_type(self): response = self.client.get('/%s/file.unknown' % self.prefix) self.assertEqual('application/octet-stream', response['Content-Type']) response.close() def test_copes_with_empty_path_component(self): file_name = 'file.txt' response = self.client.get('/%s//%s' % (self.prefix, file_name)) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) def test_is_modified_since(self): file_name = 'file.txt' response = self.client.get( '/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT' ) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) def test_not_modified_since(self): file_name = 'file.txt' response = self.client.get( '/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE='Mon, 18 Jan 2038 05:14:07 GMT' # This is 24h before max Unix time. Remember to fix Django and # update this test well before 2038 :) ) self.assertIsInstance(response, HttpResponseNotModified) def test_invalid_if_modified_since(self): """Handle bogus If-Modified-Since values gracefully Assume that a file is modified since an invalid timestamp as per RFC 2616, section 14.25. """ file_name = 'file.txt' invalid_date = 'Mon, 28 May 999999999999 28:25:26 GMT' response = self.client.get('/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE=invalid_date) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response['Content-Length'])) def test_invalid_if_modified_since2(self): """Handle even more bogus If-Modified-Since values gracefully Assume that a file is modified since an invalid timestamp as per RFC 2616, section 14.25. """ file_name = 'file.txt' invalid_date = ': 1291108438, Wed, 20 Oct 2010 14:05:00 GMT' response = self.client.get('/%s/%s' % (self.prefix, file_name), HTTP_IF_MODIFIED_SINCE=invalid_date) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) self.assertEqual(len(response_content), int(response['Content-Length'])) def test_404(self): response = self.client.get('/%s/nonexistent_resource' % self.prefix) self.assertEqual(404, response.status_code) def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of ./') # Directories have a trailing slash. self.assertIn('subdir/', response.context['file_list']) def test_index_subdir(self): response = self.client.get('/%s/subdir/' % self.prefix) self.assertContains(response, 'Index of subdir/') # File with a leading dot (e.g. .hidden) aren't displayed. self.assertEqual(response.context['file_list'], ['visible']) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { 'static/directory_index.html': 'Test index', }), ], }, }]) def test_index_custom_template(self): response = self.client.get('/%s/' % self.prefix) self.assertEqual(response.content, b'Test index') class StaticHelperTest(StaticTests): """ Test case to make sure the static URL pattern helper works as expected """ def setUp(self): super().setUp() self._old_views_urlpatterns = urls.urlpatterns[:] urls.urlpatterns += static('/media/', document_root=media_dir) def tearDown(self): super().tearDown() urls.urlpatterns = self._old_views_urlpatterns def test_prefix(self): self.assertEqual(static('test')[0].pattern.regex.pattern, '^test(?P<path>.*)$') @override_settings(DEBUG=False) def test_debug_off(self): """No URLs are served if DEBUG=False.""" self.assertEqual(static('test'), []) def test_empty_prefix(self): with self.assertRaisesMessage(ImproperlyConfigured, 'Empty static prefix not permitted'): static('') def test_special_prefix(self): """No URLs are served if prefix contains a netloc part.""" self.assertEqual(static('http://example.org'), []) self.assertEqual(static('//example.org'), []) class StaticUtilsTests(unittest.TestCase): def test_was_modified_since_fp(self): """ A floating point mtime does not disturb was_modified_since (#18675). """ mtime = 1343416141.107817 header = http_date(mtime) self.assertFalse(was_modified_since(header, mtime))
24124a84eb78ec0442cf5193ae43b47bcd355d6b89af0b1dbe9353d74efcc5e4
import datetime from django.contrib.sites.models import Site from django.http import Http404 from django.template import TemplateDoesNotExist from django.test import RequestFactory, TestCase from django.test.utils import override_settings from django.views.defaults import ( bad_request, page_not_found, permission_denied, server_error, ) from ..models import Article, Author, UrlArticle @override_settings(ROOT_URLCONF='view_tests.urls') class DefaultsTests(TestCase): """Test django views in django/views/defaults.py""" nonexistent_urls = [ '/nonexistent_url/', # this is in urls.py '/other_nonexistent_url/', # this NOT in urls.py ] request_factory = RequestFactory() @classmethod def setUpTestData(cls): Author.objects.create(name='Boris') Article.objects.create( title='Old Article', slug='old_article', author_id=1, date_created=datetime.datetime(2001, 1, 1, 21, 22, 23) ) Article.objects.create( title='Current Article', slug='current_article', author_id=1, date_created=datetime.datetime(2007, 9, 17, 21, 22, 23) ) Article.objects.create( title='Future Article', slug='future_article', author_id=1, date_created=datetime.datetime(3000, 1, 1, 21, 22, 23) ) UrlArticle.objects.create( title='Old Article', slug='old_article', author_id=1, date_created=datetime.datetime(2001, 1, 1, 21, 22, 23) ) Site(id=1, domain='testserver', name='testserver').save() def test_page_not_found(self): "A 404 status is returned by the page_not_found view" for url in self.nonexistent_urls: response = self.client.get(url) self.assertEqual(response.status_code, 404) self.assertIn(b'<h1>Not Found</h1>', response.content) self.assertIn( b'<p>The requested resource was not found on this server.</p>', response.content, ) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': '{{ csrf_token }}', }), ], }, }]) def test_csrf_token_in_404(self): """ The 404 page should have the csrf_token available in the context """ # See ticket #14565 for url in self.nonexistent_urls: response = self.client.get(url) self.assertNotEqual(response.content, b'NOTPROVIDED') self.assertNotEqual(response.content, b'') def test_server_error(self): "The server_error view raises a 500 status" response = self.client.get('/server_error/') self.assertContains(response, b'<h1>Server Error (500)</h1>', status_code=500) def test_bad_request(self): request = self.request_factory.get('/') response = bad_request(request, Exception()) self.assertContains(response, b'<h1>Bad Request (400)</h1>', status_code=400) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': 'This is a test template for a 404 error ' '(path: {{ request_path }}, exception: {{ exception }}).', '500.html': 'This is a test template for a 500 error.', }), ], }, }]) def test_custom_templates(self): """ 404.html and 500.html templates are picked by their respective handler. """ response = self.client.get('/server_error/') self.assertContains(response, "test template for a 500 error", status_code=500) response = self.client.get('/no_such_url/') self.assertContains(response, 'path: /no_such_url/', status_code=404) self.assertContains(response, 'exception: Resolver404', status_code=404) response = self.client.get('/technical404/') self.assertContains(response, 'exception: Testing technical 404.', status_code=404) def test_get_absolute_url_attributes(self): "A model can set attributes on the get_absolute_url method" self.assertTrue(getattr(UrlArticle.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') article = UrlArticle.objects.get(pk=1) self.assertTrue(getattr(article.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') def test_custom_templates_wrong(self): """ Default error views should raise TemplateDoesNotExist when passed a template that doesn't exist. """ request = self.request_factory.get('/') with self.assertRaises(TemplateDoesNotExist): bad_request(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): permission_denied(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): page_not_found(request, Http404(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): server_error(request, template_name='nonexistent') def test_error_pages(self): request = self.request_factory.get('/') for response, title in ( (bad_request(request, Exception()), b'Bad Request (400)'), (permission_denied(request, Exception()), b'403 Forbidden'), (page_not_found(request, Http404()), b'Not Found'), (server_error(request), b'Server Error (500)'), ): with self.subTest(title=title): self.assertIn(b'<!doctype html>', response.content) self.assertIn(b'<html lang="en">', response.content) self.assertIn(b'<head>', response.content) self.assertIn(b'<title>%s</title>' % title, response.content) self.assertIn(b'<body>', response.content)
5bf7907dba061b57209e3e5dd6b5d05afabae17b38d0aafd62c9deb594c74b64
from django.template import TemplateDoesNotExist from django.test import ( Client, RequestFactory, SimpleTestCase, override_settings, ) from django.utils.translation import override from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure @override_settings(ROOT_URLCONF='view_tests.urls') class CsrfViewTests(SimpleTestCase): def setUp(self): super().setUp() self.client = Client(enforce_csrf_checks=True) @override_settings( USE_I18N=True, MIDDLEWARE=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ], ) def test_translation(self): """An invalid request is rejected with a localized error message.""" response = self.client.post('/') self.assertContains(response, 'Forbidden', status_code=403) self.assertContains(response, 'CSRF verification failed. Request aborted.', status_code=403) with self.settings(LANGUAGE_CODE='nl'), override('en-us'): response = self.client.post('/') self.assertContains(response, 'Verboden', status_code=403) self.assertContains(response, 'CSRF-verificatie mislukt. Verzoek afgebroken.', status_code=403) @override_settings( SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https') ) def test_no_referer(self): """ Referer header is strictly checked for POST over HTTPS. Trigger the exception by sending an incorrect referer. """ response = self.client.post('/', HTTP_X_FORWARDED_PROTO='https') self.assertContains( response, 'You are seeing this message because this HTTPS site requires a ' '&#x27;Referer header&#x27; to be sent by your Web browser, but ' 'none was sent.', status_code=403, ) self.assertContains( response, 'If you have configured your browser to disable &#x27;Referer&#x27; ' 'headers, please re-enable them, at least for this site, or for ' 'HTTPS connections, or for &#x27;same-origin&#x27; requests.', status_code=403, ) self.assertContains( response, 'If you are using the &lt;meta name=&quot;referrer&quot; ' 'content=&quot;no-referrer&quot;&gt; tag or including the ' '&#x27;Referrer-Policy: no-referrer&#x27; header, please remove them.', status_code=403, ) def test_no_cookies(self): """ The CSRF cookie is checked for POST. Failure to send this cookie should provide a nice error message. """ response = self.client.post('/') self.assertContains( response, 'You are seeing this message because this site requires a CSRF ' 'cookie when submitting forms. This cookie is required for ' 'security reasons, to ensure that your browser is not being ' 'hijacked by third parties.', status_code=403, ) @override_settings(TEMPLATES=[]) def test_no_django_template_engine(self): """ The CSRF view doesn't depend on the TEMPLATES configuration (#24388). """ response = self.client.post('/') self.assertContains(response, 'Forbidden', status_code=403) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { CSRF_FAILURE_TEMPLATE_NAME: 'Test template for CSRF failure' }), ], }, }]) def test_custom_template(self): """A custom CSRF_FAILURE_TEMPLATE_NAME is used.""" response = self.client.post('/') self.assertContains(response, 'Test template for CSRF failure', status_code=403) def test_custom_template_does_not_exist(self): """An exception is raised if a nonexistent template is supplied.""" factory = RequestFactory() request = factory.post('/') with self.assertRaises(TemplateDoesNotExist): csrf_failure(request, template_name='nonexistent.html')
ca116b6e02852047b91eedbdeacae13bfc622ac04686e3a1fc3379ddfc222c8a
import gettext import json from os import path from django.conf import settings from django.test import ( RequestFactory, SimpleTestCase, TestCase, ignore_warnings, modify_settings, override_settings, ) from django.test.selenium import SeleniumTestCase from django.urls import reverse from django.utils.deprecation import RemovedInDjango40Warning from django.utils.translation import ( LANGUAGE_SESSION_KEY, get_language, override, ) from django.views.i18n import JavaScriptCatalog, get_formats from ..urls import locale_dir @override_settings(ROOT_URLCONF='view_tests.urls') class SetLanguageTests(TestCase): """Test the django.views.i18n.set_language view.""" def _get_inactive_language_code(self): """Return language code for a language which is not activated.""" current_language = get_language() return [code for code, name in settings.LANGUAGES if not code == current_language][0] def test_setlang(self): """ The set_language view can be used to change the session language. The user is redirected to the 'next' argument if provided. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '/'} response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i_should_not_be_used/') self.assertRedirects(response, '/') with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) # The language is set in a cookie. language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME] self.assertEqual(language_cookie.value, lang_code) self.assertEqual(language_cookie['domain'], '') self.assertEqual(language_cookie['path'], '/') self.assertEqual(language_cookie['max-age'], '') self.assertEqual(language_cookie['httponly'], '') self.assertEqual(language_cookie['samesite'], '') self.assertEqual(language_cookie['secure'], '') def test_setlang_unsafe_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe". """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '//unsafe/redirection/'} response = self.client.post('/i18n/setlang/', data=post_data) self.assertEqual(response.url, '/') self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_http_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe" and its scheme is https if the request was sent over https. """ lang_code = self._get_inactive_language_code() non_https_next_url = 'http://testserver/redirection/' post_data = {'language': lang_code, 'next': non_https_next_url} # Insecure URL in POST data. response = self.client.post('/i18n/setlang/', data=post_data, secure=True) self.assertEqual(response.url, '/') self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) # Insecure URL in HTTP referer. response = self.client.post('/i18n/setlang/', secure=True, HTTP_REFERER=non_https_next_url) self.assertEqual(response.url, '/') self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_redirect_to_referer(self): """ The set_language view redirects to the URL in the referer header when there isn't a "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} response = self.client.post('/i18n/setlang/', post_data, HTTP_REFERER='/i18n/') self.assertRedirects(response, '/i18n/', fetch_redirect_response=False) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_default_redirect(self): """ The set_language view redirects to '/' when there isn't a referer or "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} response = self.client.post('/i18n/setlang/', post_data) self.assertRedirects(response, '/') self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_performs_redirect_for_ajax_if_explicitly_requested(self): """ The set_language view redirects to the "next" parameter for AJAX calls. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '/'} response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertRedirects(response, '/') self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_doesnt_perform_a_redirect_to_referer_for_ajax(self): """ The set_language view doesn't redirect to the HTTP referer header for AJAX calls. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} headers = {'HTTP_REFERER': '/', 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} response = self.client.post('/i18n/setlang/', post_data, **headers) self.assertEqual(response.status_code, 204) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_doesnt_perform_a_default_redirect_for_ajax(self): """ The set_language view returns 204 for AJAX calls by default. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code} response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 204) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) def test_setlang_unsafe_next_for_ajax(self): """ The fallback to root URL for the set_language view works for AJAX calls. """ lang_code = self._get_inactive_language_code() post_data = {'language': lang_code, 'next': '//unsafe/redirection/'} response = self.client.post('/i18n/setlang/', post_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.url, '/') self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) def test_session_language_deprecation(self): msg = ( 'The user language will no longer be stored in request.session ' 'in Django 4.0. Read it from ' 'request.COOKIES[settings.LANGUAGE_COOKIE_NAME] instead.' ) with self.assertRaisesMessage(RemovedInDjango40Warning, msg): self.client.session[LANGUAGE_SESSION_KEY] def test_setlang_reversal(self): self.assertEqual(reverse('set_language'), '/i18n/setlang/') def test_setlang_cookie(self): # we force saving language to a cookie rather than a session # by excluding session middleware and those which do require it test_settings = { 'MIDDLEWARE': ['django.middleware.common.CommonMiddleware'], 'LANGUAGE_COOKIE_NAME': 'mylanguage', 'LANGUAGE_COOKIE_AGE': 3600 * 7 * 2, 'LANGUAGE_COOKIE_DOMAIN': '.example.com', 'LANGUAGE_COOKIE_PATH': '/test/', 'LANGUAGE_COOKIE_HTTPONLY': True, 'LANGUAGE_COOKIE_SAMESITE': 'Strict', 'LANGUAGE_COOKIE_SECURE': True, } with self.settings(**test_settings): post_data = {'language': 'pl', 'next': '/views/'} response = self.client.post('/i18n/setlang/', data=post_data) language_cookie = response.cookies.get('mylanguage') self.assertEqual(language_cookie.value, 'pl') self.assertEqual(language_cookie['domain'], '.example.com') self.assertEqual(language_cookie['path'], '/test/') self.assertEqual(language_cookie['max-age'], 3600 * 7 * 2) self.assertEqual(language_cookie['httponly'], True) self.assertEqual(language_cookie['samesite'], 'Strict') self.assertEqual(language_cookie['secure'], True) def test_setlang_decodes_http_referer_url(self): """ The set_language view decodes the HTTP_REFERER URL. """ # The URL & view must exist for this to work as a regression test. self.assertEqual(reverse('with_parameter', kwargs={'parameter': 'x'}), '/test-setlang/x/') lang_code = self._get_inactive_language_code() encoded_url = '/test-setlang/%C3%A4/' # (%C3%A4 decodes to ä) response = self.client.post('/i18n/setlang/', {'language': lang_code}, HTTP_REFERER=encoded_url) self.assertRedirects(response, encoded_url, fetch_redirect_response=False) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code) with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], lang_code) @modify_settings(MIDDLEWARE={ 'append': 'django.middleware.locale.LocaleMiddleware', }) def test_lang_from_translated_i18n_pattern(self): response = self.client.post( '/i18n/setlang/', data={'language': 'nl'}, follow=True, HTTP_REFERER='/en/translated/' ) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, 'nl') with ignore_warnings(category=RemovedInDjango40Warning): self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'nl') self.assertRedirects(response, '/nl/vertaald/') # And reverse response = self.client.post( '/i18n/setlang/', data={'language': 'en'}, follow=True, HTTP_REFERER='/nl/vertaald/' ) self.assertRedirects(response, '/en/translated/') @override_settings(ROOT_URLCONF='view_tests.urls') class I18NViewTests(SimpleTestCase): """Test django.views.i18n views other than set_language.""" @override_settings(LANGUAGE_CODE='de') def test_get_formats(self): formats = get_formats() # Test 3 possible types in get_formats: integer, string, and list. self.assertEqual(formats['FIRST_DAY_OF_WEEK'], 0) self.assertEqual(formats['DECIMAL_SEPARATOR'], '.') self.assertEqual(formats['TIME_INPUT_FORMATS'], ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']) def test_jsi18n(self): """The javascript_catalog can be deployed with language settings""" for lang_code in ['es', 'fr', 'ru']: with override(lang_code): catalog = gettext.translation('djangojs', locale_dir, [lang_code]) trans_txt = catalog.gettext('this is to be translated') response = self.client.get('/jsi18n/') self.assertEqual(response['Content-Type'], 'text/javascript; charset="utf-8"') # response content must include a line like: # "this is to be translated": <value of trans_txt Python variable> # json.dumps() is used to be able to check unicode strings self.assertContains(response, json.dumps(trans_txt), 1) if lang_code == 'fr': # Message with context (msgctxt) self.assertContains(response, '"month name\\u0004May": "mai"', 1) @override_settings(USE_I18N=False) def test_jsi18n_USE_I18N_False(self): response = self.client.get('/jsi18n/') # default plural function self.assertContains(response, 'django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };') self.assertNotContains(response, 'var newcatalog =') def test_jsoni18n(self): """ The json_catalog returns the language catalog and settings as JSON. """ with override('de'): response = self.client.get('/jsoni18n/') data = json.loads(response.content.decode()) self.assertIn('catalog', data) self.assertIn('formats', data) self.assertEqual(data['formats']['TIME_INPUT_FORMATS'], ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']) self.assertEqual(data['formats']['FIRST_DAY_OF_WEEK'], 0) self.assertIn('plural', data) self.assertEqual(data['catalog']['month name\x04May'], 'Mai') self.assertIn('DATETIME_FORMAT', data['formats']) self.assertEqual(data['plural'], '(n != 1)') def test_jsi18n_with_missing_en_files(self): """ The javascript_catalog shouldn't load the fallback language in the case that the current selected language is actually the one translated from, and hence missing translation files completely. This happens easily when you're translating from English to other languages and you've set settings.LANGUAGE_CODE to some other language than English. """ with self.settings(LANGUAGE_CODE='es'), override('en-us'): response = self.client.get('/jsi18n/') self.assertNotContains(response, 'esto tiene que ser traducido') def test_jsoni18n_with_missing_en_files(self): """ Same as above for the json_catalog view. Here we also check for the expected JSON format. """ with self.settings(LANGUAGE_CODE='es'), override('en-us'): response = self.client.get('/jsoni18n/') data = json.loads(response.content.decode()) self.assertIn('catalog', data) self.assertIn('formats', data) self.assertIn('plural', data) self.assertEqual(data['catalog'], {}) self.assertIn('DATETIME_FORMAT', data['formats']) self.assertIsNone(data['plural']) def test_jsi18n_fallback_language(self): """ Let's make sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'), override('fi'): response = self.client.get('/jsi18n/') self.assertContains(response, 'il faut le traduire') self.assertNotContains(response, "Untranslated string") def test_i18n_fallback_language_plural(self): """ The fallback to a language with less plural forms maintains the real language's number of plural forms and correct translations. """ with self.settings(LANGUAGE_CODE='pt'), override('ru'): response = self.client.get('/jsi18n/') self.assertEqual( response.context['catalog']['{count} plural3'], ['{count} plural3 p3', '{count} plural3 p3s', '{count} plural3 p3t'] ) self.assertEqual( response.context['catalog']['{count} plural2'], ['{count} plural2', '{count} plural2s', ''] ) with self.settings(LANGUAGE_CODE='ru'), override('pt'): response = self.client.get('/jsi18n/') self.assertEqual( response.context['catalog']['{count} plural3'], ['{count} plural3', '{count} plural3s'] ) self.assertEqual( response.context['catalog']['{count} plural2'], ['{count} plural2', '{count} plural2s'] ) def test_i18n_english_variant(self): with override('en-gb'): response = self.client.get('/jsi18n/') self.assertIn( '"this color is to be translated": "this colour is to be translated"', response.context['catalog_str'] ) def test_i18n_language_non_english_default(self): """ Check if the Javascript i18n view returns an empty language catalog if the default language is non-English, the selected language is English and there is not 'en' translation available. See #13388, #3594 and #13726 for more details. """ with self.settings(LANGUAGE_CODE='fr'), override('en-us'): response = self.client.get('/jsi18n/') self.assertNotContains(response, 'Choisir une heure') @modify_settings(INSTALLED_APPS={'append': 'view_tests.app0'}) def test_non_english_default_english_userpref(self): """ Same as above with the difference that there IS an 'en' translation available. The Javascript i18n view must return a NON empty language catalog with the proper English translations. See #13726 for more details. """ with self.settings(LANGUAGE_CODE='fr'), override('en-us'): response = self.client.get('/jsi18n_english_translation/') self.assertContains(response, 'this app0 string is to be translated') def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE='fr'), override('none'): response = self.client.get('/jsi18n/') self.assertContains(response, 'Choisir une heure') def test_escaping(self): # Force a language via GET otherwise the gettext functions are a noop! response = self.client.get('/jsi18n_admin/?language=de') self.assertContains(response, '\\x04') @modify_settings(INSTALLED_APPS={'append': ['view_tests.app5']}) def test_non_BMP_char(self): """ Non-BMP characters should not break the javascript_catalog (#21725). """ with self.settings(LANGUAGE_CODE='en-us'), override('fr'): response = self.client.get('/jsi18n/app5/') self.assertContains(response, 'emoji') self.assertContains(response, '\\ud83d\\udca9') @modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']}) def test_i18n_language_english_default(self): """ Check if the JavaScript i18n view returns a complete language catalog if the default language is en-us, the selected language has a translation available and a catalog composed by djangojs domain translations of multiple Python packages is requested. See #13388, #3594 and #13514 for more details. """ base_trans_string = 'il faut traduire cette cha\\u00eene de caract\\u00e8res de ' app1_trans_string = base_trans_string + 'app1' app2_trans_string = base_trans_string + 'app2' with self.settings(LANGUAGE_CODE='en-us'), override('fr'): response = self.client.get('/jsi18n_multi_packages1/') self.assertContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) response = self.client.get('/jsi18n/app1/') self.assertContains(response, app1_trans_string) self.assertNotContains(response, app2_trans_string) response = self.client.get('/jsi18n/app2/') self.assertNotContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) @modify_settings(INSTALLED_APPS={'append': ['view_tests.app3', 'view_tests.app4']}) def test_i18n_different_non_english_languages(self): """ Similar to above but with neither default or requested language being English. """ with self.settings(LANGUAGE_CODE='fr'), override('es-ar'): response = self.client.get('/jsi18n_multi_packages2/') self.assertContains(response, 'este texto de app3 debe ser traducido') def test_i18n_with_locale_paths(self): extended_locale_paths = settings.LOCALE_PATHS + [ path.join( path.dirname(path.dirname(path.abspath(__file__))), 'app3', 'locale', ), ] with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths): with override('es-ar'): response = self.client.get('/jsi18n/') self.assertContains(response, 'este texto de app3 debe ser traducido') def test_i18n_unknown_package_error(self): view = JavaScriptCatalog.as_view() request = RequestFactory().get('/') msg = 'Invalid package(s) provided to JavaScriptCatalog: unknown_package' with self.assertRaisesMessage(ValueError, msg): view(request, packages='unknown_package') msg += ',unknown_package2' with self.assertRaisesMessage(ValueError, msg): view(request, packages='unknown_package+unknown_package2') @override_settings(ROOT_URLCONF='view_tests.urls') class I18nSeleniumTests(SeleniumTestCase): # The test cases use fixtures & translations from these apps. available_apps = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'view_tests', ] @override_settings(LANGUAGE_CODE='de') def test_javascript_gettext(self): self.selenium.get(self.live_server_url + '/jsi18n_template/') elem = self.selenium.find_element_by_id("gettext") self.assertEqual(elem.text, "Entfernen") elem = self.selenium.find_element_by_id("ngettext_sing") self.assertEqual(elem.text, "1 Element") elem = self.selenium.find_element_by_id("ngettext_plur") self.assertEqual(elem.text, "455 Elemente") elem = self.selenium.find_element_by_id("ngettext_onnonplural") self.assertEqual(elem.text, "Bild") elem = self.selenium.find_element_by_id("pgettext") self.assertEqual(elem.text, "Kann") elem = self.selenium.find_element_by_id("npgettext_sing") self.assertEqual(elem.text, "1 Resultat") elem = self.selenium.find_element_by_id("npgettext_plur") self.assertEqual(elem.text, "455 Resultate") elem = self.selenium.find_element_by_id("formats") self.assertEqual( elem.text, "DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; FIRST_DAY_OF_WEEK is a number;" ) @modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']}) @override_settings(LANGUAGE_CODE='fr') def test_multiple_catalogs(self): self.selenium.get(self.live_server_url + '/jsi18n_multi_catalogs/') elem = self.selenium.find_element_by_id('app1string') self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app1') elem = self.selenium.find_element_by_id('app2string') self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app2')
46b89f5ed00f7640604d0bf1e153f703dcc56cedc2054160d2f7f48b77e20afd
import importlib import inspect import os import re import sys import tempfile import threading from io import StringIO from pathlib import Path from unittest import mock from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import path, reverse from django.utils.functional import SimpleLazyObject from django.utils.safestring import mark_safe from django.views.debug import ( CLEANSED_SUBSTITUTE, CallableSettingWrapper, ExceptionReporter, Path as DebugPath, cleanse_setting, default_urlconf, technical_404_response, technical_500_response, ) from ..views import ( custom_exception_reporter_filter_view, index_page, multivalue_dict_key_error, non_sensitive_view, paranoid_view, sensitive_args_function_caller, sensitive_kwargs_function_caller, sensitive_method_view, sensitive_view, ) class User: def __str__(self): return 'jacob' class WithoutEmptyPathUrls: urlpatterns = [path('url/', index_page, name='url')] class CallableSettingWrapperTests(SimpleTestCase): """ Unittests for CallableSettingWrapper """ def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(WrappedCallable())) self.assertEqual(actual, "repr from the wrapped callable") @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') class DebugViewTests(SimpleTestCase): def test_files(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises/') self.assertEqual(response.status_code, 500) data = { 'file_data.txt': SimpleUploadedFile('file_data.txt', b'haha'), } with self.assertLogs('django.request', 'ERROR'): response = self.client.post('/raises/', data) self.assertContains(response, 'file_data.txt', status_code=500) self.assertNotContains(response, 'haha', status_code=500) def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) # Ensure no 403.html template exists to test the default case. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', }]) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) # Set up a test 403.html template. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '403.html': 'This is a test template for a 403 error ({{ exception }}).', }), ], }, }]) def test_403_template(self): response = self.client.get('/raises403/') self.assertContains(response, 'test template', status_code=403) self.assertContains(response, '(Insufficient Permissions).', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) self.assertContains(response, "<code>not-in-urls</code>, didn't match", status_code=404) def test_404_not_in_urls(self): response = self.client.get('/not-in-urls') self.assertNotContains(response, "Raised by:", status_code=404) self.assertContains(response, "Django tried these URL patterns", status_code=404) self.assertContains(response, "<code>not-in-urls</code>, didn't match", status_code=404) # Pattern and view name of a RegexURLPattern appear. self.assertContains(response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404) self.assertContains(response, "[name='regex-post']", status_code=404) # Pattern and view name of a RoutePattern appear. self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404) self.assertContains(response, "[name='path-post']", status_code=404) @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls) def test_404_empty_path_not_in_urls(self): response = self.client.get('/') self.assertContains(response, "The empty path didn't match any of these.", status_code=404) def test_technical_404(self): response = self.client.get('/technical404/') self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.technical404", status_code=404) def test_classbased_technical_404(self): response = self.client.get('/classbased404/') self.assertContains(response, "Raised by:", status_code=404) self.assertContains(response, "view_tests.views.Http404View", status_code=404) def test_non_l10ned_numeric_ids(self): """ Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. """ with self.settings(DEBUG=True, USE_L10N=True): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') # We look for a HTML fragment of the form # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"' self.assertContains(response, '<div class="context" id="', status_code=500) match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content) self.assertIsNotNone(match) id_repr = match.group('id') self.assertFalse( re.search(b'[^c0-9]', id_repr), "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr.decode() ) def test_template_exceptions(self): with self.assertLogs('django.request', 'ERROR'): try: self.client.get(reverse('template_exception')) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() self.assertNotEqual( raising_loc.find("raise Exception('boom')"), -1, "Failed to find 'raise Exception' in last frame of " "traceback, instead found: %s" % raising_loc ) def test_template_loader_postmortem(self): """Tests for not existing file""" template_name = "notfound.html" with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) with override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [tempdir], }]), self.assertLogs('django.request', 'ERROR'): response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name})) self.assertContains(response, "%s (Source does not exist)" % template_path, status_code=500, count=2) # Assert as HTML. self.assertContains( response, '<li><code>django.template.loaders.filesystem.Loader</code>: ' '%s (Source does not exist)</li>' % os.path.join(tempdir, 'notfound.html'), status_code=500, html=True, ) def test_no_template_source_loaders(self): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ with self.assertLogs('django.request', 'ERROR'): with self.assertRaises(TemplateDoesNotExist): self.client.get('/render_no_template/') @override_settings(ROOT_URLCONF='view_tests.default_urls') def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown shown instead of the technical 404 page, if the user has not altered their URLconf yet. """ response = self.client.get('/') self.assertContains( response, "<h2>The install worked successfully! Congratulations!</h2>" ) @override_settings(ROOT_URLCONF='view_tests.regression_21530_urls') def test_regression_21530(self): """ Regression test for bug #21530. If the admin app include is replaced with exactly one url pattern, then the technical 404 template should be displayed. The bug here was that an AttributeError caused a 500 response. """ response = self.client.get('/') self.assertContains( response, "Page not found <span>(404)</span>", status_code=404 ) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ with mock.patch.object(DebugPath, 'open') as m: default_urlconf(None) m.assert_called_once_with(encoding='utf-8') m.reset_mock() technical_404_response(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding='utf-8') class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection databases = {'default'} def test_handle_db_exception(self): """ Ensure the debug view works when a database exception is raised by performing an invalid query and passing the exception to the debug view. """ with connection.cursor() as cursor: try: cursor.execute('INVALID SQL') except DatabaseError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get('/'), *exc_info) self.assertContains(response, 'OperationalError at /', status_code=500) @override_settings( DEBUG=True, ROOT_URLCONF='view_tests.urls', # No template directories are configured, so no templates will be found. TEMPLATES=[{ 'BACKEND': 'django.template.backends.dummy.TemplateStrings', }], ) class NonDjangoTemplatesDebugViewTests(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) def test_template_not_found_error(self): # Raises a TemplateDoesNotExist exception and shows the debug view. url = reverse('raises_template_does_not_exist', kwargs={"path": "notfound.html"}) with self.assertLogs('django.request', 'ERROR'): response = self.client.get(url) self.assertContains(response, '<div class="context" id="', status_code=500) class ExceptionReporterTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>jacob</p>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) self.assertIn('<p>No POST data</p>', html) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_eol_support(self): """The ExceptionReporter supports Unix, Windows and Macintosh EOL markers""" LINES = ['print %d' % i for i in range(1, 6)] reporter = ExceptionReporter(None, None, None, None) for newline in ['\n', '\r\n', '\r']: fd, filename = tempfile.mkstemp(text=False) os.write(fd, (newline.join(LINES) + newline).encode()) os.close(fd) try: self.assertEqual( reporter._get_lines_from_file(filename, 3, 2), (1, LINES[1:3], LINES[3], LINES[4:]) ) finally: os.unlink(filename) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">No exception message supplied</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_reporting_of_nested_exceptions(self): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError(mark_safe('<p>Second exception</p>')) from explicit except ValueError: raise IndexError(mark_safe('<p>Final exception</p>')) except Exception: # Custom exception handler, just pass it into ExceptionReporter exc_type, exc_value, tb = sys.exc_info() explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:' implicit_exc = 'During handling of the above exception ({0}), another exception occurred:' reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;'))) self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;')) text = reporter.get_traceback_text() self.assertIn(explicit_exc.format('<p>Top level</p>'), text) self.assertIn(implicit_exc.format('<p>Second exception</p>'), text) self.assertEqual(3, text.count('<p>Final exception</p>')) def test_reporting_frames_without_source(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn('generated in funcName', html) text = reporter.get_traceback_text() self.assertIn('"generated" in funcName', text) def test_reporting_frames_for_cyclic_reference(self): try: def test_func(): try: raise RuntimeError('outer') from RuntimeError('inner') except RuntimeError as exc: raise exc.__cause__ test_func() except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) def generate_traceback_frames(*args, **kwargs): nonlocal tb_frames tb_frames = reporter.get_traceback_frames() tb_frames = None tb_generator = threading.Thread(target=generate_traceback_frames, daemon=True) tb_generator.start() tb_generator.join(timeout=5) if tb_generator.is_alive(): # tb_generator is a daemon that runs until the main thread/process # exits. This is resource heavy when running the full test suite. # Setting the following values to None makes # reporter.get_traceback_frames() exit early. exc_value.__traceback__ = exc_value.__context__ = exc_value.__cause__ = None tb_generator.join() self.fail('Cyclic reference in Exception Reporter.get_traceback_frames()') if tb_frames is None: # can happen if the thread generating traceback got killed # or exception while generating the traceback self.fail('Traceback generation failed') last_frame = tb_frames[-1] self.assertIn('raise exc.__cause__', last_frame['context_line']) self.assertEqual(last_frame['filename'], __file__) self.assertEqual(last_frame['function'], 'test_func') def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_non_utf8_values_handling(self): "Non-UTF-8 exceptions/values should not make the output generation choke." try: class NonUtf8Output(Exception): def __repr__(self): return b'EXC\xe9EXC' somevar = b'VAL\xe9VAL' # NOQA raise NonUtf8Output() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('VAL\\xe9VAL', html) self.assertIn('EXC\\xe9EXC', html) def test_local_variable_escaping(self): """Safe strings in local variables are escaped.""" try: local = mark_safe('<p>Local variable</p>') raise ValueError(local) except Exception: exc_type, exc_value, tb = sys.exc_info() html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html() self.assertIn('<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre></td>', html) def test_unprintable_values_handling(self): "Unprintable values should not make the output generation choke." try: class OomOutput: def __repr__(self): raise MemoryError('OOM') oomvalue = OomOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<td class="code"><pre>Error in formatting', html) def test_too_large_values_handling(self): "Large values should not create a large HTML." large = 256 * 1024 repr_of_str_adds = len(repr('')) try: class LargeOutput: def __repr__(self): return repr('A' * large) largevalue = LargeOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb self.assertIn('&lt;trimmed %d bytes string&gt;' % (large + repr_of_str_adds,), html) def test_encoding_error(self): """ A UnicodeError displays a portion of the problematic string. HTML in safe strings is escaped. """ try: mark_safe('abcdefghijkl<p>mnὀp</p>qrstuwxyz').encode('ascii') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<h2>Unicode error hint</h2>', html) self.assertIn('The string that could not be encoded/decoded was: ', html) self.assertIn('<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>', html) def test_unfrozen_importlib(self): """ importlib is not a frozen app, but its loader thinks it's frozen which results in an ImportError. Refs #21443. """ try: request = self.rf.get('/test_view/') importlib.import_module('abc.def.invalid.name') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ModuleNotFoundError at /test_view/</h1>', html) def test_ignore_traceback_evaluation_exceptions(self): """ Don't trip over exceptions generated by crafted objects when evaluating them while cleansing (#24455). """ class BrokenEvaluation(Exception): pass def broken_setup(): raise BrokenEvaluation request = self.rf.get('/test_view/') broken_lazy = SimpleLazyObject(broken_setup) try: bool(broken_lazy) except BrokenEvaluation: exc_type, exc_value, tb = sys.exc_info() self.assertIn( "BrokenEvaluation", ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(), "Evaluation exception reason not mentioned in traceback" ) @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertIn("http://evil.com/", html) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ value = '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>' # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: ' 'items (application/octet-stream)&gt;</pre></td>', html ) # COOKES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>', html) def test_exception_fetching_user(self): """ The error page can be rendered if the current user can't be retrieved (such as when the database is unavailable). """ class ExceptionUser: def __str__(self): raise Exception() request = self.rf.get('/test_view/') request.user = ExceptionUser() try: raise ValueError('Oops') except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>[unable to retrieve the current user]</p>', html) text = reporter.get_traceback_text() self.assertIn('USER: [unable to retrieve the current user]', text) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ reporter = ExceptionReporter(None, None, None, None) with mock.patch.object(DebugPath, 'open') as m: reporter.get_traceback_html() m.assert_called_once_with(encoding='utf-8') m.reset_mock() reporter.get_traceback_text() m.assert_called_once_with(encoding='utf-8') class PlainTextReportTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError at /test_view/', text) self.assertIn("Can't find my keys", text) self.assertIn('Request Method:', text) self.assertIn('Request URL:', text) self.assertIn('USER: jacob', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback:', text) self.assertIn('Request information:', text) self.assertNotIn('Request data not supplied', text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError', text) self.assertIn("Can't find my keys", text) self.assertNotIn('Request Method:', text) self.assertNotIn('Request URL:', text) self.assertNotIn('USER:', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback:', text) self.assertIn('Request data not supplied', text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get('/test_view/') try: render(request, 'debug/template_error.html') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path(Path(__file__).parent.parent, 'templates', 'debug', 'template_error.html') self.assertIn( 'Template error:\n' 'In template %(path)s, error at line 2\n' ' \'cycle\' tag requires at least two arguments\n' ' 1 : Template with error:\n' ' 2 : {%% cycle %%} \n' ' 3 : ' % {'path': templ_path}, text ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn('items = <InMemoryUploadedFile:', text) # COOKES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text) class ExceptionReportTestMixin: # Mixin used in the ExceptionReporterFilterTests and # AjaxResponseExceptionReporterFilter tests below breakfast_data = { 'sausage-key': 'sausage-value', 'baked-beans-key': 'baked-beans-value', 'hash-brown-key': 'hash-brown-value', 'bacon-key': 'bacon-value', } def verify_unsafe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # All variables are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertContains(response, k, status_code=500) self.assertContains(response, v, status_code=500) def verify_safe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Non-sensitive variable's name and value are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) # Sensitive variable's name is shown but not its value. self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # Non-sensitive POST parameters' values are shown. self.assertContains(response, 'baked-beans-value', status_code=500) self.assertContains(response, 'hash-brown-value', status_code=500) # Sensitive POST parameters' values are not shown. self.assertNotContains(response, 'sausage-value', status_code=500) self.assertNotContains(response, 'bacon-value', status_code=500) def verify_paranoid_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that no variables or POST parameters are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Show variable names but not their values. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertNotContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # No POST parameters' values are shown. self.assertNotContains(response, v, status_code=500) def verify_unsafe_email(self, view, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertIn('worcestershire', body_html) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertIn(k, body_plain) self.assertIn(v, body_plain) self.assertIn(k, body_html) self.assertIn(v, body_html) def verify_safe_email(self, view, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertNotIn('worcestershire', body_html) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertIn(k, body_plain) # Non-sensitive POST parameters' values are shown. self.assertIn('baked-beans-value', body_plain) self.assertIn('hash-brown-value', body_plain) self.assertIn('baked-beans-value', body_html) self.assertIn('hash-brown-value', body_html) # Sensitive POST parameters' values are not shown. self.assertNotIn('sausage-value', body_plain) self.assertNotIn('bacon-value', body_plain) self.assertNotIn('sausage-value', body_html) self.assertNotIn('bacon-value', body_html) def verify_paranoid_email(self, view): """ Asserts that no variables or POST parameters are displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body = str(email.body) self.assertNotIn('cooked_eggs', body) self.assertNotIn('scrambled', body) self.assertNotIn('sauce', body) self.assertNotIn('worcestershire', body) for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertIn(k, body) # No POST parameters' values are shown. self.assertNotIn(v, body) @override_settings(ROOT_URLCONF='view_tests.urls') class ExceptionReporterFilterTests(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports (#14614). """ rf = RequestFactory() def test_non_sensitive_request(self): """ Everything (request info and frame variables) can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) def test_sensitive_request(self): """ Sensitive POST parameters and frame variables cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view) self.verify_unsafe_email(sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view) self.verify_safe_email(sensitive_view) def test_paranoid_request(self): """ No POST parameters and frame variables can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view) self.verify_unsafe_email(paranoid_view) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view) self.verify_paranoid_email(paranoid_view) def test_multivalue_dict_key_error(self): """ #21098 -- Sensitive POST parameters cannot be seen in the error reports for if request.POST['nonexistent_key'] throws an error. """ with self.settings(DEBUG=True): self.verify_unsafe_response(multivalue_dict_key_error) self.verify_unsafe_email(multivalue_dict_key_error) with self.settings(DEBUG=False): self.verify_safe_response(multivalue_dict_key_error) self.verify_safe_email(multivalue_dict_key_error) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) def test_sensitive_method(self): """ The sensitive_variables decorator works with object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_method_view, check_for_POST_params=False) self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_method_view, check_for_POST_params=False) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False) def test_sensitive_function_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False) def test_sensitive_function_keyword_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as keyword arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False) def test_callable_settings(self): """ Callable settings should not be evaluated in the debug page (#21345). """ def callable_setting(): return "This should not be displayed" with self.settings(DEBUG=True, FOOBAR=callable_setting): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_callable_settings_forbidding_to_set_attributes(self): """ Callable settings which forbid to set attributes should not break the debug page (#23070). """ class CallableSettingWithSlots: __slots__ = [] def __call__(self): return "This should not be displayed" with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_dict_setting_with_non_str_key(self): """ A dict setting containing a non-string key should not break the debug page (#12744). """ with self.settings(DEBUG=True, FOOBAR={42: None}): response = self.client.get('/raises500/') self.assertContains(response, 'FOOBAR', status_code=500) def test_sensitive_settings(self): """ The debug page should not show some sensitive settings (password, secret key, ...). """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: with self.settings(DEBUG=True, **{setting: "should not be displayed"}): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_settings_with_sensitive_keys(self): """ The debug page should filter out some sensitive information found in dict settings. """ sensitive_settings = [ 'SECRET_KEY', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: FOOBAR = { setting: "should not be displayed", 'recursive': {setting: "should not be displayed"}, } with self.settings(DEBUG=True, FOOBAR=FOOBAR): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) class AjaxResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports. Here we specifically test the plain text 500 debug-only error page served when it has been detected the request was sent by JS code. We don't check for (non)existence of frames vars in the traceback information section of the response content because we don't include them in these error pages. Refs #14614. """ rf = RequestFactory(HTTP_X_REQUESTED_WITH='XMLHttpRequest') def test_non_sensitive_request(self): """ Request info can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) def test_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view, check_for_vars=False) def test_paranoid_request(self): """ No POST parameters can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view, check_for_vars=False) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') def test_ajax_response_encoding(self): response = self.client.get('/raises500/', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response['Content-Type'], 'text/plain; charset=utf-8') class HelperFunctionTests(SimpleTestCase): def test_cleanse_setting_basic(self): self.assertEqual(cleanse_setting('TEST', 'TEST'), 'TEST') self.assertEqual(cleanse_setting('PASSWORD', 'super_secret'), CLEANSED_SUBSTITUTE) def test_cleanse_setting_ignore_case(self): self.assertEqual(cleanse_setting('password', 'super_secret'), CLEANSED_SUBSTITUTE) def test_cleanse_setting_recurses_in_dictionary(self): initial = {'login': 'cooper', 'password': 'secret'} expected = {'login': 'cooper', 'password': CLEANSED_SUBSTITUTE} self.assertEqual(cleanse_setting('SETTING_NAME', initial), expected)
dabf3c94138db118c025d32770051cf6f95ab8ec1dd125c21cd4c8dd9140e391
"""Models for test_natural.py""" import uuid from django.db import models class NaturalKeyAnchorManager(models.Manager): def get_by_natural_key(self, data): return self.get(data=data) class NaturalKeyAnchor(models.Model): data = models.CharField(max_length=100, unique=True) title = models.CharField(max_length=100, null=True) objects = NaturalKeyAnchorManager() def natural_key(self): return (self.data,) class FKDataNaturalKey(models.Model): data = models.ForeignKey(NaturalKeyAnchor, models.SET_NULL, null=True) class NaturalKeyThing(models.Model): key = models.CharField(max_length=100) other_thing = models.ForeignKey('NaturalKeyThing', on_delete=models.CASCADE, null=True) other_things = models.ManyToManyField('NaturalKeyThing', related_name='thing_m2m_set') class Manager(models.Manager): def get_by_natural_key(self, key): return self.get(key=key) objects = Manager() def natural_key(self): return (self.key,) def __str__(self): return self.key class NaturalPKWithDefault(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, unique=True) class Manager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) objects = Manager() def natural_key(self): return (self.name,)
6d2d5ac6aa08a78b589c373cf5700862ba5d5b197dbcfdc05a170f7ba9e3e2f4
from django.template import TemplateSyntaxError from django.test import SimpleTestCase from ..utils import SomeClass, SomeOtherException, UTF8Class, setup class FilterSyntaxTests(SimpleTestCase): @setup({'filter-syntax01': '{{ var|upper }}'}) def test_filter_syntax01(self): """ Basic filter usage """ output = self.engine.render_to_string('filter-syntax01', {"var": "Django is the greatest!"}) self.assertEqual(output, "DJANGO IS THE GREATEST!") @setup({'filter-syntax02': '{{ var|upper|lower }}'}) def test_filter_syntax02(self): """ Chained filters """ output = self.engine.render_to_string('filter-syntax02', {"var": "Django is the greatest!"}) self.assertEqual(output, "django is the greatest!") @setup({'filter-syntax03': '{{ var |upper }}'}) def test_filter_syntax03(self): """ Allow spaces before the filter pipe """ output = self.engine.render_to_string('filter-syntax03', {'var': 'Django is the greatest!'}) self.assertEqual(output, 'DJANGO IS THE GREATEST!') @setup({'filter-syntax04': '{{ var| upper }}'}) def test_filter_syntax04(self): """ Allow spaces after the filter pipe """ output = self.engine.render_to_string('filter-syntax04', {'var': 'Django is the greatest!'}) self.assertEqual(output, 'DJANGO IS THE GREATEST!') @setup({'filter-syntax05': '{{ var|does_not_exist }}'}) def test_filter_syntax05(self): """ Raise TemplateSyntaxError for a nonexistent filter """ msg = "Invalid filter: 'does_not_exist'" with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.get_template('filter-syntax05') @setup({'filter-syntax06': '{{ var|fil(ter) }}'}) def test_filter_syntax06(self): """ Raise TemplateSyntaxError when trying to access a filter containing an illegal character """ with self.assertRaisesMessage(TemplateSyntaxError, "Invalid filter: 'fil'"): self.engine.get_template('filter-syntax06') @setup({'filter-syntax07': "{% nothing_to_see_here %}"}) def test_filter_syntax07(self): """ Raise TemplateSyntaxError for invalid block tags """ msg = ( "Invalid block tag on line 1: 'nothing_to_see_here'. Did you " "forget to register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.get_template('filter-syntax07') @setup({'filter-syntax08': "{% %}"}) def test_filter_syntax08(self): """ Raise TemplateSyntaxError for empty block tags """ with self.assertRaisesMessage(TemplateSyntaxError, 'Empty block tag on line 1'): self.engine.get_template('filter-syntax08') @setup({'filter-syntax08-multi-line': "line 1\nline 2\nline 3{% %}\nline 4\nline 5"}) def test_filter_syntax08_multi_line(self): """ Raise TemplateSyntaxError for empty block tags in templates with multiple lines. """ with self.assertRaisesMessage(TemplateSyntaxError, 'Empty block tag on line 3'): self.engine.get_template('filter-syntax08-multi-line') @setup({'filter-syntax09': '{{ var|cut:"o"|upper|lower }}'}) def test_filter_syntax09(self): """ Chained filters, with an argument to the first one """ output = self.engine.render_to_string('filter-syntax09', {'var': 'Foo'}) self.assertEqual(output, 'f') @setup({'filter-syntax10': r'{{ var|default_if_none:" endquote\" hah" }}'}) def test_filter_syntax10(self): """ Literal string as argument is always "safe" from auto-escaping. """ output = self.engine.render_to_string('filter-syntax10', {"var": None}) self.assertEqual(output, ' endquote" hah') @setup({'filter-syntax11': r'{{ var|default_if_none:var2 }}'}) def test_filter_syntax11(self): """ Variable as argument """ output = self.engine.render_to_string('filter-syntax11', {"var": None, "var2": "happy"}) self.assertEqual(output, 'happy') @setup({'filter-syntax13': r'1{{ var.method3 }}2'}) def test_filter_syntax13(self): """ Fail silently for methods that raise an exception with a `silent_variable_failure` attribute """ output = self.engine.render_to_string('filter-syntax13', {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "1INVALID2") else: self.assertEqual(output, "12") @setup({'filter-syntax14': r'1{{ var.method4 }}2'}) def test_filter_syntax14(self): """ In methods that raise an exception without a `silent_variable_attribute` set to True, the exception propagates """ with self.assertRaises(SomeOtherException): self.engine.render_to_string('filter-syntax14', {"var": SomeClass()}) @setup({'filter-syntax15': r'{{ var|default_if_none:"foo\bar" }}'}) def test_filter_syntax15(self): """ Escaped backslash in argument """ output = self.engine.render_to_string('filter-syntax15', {"var": None}) self.assertEqual(output, r'foo\bar') @setup({'filter-syntax16': r'{{ var|default_if_none:"foo\now" }}'}) def test_filter_syntax16(self): """ Escaped backslash using known escape char """ output = self.engine.render_to_string('filter-syntax16', {"var": None}) self.assertEqual(output, r'foo\now') @setup({'filter-syntax17': r'{{ var|join:"" }}'}) def test_filter_syntax17(self): """ Empty strings can be passed as arguments to filters """ output = self.engine.render_to_string('filter-syntax17', {'var': ['a', 'b', 'c']}) self.assertEqual(output, 'abc') @setup({'filter-syntax18': r'{{ var }}'}) def test_filter_syntax18(self): """ Strings are converted to bytestrings in the final output. """ output = self.engine.render_to_string('filter-syntax18', {'var': UTF8Class()}) self.assertEqual(output, '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') @setup({'filter-syntax19': '{{ var|truncatewords:1 }}'}) def test_filter_syntax19(self): """ Numbers as filter arguments should work """ output = self.engine.render_to_string('filter-syntax19', {"var": "hello world"}) self.assertEqual(output, "hello …") @setup({'filter-syntax20': '{{ ""|default_if_none:"was none" }}'}) def test_filter_syntax20(self): """ Filters should accept empty string constants """ output = self.engine.render_to_string('filter-syntax20') self.assertEqual(output, "") @setup({'filter-syntax21': r'1{{ var.silent_fail_key }}2'}) def test_filter_syntax21(self): """ Fail silently for non-callable attribute and dict lookups which raise an exception with a "silent_variable_failure" attribute """ output = self.engine.render_to_string('filter-syntax21', {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "1INVALID2") else: self.assertEqual(output, "12") @setup({'filter-syntax22': r'1{{ var.silent_fail_attribute }}2'}) def test_filter_syntax22(self): """ Fail silently for non-callable attribute and dict lookups which raise an exception with a `silent_variable_failure` attribute """ output = self.engine.render_to_string('filter-syntax22', {"var": SomeClass()}) if self.engine.string_if_invalid: self.assertEqual(output, "1INVALID2") else: self.assertEqual(output, "12") @setup({'filter-syntax23': r'1{{ var.noisy_fail_key }}2'}) def test_filter_syntax23(self): """ In attribute and dict lookups that raise an unexpected exception without a `silent_variable_attribute` set to True, the exception propagates """ with self.assertRaises(SomeOtherException): self.engine.render_to_string('filter-syntax23', {"var": SomeClass()}) @setup({'filter-syntax24': r'1{{ var.noisy_fail_attribute }}2'}) def test_filter_syntax24(self): """ In attribute and dict lookups that raise an unexpected exception without a `silent_variable_attribute` set to True, the exception propagates """ with self.assertRaises(SomeOtherException): self.engine.render_to_string('filter-syntax24', {"var": SomeClass()}) @setup({'filter-syntax25': '{{ var.attribute_error_attribute }}'}) def test_filter_syntax25(self): """ #16383 - Attribute errors from an @property value should be reraised. """ with self.assertRaises(AttributeError): self.engine.render_to_string('filter-syntax25', {'var': SomeClass()}) @setup({'template': '{{ var.type_error_attribute }}'}) def test_type_error_attribute(self): with self.assertRaises(TypeError): self.engine.render_to_string('template', {'var': SomeClass()})
918953fd20d9a30fb6773965d0c3da3dd599220006823e0f315030577d86b5b1
from django.core.cache import cache from django.template import Context, Engine, TemplateSyntaxError from django.test import SimpleTestCase, override_settings from ..utils import setup class CacheTagTests(SimpleTestCase): libraries = { 'cache': 'django.templatetags.cache', 'custom': 'template_tests.templatetags.custom', } def tearDown(self): cache.clear() @setup({'cache03': '{% load cache %}{% cache 2 test %}cache03{% endcache %}'}) def test_cache03(self): output = self.engine.render_to_string('cache03') self.assertEqual(output, 'cache03') @setup({ 'cache03': '{% load cache %}{% cache 2 test %}cache03{% endcache %}', 'cache04': '{% load cache %}{% cache 2 test %}cache04{% endcache %}', }) def test_cache04(self): self.engine.render_to_string('cache03') output = self.engine.render_to_string('cache04') self.assertEqual(output, 'cache03') @setup({'cache05': '{% load cache %}{% cache 2 test foo %}cache05{% endcache %}'}) def test_cache05(self): output = self.engine.render_to_string('cache05', {'foo': 1}) self.assertEqual(output, 'cache05') @setup({'cache06': '{% load cache %}{% cache 2 test foo %}cache06{% endcache %}'}) def test_cache06(self): output = self.engine.render_to_string('cache06', {'foo': 2}) self.assertEqual(output, 'cache06') @setup({ 'cache05': '{% load cache %}{% cache 2 test foo %}cache05{% endcache %}', 'cache07': '{% load cache %}{% cache 2 test foo %}cache07{% endcache %}', }) def test_cache07(self): context = {'foo': 1} self.engine.render_to_string('cache05', context) output = self.engine.render_to_string('cache07', context) self.assertEqual(output, 'cache05') @setup({ 'cache06': '{% load cache %}{% cache 2 test foo %}cache06{% endcache %}', 'cache08': '{% load cache %}{% cache time test foo %}cache08{% endcache %}', }) def test_cache08(self): """ Allow first argument to be a variable. """ context = {'foo': 2, 'time': 2} self.engine.render_to_string('cache06', context) output = self.engine.render_to_string('cache08', context) self.assertEqual(output, 'cache06') # Raise exception if we don't have at least 2 args, first one integer. @setup({'cache11': '{% load cache %}{% cache %}{% endcache %}'}) def test_cache11(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('cache11') @setup({'cache12': '{% load cache %}{% cache 1 %}{% endcache %}'}) def test_cache12(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('cache12') @setup({'cache13': '{% load cache %}{% cache foo bar %}{% endcache %}'}) def test_cache13(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('cache13') @setup({'cache14': '{% load cache %}{% cache foo bar %}{% endcache %}'}) def test_cache14(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('cache14', {'foo': 'fail'}) @setup({'cache15': '{% load cache %}{% cache foo bar %}{% endcache %}'}) def test_cache15(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('cache15', {'foo': []}) @setup({'cache16': '{% load cache %}{% cache 1 foo bar %}{% endcache %}'}) def test_cache16(self): """ Regression test for #7460. """ output = self.engine.render_to_string('cache16', {'foo': 'foo', 'bar': 'with spaces'}) self.assertEqual(output, '') @setup({'cache17': '{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}'}) def test_cache17(self): """ Regression test for #11270. """ output = self.engine.render_to_string( 'cache17', { 'poem': ( 'Oh freddled gruntbuggly/Thy micturations are to me/' 'As plurdled gabbleblotchits/On a lurgid bee/' 'That mordiously hath bitled out/Its earted jurtles/' 'Into a rancid festering/Or else I shall rend thee in the gobberwarts' 'with my blurglecruncheon/See if I don\'t.' ), } ) self.assertEqual(output, 'Some Content') @setup({'cache18': '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}'}) def test_cache18(self): """ Test whitespace in filter arguments """ output = self.engine.render_to_string('cache18') self.assertEqual(output, 'cache18') @setup({ 'first': '{% load cache %}{% cache None fragment19 %}content{% endcache %}', 'second': '{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}' }) def test_none_timeout(self): """A timeout of None means "cache forever".""" output = self.engine.render_to_string('first') self.assertEqual(output, 'content') output = self.engine.render_to_string('second') self.assertEqual(output, 'content') class CacheTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(libraries={'cache': 'django.templatetags.cache'}) super().setUpClass() def test_cache_regression_20130(self): t = self.engine.from_string('{% load cache %}{% cache 1 regression_20130 %}foo{% endcache %}') cachenode = t.nodelist[1] self.assertEqual(cachenode.fragment_name, 'regression_20130') @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'default', }, 'template_fragments': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'fragments', }, }) def test_cache_fragment_cache(self): """ When a cache called "template_fragments" is present, the cache tag will use it in preference to 'default' """ t1 = self.engine.from_string('{% load cache %}{% cache 1 fragment %}foo{% endcache %}') t2 = self.engine.from_string('{% load cache %}{% cache 1 fragment using="default" %}bar{% endcache %}') ctx = Context() o1 = t1.render(ctx) o2 = t2.render(ctx) self.assertEqual(o1, 'foo') self.assertEqual(o2, 'bar') def test_cache_missing_backend(self): """ When a cache that doesn't exist is specified, the cache tag will raise a TemplateSyntaxError '""" t = self.engine.from_string('{% load cache %}{% cache 1 backend using="unknown" %}bar{% endcache %}') ctx = Context() with self.assertRaises(TemplateSyntaxError): t.render(ctx)
d0962292a23a61c358cebc35e833a644fae6cc634cd1f0e92336a244388a1e23
from django.template import RequestContext, TemplateSyntaxError from django.test import RequestFactory, SimpleTestCase, override_settings from django.urls import NoReverseMatch, resolve from ..utils import setup @override_settings(ROOT_URLCONF='template_tests.urls') class UrlTagTests(SimpleTestCase): request_factory = RequestFactory() # Successes @setup({'url01': '{% url "client" client.id %}'}) def test_url01(self): output = self.engine.render_to_string('url01', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/') @setup({'url02': '{% url "client_action" id=client.id action="update" %}'}) def test_url02(self): output = self.engine.render_to_string('url02', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/update/') @setup({'url02a': '{% url "client_action" client.id "update" %}'}) def test_url02a(self): output = self.engine.render_to_string('url02a', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/update/') @setup({'url02b': "{% url 'client_action' id=client.id action='update' %}"}) def test_url02b(self): output = self.engine.render_to_string('url02b', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/update/') @setup({'url02c': "{% url 'client_action' client.id 'update' %}"}) def test_url02c(self): output = self.engine.render_to_string('url02c', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/update/') @setup({'url03': '{% url "index" %}'}) def test_url03(self): output = self.engine.render_to_string('url03') self.assertEqual(output, '/') @setup({'url04': '{% url "named.client" client.id %}'}) def test_url04(self): output = self.engine.render_to_string('url04', {'client': {'id': 1}}) self.assertEqual(output, '/named-client/1/') @setup({'url05': '{% url "метка_оператора" v %}'}) def test_url05(self): output = self.engine.render_to_string('url05', {'v': 'Ω'}) self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') @setup({'url06': '{% url "метка_оператора_2" tag=v %}'}) def test_url06(self): output = self.engine.render_to_string('url06', {'v': 'Ω'}) self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') @setup({'url08': '{% url "метка_оператора" v %}'}) def test_url08(self): output = self.engine.render_to_string('url08', {'v': 'Ω'}) self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') @setup({'url09': '{% url "метка_оператора_2" tag=v %}'}) def test_url09(self): output = self.engine.render_to_string('url09', {'v': 'Ω'}) self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/') @setup({'url10': '{% url "client_action" id=client.id action="two words" %}'}) def test_url10(self): output = self.engine.render_to_string('url10', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/two%20words/') @setup({'url11': '{% url "client_action" id=client.id action="==" %}'}) def test_url11(self): output = self.engine.render_to_string('url11', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/==/') @setup({'url12': '{% url "client_action" id=client.id action="!$&\'()*+,;=~:@," %}'}) def test_url12(self): output = self.engine.render_to_string('url12', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/!$&amp;&#x27;()*+,;=~:@,/') @setup({'url13': '{% url "client_action" id=client.id action=arg|join:"-" %}'}) def test_url13(self): output = self.engine.render_to_string('url13', {'client': {'id': 1}, 'arg': ['a', 'b']}) self.assertEqual(output, '/client/1/a-b/') @setup({'url14': '{% url "client_action" client.id arg|join:"-" %}'}) def test_url14(self): output = self.engine.render_to_string('url14', {'client': {'id': 1}, 'arg': ['a', 'b']}) self.assertEqual(output, '/client/1/a-b/') @setup({'url15': '{% url "client_action" 12 "test" %}'}) def test_url15(self): output = self.engine.render_to_string('url15') self.assertEqual(output, '/client/12/test/') @setup({'url18': '{% url "client" "1,2" %}'}) def test_url18(self): output = self.engine.render_to_string('url18') self.assertEqual(output, '/client/1,2/') @setup({'url19': '{% url named_url client.id %}'}) def test_url19(self): output = self.engine.render_to_string( 'url19', {'client': {'id': 1}, 'named_url': 'client'} ) self.assertEqual(output, '/client/1/') @setup({'url20': '{% url url_name_in_var client.id %}'}) def test_url20(self): output = self.engine.render_to_string('url20', {'client': {'id': 1}, 'url_name_in_var': 'named.client'}) self.assertEqual(output, '/named-client/1/') @setup({'url21': '{% autoescape off %}' '{% url "client_action" id=client.id action="!$&\'()*+,;=~:@," %}' '{% endautoescape %}'}) def test_url21(self): output = self.engine.render_to_string('url21', {'client': {'id': 1}}) self.assertEqual(output, '/client/1/!$&\'()*+,;=~:@,/') # Failures @setup({'url-fail01': '{% url %}'}) def test_url_fail01(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('url-fail01') @setup({'url-fail02': '{% url "no_such_view" %}'}) def test_url_fail02(self): with self.assertRaises(NoReverseMatch): self.engine.render_to_string('url-fail02') @setup({'url-fail03': '{% url "client" %}'}) def test_url_fail03(self): with self.assertRaises(NoReverseMatch): self.engine.render_to_string('url-fail03') @setup({'url-fail04': '{% url "view" id, %}'}) def test_url_fail04(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('url-fail04') @setup({'url-fail05': '{% url "view" id= %}'}) def test_url_fail05(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('url-fail05') @setup({'url-fail06': '{% url "view" a.id=id %}'}) def test_url_fail06(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('url-fail06') @setup({'url-fail07': '{% url "view" a.id!id %}'}) def test_url_fail07(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('url-fail07') @setup({'url-fail08': '{% url "view" id="unterminatedstring %}'}) def test_url_fail08(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('url-fail08') @setup({'url-fail09': '{% url "view" id=", %}'}) def test_url_fail09(self): with self.assertRaises(TemplateSyntaxError): self.engine.get_template('url-fail09') @setup({'url-fail11': '{% url named_url %}'}) def test_url_fail11(self): with self.assertRaises(NoReverseMatch): self.engine.render_to_string('url-fail11') @setup({'url-fail12': '{% url named_url %}'}) def test_url_fail12(self): with self.assertRaises(NoReverseMatch): self.engine.render_to_string('url-fail12', {'named_url': 'no_such_view'}) @setup({'url-fail13': '{% url named_url %}'}) def test_url_fail13(self): with self.assertRaises(NoReverseMatch): self.engine.render_to_string('url-fail13', {'named_url': 'template_tests.views.client'}) @setup({'url-fail14': '{% url named_url id, %}'}) def test_url_fail14(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('url-fail14', {'named_url': 'view'}) @setup({'url-fail15': '{% url named_url id= %}'}) def test_url_fail15(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('url-fail15', {'named_url': 'view'}) @setup({'url-fail16': '{% url named_url a.id=id %}'}) def test_url_fail16(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('url-fail16', {'named_url': 'view'}) @setup({'url-fail17': '{% url named_url a.id!id %}'}) def test_url_fail17(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('url-fail17', {'named_url': 'view'}) @setup({'url-fail18': '{% url named_url id="unterminatedstring %}'}) def test_url_fail18(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('url-fail18', {'named_url': 'view'}) @setup({'url-fail19': '{% url named_url id=", %}'}) def test_url_fail19(self): with self.assertRaises(TemplateSyntaxError): self.engine.render_to_string('url-fail19', {'named_url': 'view'}) # {% url ... as var %} @setup({'url-asvar01': '{% url "index" as url %}'}) def test_url_asvar01(self): output = self.engine.render_to_string('url-asvar01') self.assertEqual(output, '') @setup({'url-asvar02': '{% url "index" as url %}{{ url }}'}) def test_url_asvar02(self): output = self.engine.render_to_string('url-asvar02') self.assertEqual(output, '/') @setup({'url-asvar03': '{% url "no_such_view" as url %}{{ url }}'}) def test_url_asvar03(self): output = self.engine.render_to_string('url-asvar03') self.assertEqual(output, '') @setup({'url-namespace01': '{% url "app:named.client" 42 %}'}) def test_url_namespace01(self): request = self.request_factory.get('/') request.resolver_match = resolve('/ns1/') template = self.engine.get_template('url-namespace01') context = RequestContext(request) output = template.render(context) self.assertEqual(output, '/ns1/named-client/42/') @setup({'url-namespace02': '{% url "app:named.client" 42 %}'}) def test_url_namespace02(self): request = self.request_factory.get('/') request.resolver_match = resolve('/ns2/') template = self.engine.get_template('url-namespace02') context = RequestContext(request) output = template.render(context) self.assertEqual(output, '/ns2/named-client/42/') @setup({'url-namespace03': '{% url "app:named.client" 42 %}'}) def test_url_namespace03(self): request = self.request_factory.get('/') template = self.engine.get_template('url-namespace03') context = RequestContext(request) output = template.render(context) self.assertEqual(output, '/ns2/named-client/42/') @setup({'url-namespace-no-current-app': '{% url "app:named.client" 42 %}'}) def test_url_namespace_no_current_app(self): request = self.request_factory.get('/') request.resolver_match = resolve('/ns1/') request.current_app = None template = self.engine.get_template('url-namespace-no-current-app') context = RequestContext(request) output = template.render(context) self.assertEqual(output, '/ns2/named-client/42/') @setup({'url-namespace-explicit-current-app': '{% url "app:named.client" 42 %}'}) def test_url_namespace_explicit_current_app(self): request = self.request_factory.get('/') request.resolver_match = resolve('/ns1/') request.current_app = 'app' template = self.engine.get_template('url-namespace-explicit-current-app') context = RequestContext(request) output = template.render(context) self.assertEqual(output, '/ns2/named-client/42/')
93cd63174184a937113cc77d186fd35280e01533329b0bf08081aff1e629b1fb
from django.template.defaultfilters import urlizetrunc from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class UrlizetruncTests(SimpleTestCase): @setup({ 'urlizetrunc01': '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% endautoescape %}' }) def test_urlizetrunc01(self): output = self.engine.render_to_string( 'urlizetrunc01', { 'a': '"Unsafe" http://example.com/x=&y=', 'b': mark_safe('&quot;Safe&quot; http://example.com?x=&amp;y='), }, ) self.assertEqual( output, '"Unsafe" <a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> ' '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>' ) @setup({'urlizetrunc02': '{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'}) def test_urlizetrunc02(self): output = self.engine.render_to_string( 'urlizetrunc02', { 'a': '"Unsafe" http://example.com/x=&y=', 'b': mark_safe('&quot;Safe&quot; http://example.com?x=&amp;y='), }, ) self.assertEqual( output, '&quot;Unsafe&quot; <a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> ' '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>' ) class FunctionTests(SimpleTestCase): def test_truncate(self): uri = 'http://31characteruri.com/test/' self.assertEqual(len(uri), 31) self.assertEqual( urlizetrunc(uri, 31), '<a href="http://31characteruri.com/test/" rel="nofollow">' 'http://31characteruri.com/test/</a>', ) self.assertEqual( urlizetrunc(uri, 30), '<a href="http://31characteruri.com/test/" rel="nofollow">' 'http://31characteruri.com/tes…</a>', ) self.assertEqual( urlizetrunc(uri, 1), '<a href="http://31characteruri.com/test/"' ' rel="nofollow">…</a>', ) def test_overtruncate(self): self.assertEqual( urlizetrunc('http://short.com/', 20), '<a href=' '"http://short.com/" rel="nofollow">http://short.com/</a>', ) def test_query_string(self): self.assertEqual( urlizetrunc('http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=', 20), '<a href="http://www.google.co.uk/search?hl=en&amp;q=some+long+url&amp;btnG=Search&amp;' 'meta=" rel="nofollow">http://www.google.c…</a>', ) def test_non_string_input(self): self.assertEqual(urlizetrunc(123, 1), '123') def test_autoescape(self): self.assertEqual( urlizetrunc('foo<a href=" google.com ">bar</a>buz', 10), 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com</a> &quot;&gt;bar&lt;/a&gt;buz' ) def test_autoescape_off(self): self.assertEqual( urlizetrunc('foo<a href=" google.com ">bar</a>buz', 9, autoescape=False), 'foo<a href=" <a href="http://google.com" rel="nofollow">google.c…</a> ">bar</a>buz', )
060fccb7271f000ab6c8da21345653e22d109883a615b407b57ce5ba6d41ca98
from django.template.defaultfilters import addslashes from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class AddslashesTests(SimpleTestCase): @setup({'addslashes01': '{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}'}) def test_addslashes01(self): output = self.engine.render_to_string('addslashes01', {"a": "<a>'", "b": mark_safe("<a>'")}) self.assertEqual(output, r"<a>\' <a>\'") @setup({'addslashes02': '{{ a|addslashes }} {{ b|addslashes }}'}) def test_addslashes02(self): output = self.engine.render_to_string('addslashes02', {"a": "<a>'", "b": mark_safe("<a>'")}) self.assertEqual(output, r"&lt;a&gt;\&#x27; <a>\'") class FunctionTests(SimpleTestCase): def test_quotes(self): self.assertEqual( addslashes('"double quotes" and \'single quotes\''), '\\"double quotes\\" and \\\'single quotes\\\'', ) def test_backslashes(self): self.assertEqual(addslashes(r'\ : backslashes, too'), '\\\\ : backslashes, too') def test_non_string_input(self): self.assertEqual(addslashes(123), '123')
e431ac1042f25e0602a2175c99ceb66acf7e548f8831065aa4a447e9fb083a0c
from django.template.defaultfilters import truncatewords from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class TruncatewordsTests(SimpleTestCase): @setup({ 'truncatewords01': '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}' }) def test_truncatewords01(self): output = self.engine.render_to_string( 'truncatewords01', {'a': 'alpha & bravo', 'b': mark_safe('alpha &amp; bravo')} ) self.assertEqual(output, 'alpha & … alpha &amp; …') @setup({'truncatewords02': '{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'}) def test_truncatewords02(self): output = self.engine.render_to_string( 'truncatewords02', {'a': 'alpha & bravo', 'b': mark_safe('alpha &amp; bravo')} ) self.assertEqual(output, 'alpha &amp; … alpha &amp; …') class FunctionTests(SimpleTestCase): def test_truncate(self): self.assertEqual(truncatewords('A sentence with a few words in it', 1), 'A …') def test_truncate2(self): self.assertEqual( truncatewords('A sentence with a few words in it', 5), 'A sentence with a few …', ) def test_overtruncate(self): self.assertEqual( truncatewords('A sentence with a few words in it', 100), 'A sentence with a few words in it', ) def test_invalid_number(self): self.assertEqual( truncatewords('A sentence with a few words in it', 'not a number'), 'A sentence with a few words in it', ) def test_non_string_input(self): self.assertEqual(truncatewords(123, 2), '123')
d1c77667b28e745b85750cad12ccce6ca2c6cf229a8b844dc3f8cea109d5ee22
from django.template.defaultfilters import make_list from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class MakeListTests(SimpleTestCase): """ The make_list filter can destroy existing escaping, so the results are escaped. """ @setup({'make_list01': '{% autoescape off %}{{ a|make_list }}{% endautoescape %}'}) def test_make_list01(self): output = self.engine.render_to_string('make_list01', {"a": mark_safe("&")}) self.assertEqual(output, "['&']") @setup({'make_list02': '{{ a|make_list }}'}) def test_make_list02(self): output = self.engine.render_to_string('make_list02', {"a": mark_safe("&")}) self.assertEqual(output, '[&#x27;&amp;&#x27;]') @setup({'make_list03': '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}'}) def test_make_list03(self): output = self.engine.render_to_string('make_list03', {"a": mark_safe("&")}) self.assertEqual(output, "['&']") @setup({'make_list04': '{{ a|make_list|stringformat:"s"|safe }}'}) def test_make_list04(self): output = self.engine.render_to_string('make_list04', {"a": mark_safe("&")}) self.assertEqual(output, "['&']") class FunctionTests(SimpleTestCase): def test_string(self): self.assertEqual(make_list('abc'), ['a', 'b', 'c']) def test_integer(self): self.assertEqual(make_list(1234), ['1', '2', '3', '4'])
e1a437352bc815caf9b60c025def633a8375e4bf85abbcef2a371c0e05769404
from django.template.defaultfilters import urlize from django.test import SimpleTestCase from django.utils.functional import lazy from django.utils.safestring import mark_safe from ..utils import setup class UrlizeTests(SimpleTestCase): @setup({'urlize01': '{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}'}) def test_urlize01(self): output = self.engine.render_to_string( 'urlize01', {'a': 'http://example.com/?x=&y=', 'b': mark_safe('http://example.com?x=&amp;y=&lt;2&gt;')}, ) self.assertEqual( output, '<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&y=</a> ' '<a href="http://example.com?x=&amp;y=%3C2%3E" rel="nofollow">http://example.com?x=&amp;y=&lt;2&gt;</a>' ) @setup({'urlize02': '{{ a|urlize }} {{ b|urlize }}'}) def test_urlize02(self): output = self.engine.render_to_string( 'urlize02', {'a': "http://example.com/?x=&y=", 'b': mark_safe("http://example.com?x=&amp;y=")}, ) self.assertEqual( output, '<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&amp;y=</a> ' '<a href="http://example.com?x=&amp;y=" rel="nofollow">http://example.com?x=&amp;y=</a>' ) @setup({'urlize03': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'}) def test_urlize03(self): output = self.engine.render_to_string('urlize03', {'a': mark_safe("a &amp; b")}) self.assertEqual(output, 'a &amp; b') @setup({'urlize04': '{{ a|urlize }}'}) def test_urlize04(self): output = self.engine.render_to_string('urlize04', {'a': mark_safe("a &amp; b")}) self.assertEqual(output, 'a &amp; b') # This will lead to a nonsense result, but at least it won't be # exploitable for XSS purposes when auto-escaping is on. @setup({'urlize05': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'}) def test_urlize05(self): output = self.engine.render_to_string('urlize05', {'a': "<script>alert('foo')</script>"}) self.assertEqual(output, "<script>alert('foo')</script>") @setup({'urlize06': '{{ a|urlize }}'}) def test_urlize06(self): output = self.engine.render_to_string('urlize06', {'a': "<script>alert('foo')</script>"}) self.assertEqual(output, '&lt;script&gt;alert(&#x27;foo&#x27;)&lt;/script&gt;') # mailto: testing for urlize @setup({'urlize07': '{{ a|urlize }}'}) def test_urlize07(self): output = self.engine.render_to_string('urlize07', {'a': "Email me at [email protected]"}) self.assertEqual( output, 'Email me at <a href="mailto:[email protected]">[email protected]</a>', ) @setup({'urlize08': '{{ a|urlize }}'}) def test_urlize08(self): output = self.engine.render_to_string('urlize08', {'a': "Email me at <[email protected]>"}) self.assertEqual( output, 'Email me at &lt;<a href="mailto:[email protected]">[email protected]</a>&gt;', ) @setup({'urlize09': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'}) def test_urlize09(self): output = self.engine.render_to_string('urlize09', {'a': "http://example.com/?x=&amp;y=&lt;2&gt;"}) self.assertEqual( output, '<a href="http://example.com/?x=&amp;y=%3C2%3E" rel="nofollow">http://example.com/?x=&amp;y=&lt;2&gt;</a>', ) class FunctionTests(SimpleTestCase): def test_urls(self): self.assertEqual( urlize('http://google.com'), '<a href="http://google.com" rel="nofollow">http://google.com</a>', ) self.assertEqual( urlize('http://google.com/'), '<a href="http://google.com/" rel="nofollow">http://google.com/</a>', ) self.assertEqual( urlize('www.google.com'), '<a href="http://www.google.com" rel="nofollow">www.google.com</a>', ) self.assertEqual( urlize('djangoproject.org'), '<a href="http://djangoproject.org" rel="nofollow">djangoproject.org</a>', ) self.assertEqual( urlize('djangoproject.org/'), '<a href="http://djangoproject.org/" rel="nofollow">djangoproject.org/</a>', ) def test_url_split_chars(self): # Quotes (single and double) and angle brackets shouldn't be considered # part of URLs. self.assertEqual( urlize('www.server.com"abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&quot;abc', ) self.assertEqual( urlize('www.server.com\'abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&#x27;abc', ) self.assertEqual( urlize('www.server.com<abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&lt;abc', ) self.assertEqual( urlize('www.server.com>abc'), '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&gt;abc', ) def test_email(self): self.assertEqual( urlize('[email protected]'), '<a href="mailto:[email protected]">[email protected]</a>', ) def test_word_with_dot(self): self.assertEqual(urlize('some.organization'), 'some.organization'), def test_https(self): self.assertEqual( urlize('https://google.com'), '<a href="https://google.com" rel="nofollow">https://google.com</a>', ) def test_quoting(self): """ #9655 - Check urlize doesn't overquote already quoted urls. The teststring is the urlquoted version of 'http://hi.baidu.com/重新开始' """ self.assertEqual( urlize('http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B'), '<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" rel="nofollow">' 'http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B</a>', ) def test_urlencoded(self): self.assertEqual( urlize('www.mystore.com/30%OffCoupons!'), '<a href="http://www.mystore.com/30%25OffCoupons" rel="nofollow">' 'www.mystore.com/30%OffCoupons</a>!', ) self.assertEqual( urlize('https://en.wikipedia.org/wiki/Caf%C3%A9'), '<a href="https://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">' 'https://en.wikipedia.org/wiki/Caf%C3%A9</a>', ) def test_unicode(self): self.assertEqual( urlize('https://en.wikipedia.org/wiki/Café'), '<a href="https://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">' 'https://en.wikipedia.org/wiki/Café</a>', ) def test_parenthesis(self): """ #11911 - Check urlize keeps balanced parentheses """ self.assertEqual( urlize('https://en.wikipedia.org/wiki/Django_(web_framework)'), '<a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">' 'https://en.wikipedia.org/wiki/Django_(web_framework)</a>', ) self.assertEqual( urlize('(see https://en.wikipedia.org/wiki/Django_(web_framework))'), '(see <a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">' 'https://en.wikipedia.org/wiki/Django_(web_framework)</a>)', ) def test_nofollow(self): """ #12183 - Check urlize adds nofollow properly - see #12183 """ self.assertEqual( urlize('[email protected] or www.bar.com'), '<a href="mailto:[email protected]">[email protected]</a> or ' '<a href="http://www.bar.com" rel="nofollow">www.bar.com</a>', ) def test_idn(self): """ #13704 - Check urlize handles IDN correctly """ self.assertEqual(urlize('http://c✶.ws'), '<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>') self.assertEqual(urlize('www.c✶.ws'), '<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>') self.assertEqual(urlize('c✶.org'), '<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>') self.assertEqual(urlize('info@c✶.org'), '<a href="mailto:[email protected]">info@c✶.org</a>') def test_malformed(self): """ #16395 - Check urlize doesn't highlight malformed URIs """ self.assertEqual(urlize('http:///www.google.com'), 'http:///www.google.com') self.assertEqual(urlize('http://.google.com'), 'http://.google.com') self.assertEqual(urlize('http://@foo.com'), 'http://@foo.com') def test_tlds(self): """ #16656 - Check urlize accepts more TLDs """ self.assertEqual(urlize('usa.gov'), '<a href="http://usa.gov" rel="nofollow">usa.gov</a>') def test_invalid_email(self): """ #17592 - Check urlize don't crash on invalid email with dot-starting domain """ self.assertEqual(urlize('[email protected]'), '[email protected]') def test_uppercase(self): """ #18071 - Check urlize accepts uppercased URL schemes """ self.assertEqual( urlize('HTTPS://github.com/'), '<a href="https://github.com/" rel="nofollow">HTTPS://github.com/</a>', ) def test_trailing_period(self): """ #18644 - Check urlize trims trailing period when followed by parenthesis """ self.assertEqual( urlize('(Go to http://www.example.com/foo.)'), '(Go to <a href="http://www.example.com/foo" rel="nofollow">http://www.example.com/foo</a>.)', ) def test_trailing_multiple_punctuation(self): self.assertEqual( urlize('A test http://testing.com/example..'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>..' ) self.assertEqual( urlize('A test http://testing.com/example!!'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!' ) self.assertEqual( urlize('A test http://testing.com/example!!!'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!!' ) self.assertEqual( urlize('A test http://testing.com/example.,:;)"!'), 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>.,:;)&quot;!' ) def test_brackets(self): """ #19070 - Check urlize handles brackets properly """ self.assertEqual( urlize('[see www.example.com]'), '[see <a href="http://www.example.com" rel="nofollow">www.example.com</a>]', ) self.assertEqual( urlize('see test[at[example.com'), 'see <a href="http://test[at[example.com" rel="nofollow">test[at[example.com</a>', ) self.assertEqual( urlize('[http://168.192.0.1](http://168.192.0.1)'), '[<a href="http://168.192.0.1](http://168.192.0.1)" rel="nofollow">' 'http://168.192.0.1](http://168.192.0.1)</a>', ) def test_wrapping_characters(self): wrapping_chars = ( ('()', ('(', ')')), ('<>', ('&lt;', '&gt;')), ('[]', ('[', ']')), ('""', ('&quot;', '&quot;')), ("''", ('&#x27;', '&#x27;')), ) for wrapping_in, (start_out, end_out) in wrapping_chars: with self.subTest(wrapping_in=wrapping_in): start_in, end_in = wrapping_in self.assertEqual( urlize(start_in + 'https://www.example.org/' + end_in), start_out + '<a href="https://www.example.org/" rel="nofollow">https://www.example.org/</a>' + end_out, ) def test_ipv4(self): self.assertEqual( urlize('http://192.168.0.15/api/9'), '<a href="http://192.168.0.15/api/9" rel="nofollow">http://192.168.0.15/api/9</a>', ) def test_ipv6(self): self.assertEqual( urlize('http://[2001:db8:cafe::2]/api/9'), '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">http://[2001:db8:cafe::2]/api/9</a>', ) def test_quotation_marks(self): """ #20364 - Check urlize correctly include quotation marks in links """ self.assertEqual( urlize('before "[email protected]" afterwards', autoescape=False), 'before "<a href="mailto:[email protected]">[email protected]</a>" afterwards', ) self.assertEqual( urlize('before [email protected]" afterwards', autoescape=False), 'before <a href="mailto:[email protected]">[email protected]</a>" afterwards', ) self.assertEqual( urlize('before "[email protected] afterwards', autoescape=False), 'before "<a href="mailto:[email protected]">[email protected]</a> afterwards', ) self.assertEqual( urlize('before \'[email protected]\' afterwards', autoescape=False), 'before \'<a href="mailto:[email protected]">[email protected]</a>\' afterwards', ) self.assertEqual( urlize('before [email protected]\' afterwards', autoescape=False), 'before <a href="mailto:[email protected]">[email protected]</a>\' afterwards', ) self.assertEqual( urlize('before \'[email protected] afterwards', autoescape=False), 'before \'<a href="mailto:[email protected]">[email protected]</a> afterwards', ) def test_quote_commas(self): """ #20364 - Check urlize copes with commas following URLs in quotes """ self.assertEqual( urlize('Email us at "[email protected]", or phone us at +xx.yy', autoescape=False), 'Email us at "<a href="mailto:[email protected]">[email protected]</a>", or phone us at +xx.yy', ) def test_exclamation_marks(self): """ #23715 - Check urlize correctly handles exclamation marks after TLDs or query string """ self.assertEqual( urlize('Go to djangoproject.com! and enjoy.'), 'Go to <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>! and enjoy.', ) self.assertEqual( urlize('Search for google.com/?q=! and see.'), 'Search for <a href="http://google.com/?q=" rel="nofollow">google.com/?q=</a>! and see.', ) self.assertEqual( urlize('Search for google.com/?q=dj!`? and see.'), 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a> and see.', ) self.assertEqual( urlize('Search for google.com/?q=dj!`?! and see.'), 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a>! and see.', ) def test_non_string_input(self): self.assertEqual(urlize(123), '123') def test_autoescape(self): self.assertEqual( urlize('foo<a href=" google.com ">bar</a>buz'), 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com</a> &quot;&gt;bar&lt;/a&gt;buz' ) def test_autoescape_off(self): self.assertEqual( urlize('foo<a href=" google.com ">bar</a>buz', autoescape=False), 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz', ) def test_lazystring(self): prepend_www = lazy(lambda url: 'www.' + url, str) self.assertEqual( urlize(prepend_www('google.com')), '<a href="http://www.google.com" rel="nofollow">www.google.com</a>', )
f3009e3db74f24e4ff4348180ebcdd376321687e895c366e9badfb587316068e
from django.template.defaultfilters import title from django.test import SimpleTestCase from ..utils import setup class TitleTests(SimpleTestCase): @setup({'title1': '{{ a|title }}'}) def test_title1(self): output = self.engine.render_to_string('title1', {'a': 'JOE\'S CRAB SHACK'}) self.assertEqual(output, 'Joe&#x27;s Crab Shack') @setup({'title2': '{{ a|title }}'}) def test_title2(self): output = self.engine.render_to_string('title2', {'a': '555 WEST 53RD STREET'}) self.assertEqual(output, '555 West 53rd Street') class FunctionTests(SimpleTestCase): def test_title(self): self.assertEqual(title('a nice title, isn\'t it?'), "A Nice Title, Isn't It?") def test_unicode(self): self.assertEqual(title('discoth\xe8que'), 'Discoth\xe8que') def test_non_string_input(self): self.assertEqual(title(123), '123')
376ef2d214192d6956f9d4c6fff439720cf7015eab1f11cad57e7b0af28a13dd
from django.template.defaultfilters import filesizeformat from django.test import SimpleTestCase from django.utils import translation class FunctionTests(SimpleTestCase): def test_formats(self): tests = [ (0, '0\xa0bytes'), (1, '1\xa0byte'), (1023, '1023\xa0bytes'), (1024, '1.0\xa0KB'), (10 * 1024, '10.0\xa0KB'), (1024 * 1024 - 1, '1024.0\xa0KB'), (1024 * 1024, '1.0\xa0MB'), (1024 * 1024 * 50, '50.0\xa0MB'), (1024 * 1024 * 1024 - 1, '1024.0\xa0MB'), (1024 * 1024 * 1024, '1.0\xa0GB'), (1024 * 1024 * 1024 * 1024, '1.0\xa0TB'), (1024 * 1024 * 1024 * 1024 * 1024, '1.0\xa0PB'), (1024 * 1024 * 1024 * 1024 * 1024 * 2000, '2000.0\xa0PB'), (complex(1, -1), '0\xa0bytes'), ('', '0\xa0bytes'), ('\N{GREEK SMALL LETTER ALPHA}', '0\xa0bytes'), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(filesizeformat(value), expected) def test_localized_formats(self): tests = [ (0, '0\xa0Bytes'), (1, '1\xa0Byte'), (1023, '1023\xa0Bytes'), (1024, '1,0\xa0KB'), (10 * 1024, '10,0\xa0KB'), (1024 * 1024 - 1, '1024,0\xa0KB'), (1024 * 1024, '1,0\xa0MB'), (1024 * 1024 * 50, '50,0\xa0MB'), (1024 * 1024 * 1024 - 1, '1024,0\xa0MB'), (1024 * 1024 * 1024, '1,0\xa0GB'), (1024 * 1024 * 1024 * 1024, '1,0\xa0TB'), (1024 * 1024 * 1024 * 1024 * 1024, '1,0\xa0PB'), (1024 * 1024 * 1024 * 1024 * 1024 * 2000, '2000,0\xa0PB'), (complex(1, -1), '0\xa0Bytes'), ('', '0\xa0Bytes'), ('\N{GREEK SMALL LETTER ALPHA}', '0\xa0Bytes'), ] with self.settings(USE_L10N=True), translation.override('de'): for value, expected in tests: with self.subTest(value=value): self.assertEqual(filesizeformat(value), expected) def test_negative_numbers(self): tests = [ (-1, '-1\xa0byte'), (-100, '-100\xa0bytes'), (-1024 * 1024 * 50, '-50.0\xa0MB'), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(filesizeformat(value), expected)
616a2a75856c408bed7b9711a50f2d7a581a793cb6ccae1060f0d7472b93777d
from django.template.defaultfilters import truncatechars_html from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_truncate_zero(self): self.assertEqual(truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0), '…') def test_truncate(self): self.assertEqual( truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), '<p>one…</p>', ) def test_truncate2(self): self.assertEqual( truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 9), '<p>one <a href="#">two …</a></p>', ) def test_truncate3(self): self.assertEqual( truncatechars_html('<p>one <a href="#">two - three <br>four</a> five</p>', 100), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate_unicode(self): self.assertEqual(truncatechars_html('<b>\xc5ngstr\xf6m</b> was here', 3), '<b>\xc5n…</b>') def test_truncate_something(self): self.assertEqual(truncatechars_html('a<b>b</b>c', 3), 'a<b>b</b>c') def test_invalid_arg(self): html = '<p>one <a href="#">two - three <br>four</a> five</p>' self.assertEqual(truncatechars_html(html, 'a'), html)
3ca7bdfa98c57c7dd32947a85ed2dd249fc53b46566327143f3d618109eae5d1
from django.template.defaultfilters import truncatewords_html from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_truncate_zero(self): self.assertEqual(truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0), '') def test_truncate(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 2), '<p>one <a href="#">two …</a></p>', ) def test_truncate2(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), '<p>one <a href="#">two - three <br>four …</a></p>', ) def test_truncate3(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 5), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate4(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 100), '<p>one <a href="#">two - three <br>four</a> five</p>', ) def test_truncate_unicode(self): self.assertEqual(truncatewords_html('\xc5ngstr\xf6m was here', 1), '\xc5ngstr\xf6m …') def test_truncate_complex(self): self.assertEqual( truncatewords_html('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>', 3), '<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo …</i>', ) def test_invalid_arg(self): self.assertEqual(truncatewords_html('<p>string</p>', 'a'), '<p>string</p>')
e3e4b7d35b5cb87924ef2aad516e8d565ea6d903f90a94903863cad2da08d80c
from decimal import Decimal from django.template.defaultfilters import pluralize from django.test import SimpleTestCase from ..utils import setup class PluralizeTests(SimpleTestCase): def check_values(self, *tests): for value, expected in tests: with self.subTest(value=value): output = self.engine.render_to_string('t', {'value': value}) self.assertEqual(output, expected) @setup({'t': 'vote{{ value|pluralize }}'}) def test_no_arguments(self): self.check_values(('0', 'votes'), ('1', 'vote'), ('2', 'votes')) @setup({'t': 'class{{ value|pluralize:"es" }}'}) def test_suffix(self): self.check_values(('0', 'classes'), ('1', 'class'), ('2', 'classes')) @setup({'t': 'cand{{ value|pluralize:"y,ies" }}'}) def test_singular_and_plural_suffix(self): self.check_values(('0', 'candies'), ('1', 'candy'), ('2', 'candies')) class FunctionTests(SimpleTestCase): def test_integers(self): self.assertEqual(pluralize(1), '') self.assertEqual(pluralize(0), 's') self.assertEqual(pluralize(2), 's') def test_floats(self): self.assertEqual(pluralize(0.5), 's') self.assertEqual(pluralize(1.5), 's') def test_decimals(self): self.assertEqual(pluralize(Decimal(1)), '') self.assertEqual(pluralize(Decimal(0)), 's') self.assertEqual(pluralize(Decimal(2)), 's') def test_lists(self): self.assertEqual(pluralize([1]), '') self.assertEqual(pluralize([]), 's') self.assertEqual(pluralize([1, 2, 3]), 's') def test_suffixes(self): self.assertEqual(pluralize(1, 'es'), '') self.assertEqual(pluralize(0, 'es'), 'es') self.assertEqual(pluralize(2, 'es'), 'es') self.assertEqual(pluralize(1, 'y,ies'), 'y') self.assertEqual(pluralize(0, 'y,ies'), 'ies') self.assertEqual(pluralize(2, 'y,ies'), 'ies') self.assertEqual(pluralize(0, 'y,ies,error'), '') def test_no_len_type(self): self.assertEqual(pluralize(object(), 'y,es'), '') self.assertEqual(pluralize(object(), 'es'), '') def test_value_error(self): self.assertEqual(pluralize('', 'y,es'), '') self.assertEqual(pluralize('', 'es'), '')
bba982da4ada14dd0c5fc15236e7540df33b637b357252434c0fbbeb87b26272
from django.template.defaultfilters import yesno from django.test import SimpleTestCase from ..utils import setup class YesNoTests(SimpleTestCase): @setup({'t': '{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}'}) def test_true(self): output = self.engine.render_to_string('t', {'var': True}) self.assertEqual(output, 'yup yes') class FunctionTests(SimpleTestCase): def test_true(self): self.assertEqual(yesno(True), 'yes') def test_false(self): self.assertEqual(yesno(False), 'no') def test_none(self): self.assertEqual(yesno(None), 'maybe') def test_true_arguments(self): self.assertEqual(yesno(True, 'certainly,get out of town,perhaps'), 'certainly') def test_false_arguments(self): self.assertEqual(yesno(False, 'certainly,get out of town,perhaps'), 'get out of town') def test_none_two_arguments(self): self.assertEqual(yesno(None, 'certainly,get out of town'), 'get out of town') def test_none_three_arguments(self): self.assertEqual(yesno(None, 'certainly,get out of town,perhaps'), 'perhaps') def test_invalid_value(self): self.assertIs(yesno(True, 'yes'), True) self.assertIs(yesno(False, 'yes'), False) self.assertIsNone(yesno(None, 'yes'))
1c9e6caddef2e230d6634304cf47fc254f2267408da0114f5380db2a85c89aa2
from django.test import SimpleTestCase from ..utils import setup class TruncatecharsTests(SimpleTestCase): @setup({'truncatechars01': '{{ a|truncatechars:3 }}'}) def test_truncatechars01(self): output = self.engine.render_to_string('truncatechars01', {'a': 'Testing, testing'}) self.assertEqual(output, 'Te…') @setup({'truncatechars02': '{{ a|truncatechars:7 }}'}) def test_truncatechars02(self): output = self.engine.render_to_string('truncatechars02', {'a': 'Testing'}) self.assertEqual(output, 'Testing') @setup({'truncatechars03': "{{ a|truncatechars:'e' }}"}) def test_fail_silently_incorrect_arg(self): output = self.engine.render_to_string('truncatechars03', {'a': 'Testing, testing'}) self.assertEqual(output, 'Testing, testing')
89c23aababd90bc705d8a1eaa58e1938152eb1fab5184267e030ca4e32e295c1
import operator from django import template from django.template.defaultfilters import stringfilter from django.utils.html import escape, format_html from django.utils.safestring import mark_safe register = template.Library() @register.filter @stringfilter def trim(value, num): return value[:num] @register.filter @mark_safe def make_data_div(value): """A filter that uses a decorator (@mark_safe).""" return '<div data-name="%s"></div>' % value @register.filter def noop(value, param=None): """A noop filter that always return its first argument and does nothing with its second (optional) one. Useful for testing out whitespace in filter arguments (see #19882).""" return value @register.simple_tag(takes_context=True) def context_stack_length(context): return len(context.dicts) @register.simple_tag def no_params(): """Expected no_params __doc__""" return "no_params - Expected result" no_params.anything = "Expected no_params __dict__" @register.simple_tag def one_param(arg): """Expected one_param __doc__""" return "one_param - Expected result: %s" % arg one_param.anything = "Expected one_param __dict__" @register.simple_tag(takes_context=False) def explicit_no_context(arg): """Expected explicit_no_context __doc__""" return "explicit_no_context - Expected result: %s" % arg explicit_no_context.anything = "Expected explicit_no_context __dict__" @register.simple_tag(takes_context=True) def no_params_with_context(context): """Expected no_params_with_context __doc__""" return "no_params_with_context - Expected result (context value: %s)" % context['value'] no_params_with_context.anything = "Expected no_params_with_context __dict__" @register.simple_tag(takes_context=True) def params_and_context(context, arg): """Expected params_and_context __doc__""" return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) params_and_context.anything = "Expected params_and_context __dict__" @register.simple_tag def simple_two_params(one, two): """Expected simple_two_params __doc__""" return "simple_two_params - Expected result: %s, %s" % (one, two) simple_two_params.anything = "Expected simple_two_params __dict__" @register.simple_tag def simple_keyword_only_param(*, kwarg): return "simple_keyword_only_param - Expected result: %s" % kwarg @register.simple_tag def simple_keyword_only_default(*, kwarg=42): return "simple_keyword_only_default - Expected result: %s" % kwarg @register.simple_tag def simple_one_default(one, two='hi'): """Expected simple_one_default __doc__""" return "simple_one_default - Expected result: %s, %s" % (one, two) simple_one_default.anything = "Expected simple_one_default __dict__" @register.simple_tag def simple_unlimited_args(one, two='hi', *args): """Expected simple_unlimited_args __doc__""" return "simple_unlimited_args - Expected result: %s" % ( ', '.join(str(arg) for arg in [one, two, *args]) ) simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__" @register.simple_tag def simple_only_unlimited_args(*args): """Expected simple_only_unlimited_args __doc__""" return "simple_only_unlimited_args - Expected result: %s" % ', '.join(str(arg) for arg in args) simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__" @register.simple_tag def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs): """Expected simple_unlimited_args_kwargs __doc__""" # Sort the dictionary by key to guarantee the order for testing. sorted_kwarg = sorted(kwargs.items(), key=operator.itemgetter(0)) return "simple_unlimited_args_kwargs - Expected result: %s / %s" % ( ', '.join(str(arg) for arg in [one, two, *args]), ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) ) simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__" @register.simple_tag(takes_context=True) def simple_tag_without_context_parameter(arg): """Expected simple_tag_without_context_parameter __doc__""" return "Expected result" simple_tag_without_context_parameter.anything = "Expected simple_tag_without_context_parameter __dict__" @register.simple_tag(takes_context=True) def escape_naive(context): """A tag that doesn't even think about escaping issues""" return "Hello {0}!".format(context['name']) @register.simple_tag(takes_context=True) def escape_explicit(context): """A tag that uses escape explicitly""" return escape("Hello {0}!".format(context['name'])) @register.simple_tag(takes_context=True) def escape_format_html(context): """A tag that uses format_html""" return format_html("Hello {0}!", context['name']) @register.simple_tag(takes_context=True) def current_app(context): return "%s" % context.current_app @register.simple_tag(takes_context=True) def use_l10n(context): return "%s" % context.use_l10n @register.simple_tag(name='minustwo') def minustwo_overridden_name(value): return value - 2 register.simple_tag(lambda x: x - 1, name='minusone') @register.tag('counter') def counter(parser, token): return CounterNode() class CounterNode(template.Node): def __init__(self): self.count = 0 def render(self, context): count = self.count self.count = count + 1 return count
60aaa93770c42e3cb0570988b3872bde326dd0167101566deb16ae3f04e6043a
import operator from django.template import Engine, Library engine = Engine(app_dirs=True) register = Library() @register.inclusion_tag('inclusion.html') def inclusion_no_params(): """Expected inclusion_no_params __doc__""" return {"result": "inclusion_no_params - Expected result"} inclusion_no_params.anything = "Expected inclusion_no_params __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_no_params_from_template(): """Expected inclusion_no_params_from_template __doc__""" return {"result": "inclusion_no_params_from_template - Expected result"} inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_one_param(arg): """Expected inclusion_one_param __doc__""" return {"result": "inclusion_one_param - Expected result: %s" % arg} inclusion_one_param.anything = "Expected inclusion_one_param __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_one_param_from_template(arg): """Expected inclusion_one_param_from_template __doc__""" return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg} inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__" @register.inclusion_tag('inclusion.html', takes_context=False) def inclusion_explicit_no_context(arg): """Expected inclusion_explicit_no_context __doc__""" return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__" @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=False) def inclusion_explicit_no_context_from_template(arg): """Expected inclusion_explicit_no_context_from_template __doc__""" return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg} inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__" @register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_no_params_with_context(context): """Expected inclusion_no_params_with_context __doc__""" return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']} inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__" @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) def inclusion_no_params_with_context_from_template(context): """Expected inclusion_no_params_with_context_from_template __doc__""" return { "result": ( "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value'] ) } inclusion_no_params_with_context_from_template.anything = ( "Expected inclusion_no_params_with_context_from_template __dict__" ) @register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_params_and_context(context, arg): """Expected inclusion_params_and_context __doc__""" return { "result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) } inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__" @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) def inclusion_params_and_context_from_template(context, arg): """Expected inclusion_params_and_context_from_template __doc__""" return { "result": ( "inclusion_params_and_context_from_template - Expected result " "(context value: %s): %s" % (context['value'], arg) ) } inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_two_params(one, two): """Expected inclusion_two_params __doc__""" return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)} inclusion_two_params.anything = "Expected inclusion_two_params __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_two_params_from_template(one, two): """Expected inclusion_two_params_from_template __doc__""" return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)} inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_one_default(one, two='hi'): """Expected inclusion_one_default __doc__""" return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)} inclusion_one_default.anything = "Expected inclusion_one_default __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_one_default_from_template(one, two='hi'): """Expected inclusion_one_default_from_template __doc__""" return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)} inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_unlimited_args(one, two='hi', *args): """Expected inclusion_unlimited_args __doc__""" return { "result": ( "inclusion_unlimited_args - Expected result: %s" % ( ', '.join(str(arg) for arg in [one, two, *args]) ) ) } inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_unlimited_args_from_template(one, two='hi', *args): """Expected inclusion_unlimited_args_from_template __doc__""" return { "result": ( "inclusion_unlimited_args_from_template - Expected result: %s" % ( ', '.join(str(arg) for arg in [one, two, *args]) ) ) } inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_only_unlimited_args(*args): """Expected inclusion_only_unlimited_args __doc__""" return { "result": "inclusion_only_unlimited_args - Expected result: %s" % ( ', '.join(str(arg) for arg in args) ) } inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_only_unlimited_args_from_template(*args): """Expected inclusion_only_unlimited_args_from_template __doc__""" return { "result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % ( ', '.join(str(arg) for arg in args) ) } inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__" @register.inclusion_tag('test_incl_tag_use_l10n.html', takes_context=True) def inclusion_tag_use_l10n(context): """Expected inclusion_tag_use_l10n __doc__""" return {} inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__" @register.inclusion_tag('inclusion.html') def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs): """Expected inclusion_unlimited_args_kwargs __doc__""" # Sort the dictionary by key to guarantee the order for testing. sorted_kwarg = sorted(kwargs.items(), key=operator.itemgetter(0)) return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % ( ', '.join(str(arg) for arg in [one, two, *args]), ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) )} inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__" @register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_tag_without_context_parameter(arg): """Expected inclusion_tag_without_context_parameter __doc__""" return {} inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__" @register.inclusion_tag('inclusion_extends1.html') def inclusion_extends1(): return {} @register.inclusion_tag('inclusion_extends2.html') def inclusion_extends2(): return {}
cf12ad3f83d13c48a4d574ab84878fbd712b756a89d0dfc6110c588ac2d17d9b
from django.contrib.sitemaps import views from django.urls import path from .http import simple_sitemaps urlpatterns = [ path( 'simple/index.xml', views.index, {'sitemaps': simple_sitemaps}, name='django.contrib.sitemaps.views.index'), ]
bd97cff3d3d6fec2d1b9868b78804be258f295648f3484e50705ba16f3b8c645
from django.contrib.sitemaps import views from django.urls import path from .http import SimpleSitemap class HTTPSSitemap(SimpleSitemap): protocol = 'https' secure_sitemaps = { 'simple': HTTPSSitemap, } urlpatterns = [ path('secure/index.xml', views.index, {'sitemaps': secure_sitemaps}), path( 'secure/sitemap-<section>.xml', views.sitemap, {'sitemaps': secure_sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ]
2b7ca1cd998e6abb98a61730f5906c33a90301e0f7a50505564982c5e5237d74
from datetime import date, datetime from django.conf.urls.i18n import i18n_patterns from django.contrib.sitemaps import GenericSitemap, Sitemap, views from django.http import HttpResponse from django.urls import path from django.utils import timezone from django.views.decorators.cache import cache_page from ..models import I18nTestModel, TestModel class SimpleSitemap(Sitemap): changefreq = "never" priority = 0.5 location = '/location/' lastmod = datetime.now() def items(self): return [object()] class SimplePagedSitemap(Sitemap): def items(self): return [object() for x in range(Sitemap.limit + 1)] class SimpleI18nSitemap(Sitemap): changefreq = "never" priority = 0.5 i18n = True def items(self): return I18nTestModel.objects.order_by('pk').all() class EmptySitemap(Sitemap): changefreq = "never" priority = 0.5 location = '/location/' class FixedLastmodSitemap(SimpleSitemap): lastmod = datetime(2013, 3, 13, 10, 0, 0) class FixedLastmodMixedSitemap(Sitemap): changefreq = "never" priority = 0.5 location = '/location/' loop = 0 def items(self): o1 = TestModel() o1.lastmod = datetime(2013, 3, 13, 10, 0, 0) o2 = TestModel() return [o1, o2] class FixedNewerLastmodSitemap(SimpleSitemap): lastmod = datetime(2013, 4, 20, 5, 0, 0) class DateSiteMap(SimpleSitemap): lastmod = date(2013, 3, 13) class TimezoneSiteMap(SimpleSitemap): lastmod = datetime(2013, 3, 13, 10, 0, 0, tzinfo=timezone.get_fixed_timezone(-300)) def testmodelview(request, id): return HttpResponse() simple_sitemaps = { 'simple': SimpleSitemap, } simple_i18nsitemaps = { 'simple': SimpleI18nSitemap, } simple_sitemaps_not_callable = { 'simple': SimpleSitemap(), } simple_sitemaps_paged = { 'simple': SimplePagedSitemap, } empty_sitemaps = { 'empty': EmptySitemap, } fixed_lastmod_sitemaps = { 'fixed-lastmod': FixedLastmodSitemap, } fixed_lastmod__mixed_sitemaps = { 'fixed-lastmod-mixed': FixedLastmodMixedSitemap, } sitemaps_lastmod_mixed_ascending = { 'no-lastmod': EmptySitemap, 'lastmod': FixedLastmodSitemap, } sitemaps_lastmod_mixed_descending = { 'lastmod': FixedLastmodSitemap, 'no-lastmod': EmptySitemap, } sitemaps_lastmod_ascending = { 'date': DateSiteMap, 'datetime': FixedLastmodSitemap, 'datetime-newer': FixedNewerLastmodSitemap, } sitemaps_lastmod_descending = { 'datetime-newer': FixedNewerLastmodSitemap, 'datetime': FixedLastmodSitemap, 'date': DateSiteMap, } generic_sitemaps = { 'generic': GenericSitemap({'queryset': TestModel.objects.order_by('pk').all()}), } generic_sitemaps_lastmod = { 'generic': GenericSitemap({ 'queryset': TestModel.objects.order_by('pk').all(), 'date_field': 'lastmod', }), } urlpatterns = [ path('simple/index.xml', views.index, {'sitemaps': simple_sitemaps}), path('simple-paged/index.xml', views.index, {'sitemaps': simple_sitemaps_paged}), path('simple-not-callable/index.xml', views.index, {'sitemaps': simple_sitemaps_not_callable}), path( 'simple/custom-index.xml', views.index, {'sitemaps': simple_sitemaps, 'template_name': 'custom_sitemap_index.xml'}), path( 'simple/sitemap-<section>.xml', views.sitemap, {'sitemaps': simple_sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path( 'simple/sitemap.xml', views.sitemap, {'sitemaps': simple_sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path( 'simple/i18n.xml', views.sitemap, {'sitemaps': simple_i18nsitemaps}, name='django.contrib.sitemaps.views.sitemap'), path( 'simple/custom-sitemap.xml', views.sitemap, {'sitemaps': simple_sitemaps, 'template_name': 'custom_sitemap.xml'}, name='django.contrib.sitemaps.views.sitemap'), path( 'empty/sitemap.xml', views.sitemap, {'sitemaps': empty_sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod/sitemap.xml', views.sitemap, {'sitemaps': fixed_lastmod_sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod-mixed/sitemap.xml', views.sitemap, {'sitemaps': fixed_lastmod__mixed_sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod/date-sitemap.xml', views.sitemap, {'sitemaps': {'date-sitemap': DateSiteMap}}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod/tz-sitemap.xml', views.sitemap, {'sitemaps': {'tz-sitemap': TimezoneSiteMap}}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod-sitemaps/mixed-ascending.xml', views.sitemap, {'sitemaps': sitemaps_lastmod_mixed_ascending}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod-sitemaps/mixed-descending.xml', views.sitemap, {'sitemaps': sitemaps_lastmod_mixed_descending}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod-sitemaps/ascending.xml', views.sitemap, {'sitemaps': sitemaps_lastmod_ascending}, name='django.contrib.sitemaps.views.sitemap'), path( 'lastmod-sitemaps/descending.xml', views.sitemap, {'sitemaps': sitemaps_lastmod_descending}, name='django.contrib.sitemaps.views.sitemap'), path( 'generic/sitemap.xml', views.sitemap, {'sitemaps': generic_sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path( 'generic-lastmod/sitemap.xml', views.sitemap, {'sitemaps': generic_sitemaps_lastmod}, name='django.contrib.sitemaps.views.sitemap'), path( 'cached/index.xml', cache_page(1)(views.index), {'sitemaps': simple_sitemaps, 'sitemap_url_name': 'cached_sitemap'}), path( 'cached/sitemap-<section>.xml', cache_page(1)(views.sitemap), {'sitemaps': simple_sitemaps}, name='cached_sitemap'), path( 'sitemap-without-entries/sitemap.xml', views.sitemap, {'sitemaps': {}}, name='django.contrib.sitemaps.views.sitemap'), ] urlpatterns += i18n_patterns( path('i18n/testmodel/<int:id>/', testmodelview, name='i18n_testmodel'), )
e640f2ead3441eae856d7cea8ac1ee8e1b60945434c381ba06fcebe4ed6c05fa
import unittest from django.db import connection from django.db.models.fields import BooleanField, NullBooleanField from django.db.utils import DatabaseError from django.test import TransactionTestCase from ..models import Square @unittest.skipUnless(connection.vendor == 'oracle', 'Oracle tests') class Tests(unittest.TestCase): def test_quote_name(self): """'%' chars are escaped for query execution.""" name = '"SOME%NAME"' quoted_name = connection.ops.quote_name(name) self.assertEqual(quoted_name % (), name) def test_dbms_session(self): """A stored procedure can be called through a cursor wrapper.""" with connection.cursor() as cursor: cursor.callproc('DBMS_SESSION.SET_IDENTIFIER', ['_django_testing!']) def test_cursor_var(self): """Cursor variables can be passed as query parameters.""" with connection.cursor() as cursor: var = cursor.var(str) cursor.execute("BEGIN %s := 'X'; END; ", [var]) self.assertEqual(var.getvalue(), 'X') def test_client_encoding(self): """Client encoding is set correctly.""" connection.ensure_connection() self.assertEqual(connection.connection.encoding, 'UTF-8') self.assertEqual(connection.connection.nencoding, 'UTF-8') def test_order_of_nls_parameters(self): """ An 'almost right' datetime works with configured NLS parameters (#18465). """ with connection.cursor() as cursor: query = "select 1 from dual where '1936-12-29 00:00' < sysdate" # The query succeeds without errors - pre #18465 this # wasn't the case. cursor.execute(query) self.assertEqual(cursor.fetchone()[0], 1) def test_boolean_constraints(self): """Boolean fields have check constraints on their values.""" for field in (BooleanField(), NullBooleanField(), BooleanField(null=True)): with self.subTest(field=field): field.set_attributes_from_name('is_nice') self.assertIn('"IS_NICE" IN (0,1)', field.db_check(connection)) @unittest.skipUnless(connection.vendor == 'oracle', 'Oracle tests') class TransactionalTests(TransactionTestCase): available_apps = ['backends'] def test_hidden_no_data_found_exception(self): # "ORA-1403: no data found" exception is hidden by Oracle OCI library # when an INSERT statement is used with a RETURNING clause (see #28859). with connection.cursor() as cursor: # Create trigger that raises "ORA-1403: no data found". cursor.execute(""" CREATE OR REPLACE TRIGGER "TRG_NO_DATA_FOUND" AFTER INSERT ON "BACKENDS_SQUARE" FOR EACH ROW BEGIN RAISE NO_DATA_FOUND; END; """) try: with self.assertRaisesMessage(DatabaseError, ( 'The database did not return a new row id. Probably "ORA-1403: ' 'no data found" was raised internally but was hidden by the ' 'Oracle OCI library (see https://code.djangoproject.com/ticket/28859).' )): Square.objects.create(root=2, square=4) finally: with connection.cursor() as cursor: cursor.execute('DROP TRIGGER "TRG_NO_DATA_FOUND"') def test_password_with_at_sign(self): old_password = connection.settings_dict['PASSWORD'] connection.settings_dict['PASSWORD'] = 'p@ssword' try: self.assertIn('/"p@ssword"@', connection._connect_string()) with self.assertRaises(DatabaseError) as context: connection.cursor() # Database exception: "ORA-01017: invalid username/password" is # expected. self.assertIn('ORA-01017', context.exception.args[0].message) finally: connection.settings_dict['PASSWORD'] = old_password
fae79285822384ca56a3852d0cdcbc7770583552bd8c138e13d4090a27cb8f9f
import unittest from io import StringIO from unittest import mock from django.db import connection from django.db.backends.oracle.creation import DatabaseCreation from django.db.utils import DatabaseError from django.test import TestCase @unittest.skipUnless(connection.vendor == 'oracle', 'Oracle tests') @mock.patch.object(DatabaseCreation, '_maindb_connection', return_value=connection) @mock.patch('sys.stdout', new_callable=StringIO) @mock.patch('sys.stderr', new_callable=StringIO) class DatabaseCreationTests(TestCase): def _execute_raise_user_already_exists(self, cursor, statements, parameters, verbosity, allow_quiet_fail=False): # Raise "user already exists" only in test user creation if statements and statements[0].startswith('CREATE USER'): raise DatabaseError("ORA-01920: user name 'string' conflicts with another user or role name") def _execute_raise_tablespace_already_exists( self, cursor, statements, parameters, verbosity, allow_quiet_fail=False ): raise DatabaseError("ORA-01543: tablespace 'string' already exists") def _execute_raise_insufficient_privileges( self, cursor, statements, parameters, verbosity, allow_quiet_fail=False ): raise DatabaseError("ORA-01031: insufficient privileges") def _test_database_passwd(self): # Mocked to avoid test user password changed return connection.settings_dict['SAVED_PASSWORD'] def patch_execute_statements(self, execute_statements): return mock.patch.object(DatabaseCreation, '_execute_statements', execute_statements) @mock.patch.object(DatabaseCreation, '_test_user_create', return_value=False) def test_create_test_db(self, *mocked_objects): creation = DatabaseCreation(connection) # Simulate test database creation raising "tablespace already exists" with self.patch_execute_statements(self._execute_raise_tablespace_already_exists): with mock.patch('builtins.input', return_value='no'): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test tablespace. creation._create_test_db(verbosity=0, keepdb=False) # "Tablespace already exists" error is ignored when keepdb is on creation._create_test_db(verbosity=0, keepdb=True) # Simulate test database creation raising unexpected error with self.patch_execute_statements(self._execute_raise_insufficient_privileges): with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=False) with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=True) @mock.patch.object(DatabaseCreation, '_test_database_create', return_value=False) def test_create_test_user(self, *mocked_objects): creation = DatabaseCreation(connection) with mock.patch.object(DatabaseCreation, '_test_database_passwd', self._test_database_passwd): # Simulate test user creation raising "user already exists" with self.patch_execute_statements(self._execute_raise_user_already_exists): with mock.patch('builtins.input', return_value='no'): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test user. creation._create_test_db(verbosity=0, keepdb=False) # "User already exists" error is ignored when keepdb is on creation._create_test_db(verbosity=0, keepdb=True) # Simulate test user creation raising unexpected error with self.patch_execute_statements(self._execute_raise_insufficient_privileges): with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=False) with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, keepdb=True) def test_oracle_managed_files(self, *mocked_objects): def _execute_capture_statements(self, cursor, statements, parameters, verbosity, allow_quiet_fail=False): self.tblspace_sqls = statements creation = DatabaseCreation(connection) # Simulate test database creation with Oracle Managed File (OMF) # tablespaces. with mock.patch.object(DatabaseCreation, '_test_database_oracle_managed_files', return_value=True): with self.patch_execute_statements(_execute_capture_statements): with connection.cursor() as cursor: creation._execute_test_db_creation(cursor, creation._get_test_db_params(), verbosity=0) tblspace_sql, tblspace_tmp_sql = creation.tblspace_sqls # Datafile names shouldn't appear. self.assertIn('DATAFILE SIZE', tblspace_sql) self.assertIn('TEMPFILE SIZE', tblspace_tmp_sql) # REUSE cannot be used with OMF. self.assertNotIn('REUSE', tblspace_sql) self.assertNotIn('REUSE', tblspace_tmp_sql)
26ce1ba29b3ec5ffc342e9febd838dd7129a812bcca437fd06a03ea47f8931bb
import re import threading import unittest from sqlite3 import dbapi2 from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import connection, transaction from django.db.models import Avg, StdDev, Sum, Variance from django.db.models.aggregates import Aggregate from django.db.models.fields import CharField from django.db.utils import NotSupportedError from django.test import ( TestCase, TransactionTestCase, override_settings, skipIfDBFeature, ) from django.test.utils import isolate_apps from ..models import Author, Item, Object, Square try: from django.db.backends.sqlite3.base import check_sqlite_version except ImproperlyConfigured: # Ignore "SQLite is too old" when running tests on another database. pass @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class Tests(TestCase): longMessage = True def test_check_sqlite_version(self): msg = 'SQLite 3.8.3 or later is required (found 3.8.2).' with mock.patch.object(dbapi2, 'sqlite_version_info', (3, 8, 2)), \ mock.patch.object(dbapi2, 'sqlite_version', '3.8.2'), \ self.assertRaisesMessage(ImproperlyConfigured, msg): check_sqlite_version() def test_aggregation(self): """ Raise NotImplementedError when aggregating on date/time fields (#19360). """ for aggregate in (Sum, Avg, Variance, StdDev): with self.assertRaises(NotSupportedError): Item.objects.all().aggregate(aggregate('time')) with self.assertRaises(NotSupportedError): Item.objects.all().aggregate(aggregate('date')) with self.assertRaises(NotSupportedError): Item.objects.all().aggregate(aggregate('last_modified')) with self.assertRaises(NotSupportedError): Item.objects.all().aggregate( **{'complex': aggregate('last_modified') + aggregate('last_modified')} ) def test_distinct_aggregation(self): class DistinctAggregate(Aggregate): allow_distinct = True aggregate = DistinctAggregate('first', 'second', distinct=True) msg = ( "SQLite doesn't support DISTINCT on aggregate functions accepting " "multiple arguments." ) with self.assertRaisesMessage(NotSupportedError, msg): connection.ops.check_expression_support(aggregate) def test_memory_db_test_name(self): """A named in-memory db should be allowed where supported.""" from django.db.backends.sqlite3.base import DatabaseWrapper settings_dict = { 'TEST': { 'NAME': 'file:memorydb_test?mode=memory&cache=shared', } } creation = DatabaseWrapper(settings_dict).creation self.assertEqual(creation._get_test_db_name(), creation.connection.settings_dict['TEST']['NAME']) def test_regexp_function(self): tests = ( ('test', r'[0-9]+', False), ('test', r'[a-z]+', True), ('test', None, None), (None, r'[a-z]+', None), (None, None, None), ) for string, pattern, expected in tests: with self.subTest((string, pattern)): with connection.cursor() as cursor: cursor.execute('SELECT %s REGEXP %s', [string, pattern]) value = cursor.fetchone()[0] value = bool(value) if value in {0, 1} else value self.assertIs(value, expected) @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') @isolate_apps('backends') class SchemaTests(TransactionTestCase): available_apps = ['backends'] def test_autoincrement(self): """ auto_increment fields are created with the AUTOINCREMENT keyword in order to be monotonically increasing (#10164). """ with connection.schema_editor(collect_sql=True) as editor: editor.create_model(Square) statements = editor.collected_sql match = re.search('"id" ([^,]+),', statements[0]) self.assertIsNotNone(match) self.assertEqual( 'integer NOT NULL PRIMARY KEY AUTOINCREMENT', match.group(1), 'Wrong SQL used to create an auto-increment column on SQLite' ) def test_disable_constraint_checking_failure_disallowed(self): """ SQLite schema editor is not usable within an outer transaction if foreign key constraint checks are not disabled beforehand. """ msg = ( 'SQLite schema editor cannot be used while foreign key ' 'constraint checks are enabled. Make sure to disable them ' 'before entering a transaction.atomic() context because ' 'SQLite does not support disabling them in the middle of ' 'a multi-statement transaction.' ) with self.assertRaisesMessage(NotSupportedError, msg): with transaction.atomic(), connection.schema_editor(atomic=True): pass def test_constraint_checks_disabled_atomic_allowed(self): """ SQLite schema editor is usable within an outer transaction as long as foreign key constraints checks are disabled beforehand. """ def constraint_checks_enabled(): with connection.cursor() as cursor: return bool(cursor.execute('PRAGMA foreign_keys').fetchone()[0]) with connection.constraint_checks_disabled(), transaction.atomic(): with connection.schema_editor(atomic=True): self.assertFalse(constraint_checks_enabled()) self.assertFalse(constraint_checks_enabled()) self.assertTrue(constraint_checks_enabled()) @skipIfDBFeature('supports_atomic_references_rename') def test_field_rename_inside_atomic_block(self): """ NotImplementedError is raised when a model field rename is attempted inside an atomic block. """ new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') msg = ( "Renaming the 'backends_author'.'name' column while in a " "transaction is not supported on SQLite < 3.26 because it would " "break referential integrity. Try adding `atomic = False` to the " "Migration class." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: editor.alter_field(Author, Author._meta.get_field('name'), new_field) @skipIfDBFeature('supports_atomic_references_rename') def test_table_rename_inside_atomic_block(self): """ NotImplementedError is raised when a table rename is attempted inside an atomic block. """ msg = ( "Renaming the 'backends_author' table while in a transaction is " "not supported on SQLite < 3.26 because it would break referential " "integrity. Try adding `atomic = False` to the Migration class." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Author, "backends_author", "renamed_table") @unittest.skipUnless(connection.vendor == 'sqlite', 'Test only for SQLite') @override_settings(DEBUG=True) class LastExecutedQueryTest(TestCase): def test_no_interpolation(self): # This shouldn't raise an exception (#17158) query = "SELECT strftime('%Y', 'now');" connection.cursor().execute(query) self.assertEqual(connection.queries[-1]['sql'], query) def test_parameter_quoting(self): # The implementation of last_executed_queries isn't optimal. It's # worth testing that parameters are quoted (#14091). query = "SELECT %s" params = ["\"'\\"] connection.cursor().execute(query, params) # Note that the single quote is repeated substituted = "SELECT '\"''\\'" self.assertEqual(connection.queries[-1]['sql'], substituted) def test_large_number_of_parameters(self): # If SQLITE_MAX_VARIABLE_NUMBER (default = 999) has been changed to be # greater than SQLITE_MAX_COLUMN (default = 2000), last_executed_query # can hit the SQLITE_MAX_COLUMN limit (#26063). with connection.cursor() as cursor: sql = "SELECT MAX(%s)" % ", ".join(["%s"] * 2001) params = list(range(2001)) # This should not raise an exception. cursor.db.ops.last_executed_query(cursor.cursor, sql, params) @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class EscapingChecks(TestCase): """ All tests in this test case are also run with settings.DEBUG=True in EscapingChecksDebug test case, to also test CursorDebugWrapper. """ def test_parameter_escaping(self): # '%s' escaping support for sqlite3 (#13648). with connection.cursor() as cursor: cursor.execute("select strftime('%s', date('now'))") response = cursor.fetchall()[0][0] # response should be an non-zero integer self.assertTrue(int(response)) @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') @override_settings(DEBUG=True) class EscapingChecksDebug(EscapingChecks): pass @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class ThreadSharing(TransactionTestCase): available_apps = ['backends'] def test_database_sharing_in_threads(self): def create_object(): Object.objects.create() create_object() thread = threading.Thread(target=create_object) thread.start() thread.join() self.assertEqual(Object.objects.count(), 2)
4479cfb0d39e5e387b9b0f8b1ca9bb96910a31ef28ef2dc2d8f41bd897d7b48a
import unittest import sqlparse from django.db import connection from django.test import TestCase @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class IntrospectionTests(TestCase): def test_get_primary_key_column(self): """ Get the primary key column regardless of whether or not it has quotation. """ testable_column_strings = ( ('id', 'id'), ('[id]', 'id'), ('`id`', 'id'), ('"id"', 'id'), ('[id col]', 'id col'), ('`id col`', 'id col'), ('"id col"', 'id col') ) with connection.cursor() as cursor: for column, expected_string in testable_column_strings: sql = 'CREATE TABLE test_primary (%s int PRIMARY KEY NOT NULL)' % column with self.subTest(column=column): try: cursor.execute(sql) field = connection.introspection.get_primary_key_column(cursor, 'test_primary') self.assertEqual(field, expected_string) finally: cursor.execute('DROP TABLE test_primary') @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class ParsingTests(TestCase): def parse_definition(self, sql, columns): """Parse a column or constraint definition.""" statement = sqlparse.parse(sql)[0] tokens = (token for token in statement.flatten() if not token.is_whitespace) with connection.cursor(): return connection.introspection._parse_column_or_constraint_definition(tokens, set(columns)) def assertConstraint(self, constraint_details, cols, unique=False, check=False): self.assertEqual(constraint_details, { 'unique': unique, 'columns': cols, 'primary_key': False, 'foreign_key': None, 'check': check, 'index': False, }) def test_unique_column(self): tests = ( ('"ref" integer UNIQUE,', ['ref']), ('ref integer UNIQUE,', ['ref']), ('"customname" integer UNIQUE,', ['customname']), ('customname integer UNIQUE,', ['customname']), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertConstraint(details, columns, unique=True) self.assertIsNone(check) def test_unique_constraint(self): tests = ( ('CONSTRAINT "ref" UNIQUE ("ref"),', 'ref', ['ref']), ('CONSTRAINT ref UNIQUE (ref),', 'ref', ['ref']), ('CONSTRAINT "customname1" UNIQUE ("customname2"),', 'customname1', ['customname2']), ('CONSTRAINT customname1 UNIQUE (customname2),', 'customname1', ['customname2']), ) for sql, constraint_name, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertEqual(constraint, constraint_name) self.assertConstraint(details, columns, unique=True) self.assertIsNone(check) def test_unique_constraint_multicolumn(self): tests = ( ('CONSTRAINT "ref" UNIQUE ("ref", "customname"),', 'ref', ['ref', 'customname']), ('CONSTRAINT ref UNIQUE (ref, customname),', 'ref', ['ref', 'customname']), ) for sql, constraint_name, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertEqual(constraint, constraint_name) self.assertConstraint(details, columns, unique=True) self.assertIsNone(check) def test_check_column(self): tests = ( ('"ref" varchar(255) CHECK ("ref" != \'test\'),', ['ref']), ('ref varchar(255) CHECK (ref != \'test\'),', ['ref']), ('"customname1" varchar(255) CHECK ("customname2" != \'test\'),', ['customname2']), ('customname1 varchar(255) CHECK (customname2 != \'test\'),', ['customname2']), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertIsNone(details) self.assertConstraint(check, columns, check=True) def test_check_constraint(self): tests = ( ('CONSTRAINT "ref" CHECK ("ref" != \'test\'),', 'ref', ['ref']), ('CONSTRAINT ref CHECK (ref != \'test\'),', 'ref', ['ref']), ('CONSTRAINT "customname1" CHECK ("customname2" != \'test\'),', 'customname1', ['customname2']), ('CONSTRAINT customname1 CHECK (customname2 != \'test\'),', 'customname1', ['customname2']), ) for sql, constraint_name, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertEqual(constraint, constraint_name) self.assertIsNone(details) self.assertConstraint(check, columns, check=True) def test_check_column_with_operators_and_functions(self): tests = ( ('"ref" integer CHECK ("ref" BETWEEN 1 AND 10),', ['ref']), ('"ref" varchar(255) CHECK ("ref" LIKE \'test%\'),', ['ref']), ('"ref" varchar(255) CHECK (LENGTH(ref) > "max_length"),', ['ref', 'max_length']), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertIsNone(details) self.assertConstraint(check, columns, check=True) def test_check_and_unique_column(self): tests = ( ('"ref" varchar(255) CHECK ("ref" != \'test\') UNIQUE,', ['ref']), ('ref varchar(255) UNIQUE CHECK (ref != \'test\'),', ['ref']), ) for sql, columns in tests: with self.subTest(sql=sql): constraint, details, check, _ = self.parse_definition(sql, columns) self.assertIsNone(constraint) self.assertConstraint(details, columns, unique=True) self.assertConstraint(check, columns, check=True)
22148383d36b9954ab9458103ed8f16ff8f32d313163b551b036fe4e43cc4d60
import decimal from django.db import NotSupportedError, connection from django.db.backends.base.operations import BaseDatabaseOperations from django.db.models import DurationField from django.test import ( SimpleTestCase, TestCase, override_settings, skipIfDBFeature, ) from django.utils import timezone class SimpleDatabaseOperationTests(SimpleTestCase): may_requre_msg = 'subclasses of BaseDatabaseOperations may require a %s() method' def setUp(self): self.ops = BaseDatabaseOperations(connection=connection) def test_deferrable_sql(self): self.assertEqual(self.ops.deferrable_sql(), '') def test_end_transaction_rollback(self): self.assertEqual(self.ops.end_transaction_sql(success=False), 'ROLLBACK;') def test_no_limit_value(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'no_limit_value'): self.ops.no_limit_value() def test_quote_name(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'quote_name'): self.ops.quote_name('a') def test_regex_lookup(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'regex_lookup'): self.ops.regex_lookup(lookup_type='regex') def test_set_time_zone_sql(self): self.assertEqual(self.ops.set_time_zone_sql(), '') def test_sql_flush(self): msg = 'subclasses of BaseDatabaseOperations must provide a sql_flush() method' with self.assertRaisesMessage(NotImplementedError, msg): self.ops.sql_flush(None, None, None) def test_pk_default_value(self): self.assertEqual(self.ops.pk_default_value(), 'DEFAULT') def test_tablespace_sql(self): self.assertEqual(self.ops.tablespace_sql(None), '') def test_sequence_reset_by_name_sql(self): self.assertEqual(self.ops.sequence_reset_by_name_sql(None, []), []) def test_adapt_unknown_value_decimal(self): value = decimal.Decimal('3.14') self.assertEqual( self.ops.adapt_unknown_value(value), self.ops.adapt_decimalfield_value(value) ) def test_adapt_unknown_value_date(self): value = timezone.now().date() self.assertEqual(self.ops.adapt_unknown_value(value), self.ops.adapt_datefield_value(value)) def test_adapt_unknown_value_time(self): value = timezone.now().time() self.assertEqual(self.ops.adapt_unknown_value(value), self.ops.adapt_timefield_value(value)) def test_adapt_timefield_value_none(self): self.assertIsNone(self.ops.adapt_timefield_value(None)) def test_adapt_datetimefield_value(self): self.assertIsNone(self.ops.adapt_datetimefield_value(None)) def test_adapt_timefield_value(self): msg = 'Django does not support timezone-aware times.' with self.assertRaisesMessage(ValueError, msg): self.ops.adapt_timefield_value(timezone.make_aware(timezone.now())) @override_settings(USE_TZ=False) def test_adapt_timefield_value_unaware(self): now = timezone.now() self.assertEqual(self.ops.adapt_timefield_value(now), str(now)) def test_date_extract_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'date_extract_sql'): self.ops.date_extract_sql(None, None) def test_time_extract_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'date_extract_sql'): self.ops.time_extract_sql(None, None) def test_date_interval_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'date_interval_sql'): self.ops.date_interval_sql(None) def test_date_trunc_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'date_trunc_sql'): self.ops.date_trunc_sql(None, None) def test_time_trunc_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'time_trunc_sql'): self.ops.time_trunc_sql(None, None) def test_datetime_trunc_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'datetime_trunc_sql'): self.ops.datetime_trunc_sql(None, None, None) def test_datetime_cast_date_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'datetime_cast_date_sql'): self.ops.datetime_cast_date_sql(None, None) def test_datetime_cast_time_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'datetime_cast_time_sql'): self.ops.datetime_cast_time_sql(None, None) def test_datetime_extract_sql(self): with self.assertRaisesMessage(NotImplementedError, self.may_requre_msg % 'datetime_extract_sql'): self.ops.datetime_extract_sql(None, None, None) class DatabaseOperationTests(TestCase): def setUp(self): self.ops = BaseDatabaseOperations(connection=connection) @skipIfDBFeature('supports_over_clause') def test_window_frame_raise_not_supported_error(self): msg = 'This backend does not support window expressions.' with self.assertRaisesMessage(NotSupportedError, msg): self.ops.window_frame_rows_start_end() @skipIfDBFeature('can_distinct_on_fields') def test_distinct_on_fields(self): msg = 'DISTINCT ON fields is not supported by this database backend' with self.assertRaisesMessage(NotSupportedError, msg): self.ops.distinct_sql(['a', 'b'], None) @skipIfDBFeature('supports_temporal_subtraction') def test_subtract_temporals(self): duration_field = DurationField() duration_field_internal_type = duration_field.get_internal_type() msg = ( 'This backend does not support %s subtraction.' % duration_field_internal_type ) with self.assertRaisesMessage(NotSupportedError, msg): self.ops.subtract_temporals(duration_field_internal_type, None, None)
1d62d2843d44e7af49bbe245283c63c8a387423392c9e4d56c266e817b6e38df
from django.db import models from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.test import SimpleTestCase class SchemaEditorTests(SimpleTestCase): def test_effective_default_callable(self): """SchemaEditor.effective_default() shouldn't call callable defaults.""" class MyStr(str): def __call__(self): return self class MyCharField(models.CharField): def _get_default(self): return self.default field = MyCharField(max_length=1, default=MyStr) self.assertEqual(BaseDatabaseSchemaEditor._effective_default(field), MyStr)
bfa18b92c0e2b032f33102506d31b5353e841979a1a9cb10d72b9a7e6fa3920a
from django.db import connection from django.test import SimpleTestCase class TestDatabaseFeatures(SimpleTestCase): def test_nonexistent_feature(self): self.assertFalse(hasattr(connection.features, 'nonexistent'))
dcbfa507e3d361698e9a8dfc4841f7fe8eac6aaaeb5ac75d16f4672b58ed8545
import unittest from django.db import connection from django.test import TestCase @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL tests') class SchemaEditorTests(TestCase): def test_quote_value(self): import MySQLdb editor = connection.schema_editor() tested_values = [ ('string', "'string'"), (42, '42'), (1.754, '1.754e0' if MySQLdb.version_info >= (1, 3, 14) else '1.754'), (False, b'0' if MySQLdb.version_info >= (1, 4, 0) else '0'), ] for value, expected in tested_values: with self.subTest(value=value): self.assertEqual(editor.quote_value(value), expected)
9ee97906f0214fdf39fe4499cc6040d5c49323f8e433333dd61ace42124aabb9
from unittest import mock, skipUnless from django.db import connection from django.db.backends.mysql.features import DatabaseFeatures from django.test import TestCase @skipUnless(connection.vendor == 'mysql', 'MySQL tests') class TestFeatures(TestCase): def test_supports_transactions(self): """ All storage engines except MyISAM support transactions. """ with mock.patch('django.db.connection.features._mysql_storage_engine', 'InnoDB'): self.assertTrue(connection.features.supports_transactions) del connection.features.supports_transactions with mock.patch('django.db.connection.features._mysql_storage_engine', 'MyISAM'): self.assertFalse(connection.features.supports_transactions) del connection.features.supports_transactions def test_skip_locked_no_wait(self): with mock.MagicMock() as _connection: _connection.mysql_version = (8, 0, 1) _connection.mysql_is_mariadb = False database_features = DatabaseFeatures(_connection) self.assertTrue(database_features.has_select_for_update_skip_locked) self.assertTrue(database_features.has_select_for_update_nowait) with mock.MagicMock() as _connection: _connection.mysql_version = (8, 0, 0) _connection.mysql_is_mariadb = False database_features = DatabaseFeatures(_connection) self.assertFalse(database_features.has_select_for_update_skip_locked) self.assertFalse(database_features.has_select_for_update_nowait)
7d2477c5cebc5235788094def875b74c818af157bccc331d1de12f43a70314af
import unittest from io import StringIO from unittest import mock from django.db import connection from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends.mysql.creation import DatabaseCreation from django.db.utils import DatabaseError from django.test import SimpleTestCase @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL tests') class DatabaseCreationTests(SimpleTestCase): def _execute_raise_database_exists(self, cursor, parameters, keepdb=False): raise DatabaseError(1007, "Can't create database '%s'; database exists" % parameters['dbname']) def _execute_raise_access_denied(self, cursor, parameters, keepdb=False): raise DatabaseError(1044, "Access denied for user") def patch_test_db_creation(self, execute_create_test_db): return mock.patch.object(BaseDatabaseCreation, '_execute_create_test_db', execute_create_test_db) @mock.patch('sys.stdout', new_callable=StringIO) @mock.patch('sys.stderr', new_callable=StringIO) def test_create_test_db_database_exists(self, *mocked_objects): # Simulate test database creation raising "database exists" creation = DatabaseCreation(connection) with self.patch_test_db_creation(self._execute_raise_database_exists): with mock.patch('builtins.input', return_value='no'): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test database. creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False) # "Database exists" shouldn't appear when keepdb is on creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True) @mock.patch('sys.stdout', new_callable=StringIO) @mock.patch('sys.stderr', new_callable=StringIO) def test_create_test_db_unexpected_error(self, *mocked_objects): # Simulate test database creation raising unexpected error creation = DatabaseCreation(connection) with self.patch_test_db_creation(self._execute_raise_access_denied): with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False) def test_clone_test_db_database_exists(self): creation = DatabaseCreation(connection) with self.patch_test_db_creation(self._execute_raise_database_exists): with mock.patch.object(DatabaseCreation, '_clone_db') as _clone_db: creation._clone_test_db('suffix', verbosity=0, keepdb=True) _clone_db.assert_not_called()
c670458b256426d7a945a543beda2f45d7731d14686d6686ba065a1d1cbeec00
import unittest from io import StringIO from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import DatabaseError, connection, connections from django.test import TestCase, override_settings @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL tests') class Tests(TestCase): def test_nodb_connection(self): """ The _nodb_connection property fallbacks to the default connection database when access to the 'postgres' database is not granted. """ def mocked_connect(self): if self.settings_dict['NAME'] is None: raise DatabaseError() return '' nodb_conn = connection._nodb_connection self.assertIsNone(nodb_conn.settings_dict['NAME']) # Now assume the 'postgres' db isn't available msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch('django.db.backends.base.base.BaseDatabaseWrapper.connect', side_effect=mocked_connect, autospec=True): with mock.patch.object( connection, 'settings_dict', {**connection.settings_dict, 'NAME': 'postgres'}, ): nodb_conn = connection._nodb_connection self.assertIsNotNone(nodb_conn.settings_dict['NAME']) self.assertEqual(nodb_conn.settings_dict['NAME'], connections['other'].settings_dict['NAME']) def test_database_name_too_long(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() max_name_length = connection.ops.max_name_length() settings['NAME'] = 'a' + (max_name_length * 'a') msg = ( "The database name '%s' (%d characters) is longer than " "PostgreSQL's limit of %s characters. Supply a shorter NAME in " "settings.DATABASES." ) % (settings['NAME'], max_name_length + 1, max_name_length) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_connect_and_rollback(self): """ PostgreSQL shouldn't roll back SET TIME ZONE, even if the first transaction is rolled back (#17062). """ new_connection = connection.copy() try: # Ensure the database default time zone is different than # the time zone in new_connection.settings_dict. We can # get the default time zone by reset & show. with new_connection.cursor() as cursor: cursor.execute("RESET TIMEZONE") cursor.execute("SHOW TIMEZONE") db_default_tz = cursor.fetchone()[0] new_tz = 'Europe/Paris' if db_default_tz == 'UTC' else 'UTC' new_connection.close() # Invalidate timezone name cache, because the setting_changed # handler cannot know about new_connection. del new_connection.timezone_name # Fetch a new connection with the new_tz as default # time zone, run a query and rollback. with self.settings(TIME_ZONE=new_tz): new_connection.set_autocommit(False) new_connection.rollback() # Now let's see if the rollback rolled back the SET TIME ZONE. with new_connection.cursor() as cursor: cursor.execute("SHOW TIMEZONE") tz = cursor.fetchone()[0] self.assertEqual(new_tz, tz) finally: new_connection.close() def test_connect_non_autocommit(self): """ The connection wrapper shouldn't believe that autocommit is enabled after setting the time zone when AUTOCOMMIT is False (#21452). """ new_connection = connection.copy() new_connection.settings_dict['AUTOCOMMIT'] = False try: # Open a database connection. new_connection.cursor() self.assertFalse(new_connection.get_autocommit()) finally: new_connection.close() def test_connect_isolation_level(self): """ The transaction level can be configured with DATABASES ['OPTIONS']['isolation_level']. """ import psycopg2 from psycopg2.extensions import ( ISOLATION_LEVEL_READ_COMMITTED as read_committed, ISOLATION_LEVEL_SERIALIZABLE as serializable, ) # Since this is a django.test.TestCase, a transaction is in progress # and the isolation level isn't reported as 0. This test assumes that # PostgreSQL is configured with the default isolation level. # Check the level on the psycopg2 connection, not the Django wrapper. default_level = read_committed if psycopg2.__version__ < '2.7' else None self.assertEqual(connection.connection.isolation_level, default_level) new_connection = connection.copy() new_connection.settings_dict['OPTIONS']['isolation_level'] = serializable try: # Start a transaction so the isolation level isn't reported as 0. new_connection.set_autocommit(False) # Check the level on the psycopg2 connection, not the Django wrapper. self.assertEqual(new_connection.connection.isolation_level, serializable) finally: new_connection.close() def test_connect_no_is_usable_checks(self): new_connection = connection.copy() with mock.patch.object(new_connection, 'is_usable') as is_usable: new_connection.connect() is_usable.assert_not_called() def _select(self, val): with connection.cursor() as cursor: cursor.execute('SELECT %s', (val,)) return cursor.fetchone()[0] def test_select_ascii_array(self): a = ['awef'] b = self._select(a) self.assertEqual(a[0], b[0]) def test_select_unicode_array(self): a = ['ᄲawef'] b = self._select(a) self.assertEqual(a[0], b[0]) def test_lookup_cast(self): from django.db.backends.postgresql.operations import DatabaseOperations do = DatabaseOperations(connection=None) lookups = ( 'iexact', 'contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'regex', 'iregex', ) for lookup in lookups: with self.subTest(lookup=lookup): self.assertIn('::text', do.lookup_cast(lookup)) for lookup in lookups: for field_type in ('CICharField', 'CIEmailField', 'CITextField'): with self.subTest(lookup=lookup, field_type=field_type): self.assertIn('::citext', do.lookup_cast(lookup, internal_type=field_type)) def test_correct_extraction_psycopg2_version(self): from django.db.backends.postgresql.base import psycopg2_version with mock.patch('psycopg2.__version__', '4.2.1 (dt dec pq3 ext lo64)'): self.assertEqual(psycopg2_version(), (4, 2, 1)) with mock.patch('psycopg2.__version__', '4.2b0.dev1 (dt dec pq3 ext lo64)'): self.assertEqual(psycopg2_version(), (4, 2)) @override_settings(DEBUG=True) def test_copy_cursors(self): out = StringIO() copy_expert_sql = 'COPY django_session TO STDOUT (FORMAT CSV, HEADER)' with connection.cursor() as cursor: cursor.copy_expert(copy_expert_sql, out) cursor.copy_to(out, 'django_session') self.assertEqual( [q['sql'] for q in connection.queries], [copy_expert_sql, 'COPY django_session TO STDOUT'], )
b329653a5bd5b6d6e521ffe56ca89fa2ccdfccc1345aa927b99a7e4952fe3cb4
import unittest from contextlib import contextmanager from io import StringIO from unittest import mock from django.db import connection from django.db.backends.base.creation import BaseDatabaseCreation from django.db.utils import DatabaseError from django.test import SimpleTestCase try: import psycopg2 # NOQA except ImportError: pass else: from psycopg2 import errorcodes from django.db.backends.postgresql.creation import DatabaseCreation @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL tests') class DatabaseCreationTests(SimpleTestCase): @contextmanager def changed_test_settings(self, **kwargs): settings = connection.settings_dict['TEST'] saved_values = {} for name in kwargs: if name in settings: saved_values[name] = settings[name] for name, value in kwargs.items(): settings[name] = value try: yield finally: for name in kwargs: if name in saved_values: settings[name] = saved_values[name] else: del settings[name] def check_sql_table_creation_suffix(self, settings, expected): with self.changed_test_settings(**settings): creation = DatabaseCreation(connection) suffix = creation.sql_table_creation_suffix() self.assertEqual(suffix, expected) def test_sql_table_creation_suffix_with_none_settings(self): settings = {'CHARSET': None, 'TEMPLATE': None} self.check_sql_table_creation_suffix(settings, "") def test_sql_table_creation_suffix_with_encoding(self): settings = {'CHARSET': 'UTF8'} self.check_sql_table_creation_suffix(settings, "WITH ENCODING 'UTF8'") def test_sql_table_creation_suffix_with_template(self): settings = {'TEMPLATE': 'template0'} self.check_sql_table_creation_suffix(settings, 'WITH TEMPLATE "template0"') def test_sql_table_creation_suffix_with_encoding_and_template(self): settings = {'CHARSET': 'UTF8', 'TEMPLATE': 'template0'} self.check_sql_table_creation_suffix(settings, '''WITH ENCODING 'UTF8' TEMPLATE "template0"''') def _execute_raise_database_already_exists(self, cursor, parameters, keepdb=False): error = DatabaseError('database %s already exists' % parameters['dbname']) error.pgcode = errorcodes.DUPLICATE_DATABASE raise DatabaseError() from error def _execute_raise_permission_denied(self, cursor, parameters, keepdb=False): error = DatabaseError('permission denied to create database') error.pgcode = errorcodes.INSUFFICIENT_PRIVILEGE raise DatabaseError() from error def patch_test_db_creation(self, execute_create_test_db): return mock.patch.object(BaseDatabaseCreation, '_execute_create_test_db', execute_create_test_db) @mock.patch('sys.stdout', new_callable=StringIO) @mock.patch('sys.stderr', new_callable=StringIO) def test_create_test_db(self, *mocked_objects): creation = DatabaseCreation(connection) # Simulate test database creation raising "database already exists" with self.patch_test_db_creation(self._execute_raise_database_already_exists): with mock.patch('builtins.input', return_value='no'): with self.assertRaises(SystemExit): # SystemExit is raised if the user answers "no" to the # prompt asking if it's okay to delete the test database. creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False) # "Database already exists" error is ignored when keepdb is on creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True) # Simulate test database creation raising unexpected error with self.patch_test_db_creation(self._execute_raise_permission_denied): with mock.patch.object(DatabaseCreation, '_database_exists', return_value=False): with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, autoclobber=False, keepdb=False) with self.assertRaises(SystemExit): creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True) # Simulate test database creation raising "insufficient privileges". # An error shouldn't appear when keepdb is on and the database already # exists. with self.patch_test_db_creation(self._execute_raise_permission_denied): with mock.patch.object(DatabaseCreation, '_database_exists', return_value=True): creation._create_test_db(verbosity=0, autoclobber=False, keepdb=True)
492c087c7edcabf2ac1b6d8841ab3424b7d26533ae21ea3439a9fe1d2aa7b7c7
from django.urls import re_path urlpatterns = [ re_path('^$', lambda x: x, name='name_with:colon'), ]
4d03b806eb7f23c899fd09bd54af5ffff6d1e4dc5daf1ea11e36a873fc877bd4
from django.urls import include, path, re_path urlpatterns = [ path('', include([ re_path('^include-with-dollar$', include([])), ])), ]
8cbe8027edfeeffbb03ca16ddb6ec8fc188cf928f966465d8d883b480842016d
from django.urls import path, re_path urlpatterns = [ path('/path-starting-with-slash/', lambda x: x), re_path(r'/url-starting-with-slash/$', lambda x: x), ]
28cefc18129b114baa62ae28972ae96c0739036baba1fd0829a428cce98c6aae
from django.urls import include, re_path urlpatterns = [ re_path('^include-with-dollar$', include([])), ]
4f60c25a864ea0e959efbdb109bc2c309b544932471bed1fdd81cea1070b76ec
from django.urls import include, path common_url_patterns = ([ path('app-ns1/', include([])), path('app-url/', include([])), ], 'common') nested_url_patterns = ([ path('common/', include(common_url_patterns, namespace='nested')), ], 'nested') urlpatterns = [ path('app-ns1-0/', include(common_url_patterns, namespace='app-include-1')), path('app-ns1-1/', include(common_url_patterns, namespace='app-include-2')), # 'nested' is included twice but namespaced by nested-1 and nested-2. path('app-ns1-2/', include(nested_url_patterns, namespace='nested-1')), path('app-ns1-3/', include(nested_url_patterns, namespace='nested-2')), # namespaced URLs inside non-namespaced URLs. path('app-ns1-4/', include([path('abc/', include(common_url_patterns))])), ]
cd1c203b45d4d067eec08a2f06de5db55d6aacb22dbd6f1d2775a2262697641a
urlpatterns = [] handler400 = __name__ + '.bad_handler' handler403 = __name__ + '.bad_handler' handler404 = __name__ + '.bad_handler' handler500 = __name__ + '.bad_handler' def bad_handler(): pass
ea15c1b2d90c119b6b29ae99b5ca650d17a6a151a71a36f3b9f808d5ed7a63f8
urlpatterns = [] handler400 = 'django.views.bad_handler' handler403 = 'django.invalid_module.bad_handler' handler404 = 'invalid_module.bad_handler' handler500 = 'django'
0e3ebd796f53ee8b0fd2f10bea07425672c9cdd6759bdfb52eaa9168b65dfb8c
from django.urls import include, path common_url_patterns = ([ path('app-ns1/', include([])), path('app-url/', include([])), ], 'app-ns1') urlpatterns = [ path('app-ns1-0/', include(common_url_patterns)), path('app-ns1-1/', include(common_url_patterns)), path('app-some-url/', include(([], 'app'), namespace='app-1')), path('app-some-url-2/', include(([], 'app'), namespace='app-1')) ]
eb1c7d16db7429fdf45faf4f73828addb2027eb95b514575949733df4451ac3d
from django.urls import include, path, re_path urlpatterns = [ path('foo/', lambda x: x, name='foo'), # This dollar is ok as it is escaped re_path(r'^\$', include([ path('bar/', lambda x: x, name='bar'), ])), ]
16264104a4173e555ab84592f9377396e165accedd646aa3461ca69316f6f730
urlpatterns = [] handler400 = __name__ + '.good_handler' handler403 = __name__ + '.good_handler' handler404 = __name__ + '.good_handler' handler500 = __name__ + '.good_handler' def good_handler(request, exception=None, foo='bar'): pass
14b94b22ff4ccbe541ac99180a6323472afe34ee682bf62153687f6bdbab9075
from django.conf.urls.i18n import i18n_patterns from django.urls import path from django.utils.translation import gettext_lazy as _ urlpatterns = i18n_patterns( path(_('translated/'), lambda x: x, name='i18n_prefixed'), )
5b4518233983233ce44557c2672845d918aeba4afb6b76b3a869b247dd6dc5e5
import os import re from io import StringIO from django.contrib.gis.gdal import GDAL_VERSION, Driver, GDALException from django.contrib.gis.utils.ogrinspect import ogrinspect from django.core.management import call_command from django.db import connection, connections from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import modify_settings from ..test_data import TEST_DATA from ..utils import postgis from .models import AllOGRFields class InspectDbTests(TestCase): def test_geom_columns(self): """ Test the geo-enabled inspectdb command. """ out = StringIO() call_command( 'inspectdb', table_name_filter=lambda tn: tn == 'inspectapp_allogrfields', stdout=out ) output = out.getvalue() if connection.features.supports_geometry_field_introspection: self.assertIn('geom = models.PolygonField()', output) self.assertIn('point = models.PointField()', output) else: self.assertIn('geom = models.GeometryField(', output) self.assertIn('point = models.GeometryField(', output) @skipUnlessDBFeature("supports_3d_storage") def test_3d_columns(self): out = StringIO() call_command( 'inspectdb', table_name_filter=lambda tn: tn == 'inspectapp_fields3d', stdout=out ) output = out.getvalue() if connection.features.supports_geometry_field_introspection: self.assertIn('point = models.PointField(dim=3)', output) if postgis: # Geography type is specific to PostGIS self.assertIn('pointg = models.PointField(geography=True, dim=3)', output) self.assertIn('line = models.LineStringField(dim=3)', output) self.assertIn('poly = models.PolygonField(dim=3)', output) else: self.assertIn('point = models.GeometryField(', output) self.assertIn('pointg = models.GeometryField(', output) self.assertIn('line = models.GeometryField(', output) self.assertIn('poly = models.GeometryField(', output) @modify_settings( INSTALLED_APPS={'append': 'django.contrib.gis'}, ) class OGRInspectTest(SimpleTestCase): expected_srid = 'srid=-1' if GDAL_VERSION < (2, 2) else '' maxDiff = 1024 def test_poly(self): shp_file = os.path.join(TEST_DATA, 'test_poly', 'test_poly.shp') model_def = ogrinspect(shp_file, 'MyModel') expected = [ '# This is an auto-generated Django model module created by ogrinspect.', 'from django.contrib.gis.db import models', '', '', 'class MyModel(models.Model):', ' float = models.FloatField()', ' int = models.BigIntegerField()', ' str = models.CharField(max_length=80)', ' geom = models.PolygonField(%s)' % self.expected_srid, ] self.assertEqual(model_def, '\n'.join(expected)) def test_poly_multi(self): shp_file = os.path.join(TEST_DATA, 'test_poly', 'test_poly.shp') model_def = ogrinspect(shp_file, 'MyModel', multi_geom=True) self.assertIn('geom = models.MultiPolygonField(%s)' % self.expected_srid, model_def) # Same test with a 25D-type geometry field shp_file = os.path.join(TEST_DATA, 'gas_lines', 'gas_leitung.shp') model_def = ogrinspect(shp_file, 'MyModel', multi_geom=True) srid = '-1' if GDAL_VERSION < (2, 3) else '31253' self.assertIn('geom = models.MultiLineStringField(srid=%s)' % srid, model_def) def test_date_field(self): shp_file = os.path.join(TEST_DATA, 'cities', 'cities.shp') model_def = ogrinspect(shp_file, 'City') expected = [ '# This is an auto-generated Django model module created by ogrinspect.', 'from django.contrib.gis.db import models', '', '', 'class City(models.Model):', ' name = models.CharField(max_length=80)', ' population = models.BigIntegerField()', ' density = models.FloatField()', ' created = models.DateField()', ' geom = models.PointField(%s)' % self.expected_srid, ] self.assertEqual(model_def, '\n'.join(expected)) def test_time_field(self): # Getting the database identifier used by OGR, if None returned # GDAL does not have the support compiled in. ogr_db = get_ogr_db_string() if not ogr_db: self.skipTest("Unable to setup an OGR connection to your database") try: # Writing shapefiles via GDAL currently does not support writing OGRTime # fields, so we need to actually use a database model_def = ogrinspect(ogr_db, 'Measurement', layer_key=AllOGRFields._meta.db_table, decimal=['f_decimal']) except GDALException: self.skipTest("Unable to setup an OGR connection to your database") self.assertTrue(model_def.startswith( '# This is an auto-generated Django model module created by ogrinspect.\n' 'from django.contrib.gis.db import models\n' '\n' '\n' 'class Measurement(models.Model):\n' )) # The ordering of model fields might vary depending on several factors (version of GDAL, etc.) if connection.vendor == 'sqlite': # SpatiaLite introspection is somewhat lacking (#29461). self.assertIn(' f_decimal = models.CharField(max_length=0)', model_def) else: self.assertIn(' f_decimal = models.DecimalField(max_digits=0, decimal_places=0)', model_def) self.assertIn(' f_int = models.IntegerField()', model_def) if connection.vendor != 'mysql' or not connection.mysql_is_mariadb: # Probably a bug between GDAL and MariaDB on time fields. self.assertIn(' f_datetime = models.DateTimeField()', model_def) self.assertIn(' f_time = models.TimeField()', model_def) if connection.vendor == 'sqlite': self.assertIn(' f_float = models.CharField(max_length=0)', model_def) else: self.assertIn(' f_float = models.FloatField()', model_def) max_length = 0 if connection.vendor == 'sqlite' else 10 self.assertIn(' f_char = models.CharField(max_length=%s)' % max_length, model_def) self.assertIn(' f_date = models.DateField()', model_def) # Some backends may have srid=-1 self.assertIsNotNone(re.search(r' geom = models.PolygonField\(([^\)])*\)', model_def)) def test_management_command(self): shp_file = os.path.join(TEST_DATA, 'cities', 'cities.shp') out = StringIO() call_command('ogrinspect', shp_file, 'City', stdout=out) output = out.getvalue() self.assertIn('class City(models.Model):', output) def test_mapping_option(self): expected = ( " geom = models.PointField(%s)\n" "\n" "\n" "# Auto-generated `LayerMapping` dictionary for City model\n" "city_mapping = {\n" " 'name': 'Name',\n" " 'population': 'Population',\n" " 'density': 'Density',\n" " 'created': 'Created',\n" " 'geom': 'POINT',\n" "}\n" % self.expected_srid) shp_file = os.path.join(TEST_DATA, 'cities', 'cities.shp') out = StringIO() call_command('ogrinspect', shp_file, '--mapping', 'City', stdout=out) self.assertIn(expected, out.getvalue()) def get_ogr_db_string(): """ Construct the DB string that GDAL will use to inspect the database. GDAL will create its own connection to the database, so we re-use the connection settings from the Django test. """ db = connections.databases['default'] # Map from the django backend into the OGR driver name and database identifier # https://www.gdal.org/ogr/ogr_formats.html # # TODO: Support Oracle (OCI). drivers = { 'django.contrib.gis.db.backends.postgis': ('PostgreSQL', "PG:dbname='%(db_name)s'", ' '), 'django.contrib.gis.db.backends.mysql': ('MySQL', 'MYSQL:"%(db_name)s"', ','), 'django.contrib.gis.db.backends.spatialite': ('SQLite', '%(db_name)s', '') } db_engine = db['ENGINE'] if db_engine not in drivers: return None drv_name, db_str, param_sep = drivers[db_engine] # Ensure that GDAL library has driver support for the database. try: Driver(drv_name) except GDALException: return None # SQLite/SpatiaLite in-memory databases if db['NAME'] == ":memory:": return None # Build the params of the OGR database connection string params = [db_str % {'db_name': db['NAME']}] def add(key, template): value = db.get(key, None) # Don't add the parameter if it is not in django's settings if value: params.append(template % value) add('HOST', "host='%s'") add('PORT', "port='%s'") add('USER', "user='%s'") add('PASSWORD', "password='%s'") return param_sep.join(params)
749197269dec5ce41fcb928b6d43401baa2683538b4939b10688be2afe925331
import datetime import os import unittest from copy import copy from decimal import Decimal from django.conf import settings from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils.layermapping import ( InvalidDecimal, InvalidString, LayerMapError, LayerMapping, MissingForeignKey, ) from django.db import connection from django.test import TestCase, override_settings from .models import ( City, County, CountyFeat, DoesNotAllowNulls, HasNulls, ICity1, ICity2, Interstate, Invalid, State, city_mapping, co_mapping, cofeat_mapping, has_nulls_mapping, inter_mapping, ) shp_path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'data')) city_shp = os.path.join(shp_path, 'cities', 'cities.shp') co_shp = os.path.join(shp_path, 'counties', 'counties.shp') inter_shp = os.path.join(shp_path, 'interstates', 'interstates.shp') invalid_shp = os.path.join(shp_path, 'invalid', 'emptypoints.shp') has_nulls_geojson = os.path.join(shp_path, 'has_nulls', 'has_nulls.geojson') # Dictionaries to hold what's expected in the county shapefile. NAMES = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo'] NUMS = [1, 2, 1, 19, 1] # Number of polygons for each. STATES = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado'] class LayerMapTest(TestCase): def test_init(self): "Testing LayerMapping initialization." # Model field that does not exist. bad1 = copy(city_mapping) bad1['foobar'] = 'FooField' # Shapefile field that does not exist. bad2 = copy(city_mapping) bad2['name'] = 'Nombre' # Nonexistent geographic field type. bad3 = copy(city_mapping) bad3['point'] = 'CURVE' # Incrementing through the bad mapping dictionaries and # ensuring that a LayerMapError is raised. for bad_map in (bad1, bad2, bad3): with self.assertRaises(LayerMapError): LayerMapping(City, city_shp, bad_map) # A LookupError should be thrown for bogus encodings. with self.assertRaises(LookupError): LayerMapping(City, city_shp, city_mapping, encoding='foobar') def test_simple_layermap(self): "Test LayerMapping import of a simple point shapefile." # Setting up for the LayerMapping. lm = LayerMapping(City, city_shp, city_mapping) lm.save() # There should be three cities in the shape file. self.assertEqual(3, City.objects.count()) # Opening up the shapefile, and verifying the values in each # of the features made it to the model. ds = DataSource(city_shp) layer = ds[0] for feat in layer: city = City.objects.get(name=feat['Name'].value) self.assertEqual(feat['Population'].value, city.population) self.assertEqual(Decimal(str(feat['Density'])), city.density) self.assertEqual(feat['Created'].value, city.dt) # Comparing the geometries. pnt1, pnt2 = feat.geom, city.point self.assertAlmostEqual(pnt1.x, pnt2.x, 5) self.assertAlmostEqual(pnt1.y, pnt2.y, 5) def test_layermap_strict(self): "Testing the `strict` keyword, and import of a LineString shapefile." # When the `strict` keyword is set an error encountered will force # the importation to stop. with self.assertRaises(InvalidDecimal): lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True, strict=True) Interstate.objects.all().delete() # This LayerMapping should work b/c `strict` is not set. lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True) # Two interstate should have imported correctly. self.assertEqual(2, Interstate.objects.count()) # Verifying the values in the layer w/the model. ds = DataSource(inter_shp) # Only the first two features of this shapefile are valid. valid_feats = ds[0][:2] for feat in valid_feats: istate = Interstate.objects.get(name=feat['Name'].value) if feat.fid == 0: self.assertEqual(Decimal(str(feat['Length'])), istate.length) elif feat.fid == 1: # Everything but the first two decimal digits were truncated, # because the Interstate model's `length` field has decimal_places=2. self.assertAlmostEqual(feat.get('Length'), float(istate.length), 2) for p1, p2 in zip(feat.geom, istate.path): self.assertAlmostEqual(p1[0], p2[0], 6) self.assertAlmostEqual(p1[1], p2[1], 6) def county_helper(self, county_feat=True): "Helper function for ensuring the integrity of the mapped County models." for name, n, st in zip(NAMES, NUMS, STATES): # Should only be one record b/c of `unique` keyword. c = County.objects.get(name=name) self.assertEqual(n, len(c.mpoly)) self.assertEqual(st, c.state.name) # Checking ForeignKey mapping. # Multiple records because `unique` was not set. if county_feat: qs = CountyFeat.objects.filter(name=name) self.assertEqual(n, qs.count()) def test_layermap_unique_multigeometry_fk(self): "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings." # All the following should work. # Telling LayerMapping that we want no transformations performed on the data. lm = LayerMapping(County, co_shp, co_mapping, transform=False) # Specifying the source spatial reference system via the `source_srs` keyword. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269) lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83') # Unique may take tuple or string parameters. for arg in ('name', ('name', 'mpoly')): lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) # Now test for failures # Testing invalid params for the `unique` keyword. for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))): with self.assertRaises(e): LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) # No source reference system defined in the shapefile, should raise an error. if connection.features.supports_transform: with self.assertRaises(LayerMapError): LayerMapping(County, co_shp, co_mapping) # Passing in invalid ForeignKey mapping parameters -- must be a dictionary # mapping for the model the ForeignKey points to. bad_fk_map1 = copy(co_mapping) bad_fk_map1['state'] = 'name' bad_fk_map2 = copy(co_mapping) bad_fk_map2['state'] = {'nombre': 'State'} with self.assertRaises(TypeError): LayerMapping(County, co_shp, bad_fk_map1, transform=False) with self.assertRaises(LayerMapError): LayerMapping(County, co_shp, bad_fk_map2, transform=False) # There exist no State models for the ForeignKey mapping to work -- should raise # a MissingForeignKey exception (this error would be ignored if the `strict` # keyword is not set). lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') with self.assertRaises(MissingForeignKey): lm.save(silent=True, strict=True) # Now creating the state models so the ForeignKey mapping may work. State.objects.bulk_create([ State(name='Colorado'), State(name='Hawaii'), State(name='Texas') ]) # If a mapping is specified as a collection, all OGR fields that # are not collections will be converted into them. For example, # a Point column would be converted to MultiPoint. Other things being done # w/the keyword args: # `transform=False`: Specifies that no transform is to be done; this # has the effect of ignoring the spatial reference check (because the # county shapefile does not have implicit spatial reference info). # # `unique='name'`: Creates models on the condition that they have # unique county names; geometries from each feature however will be # appended to the geometry collection of the unique model. Thus, # all of the various islands in Honolulu county will be in in one # database record with a MULTIPOLYGON type. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') lm.save(silent=True, strict=True) # A reference that doesn't use the unique keyword; a new database record will # created for each polygon. lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False) lm.save(silent=True, strict=True) # The county helper is called to ensure integrity of County models. self.county_helper() def test_test_fid_range_step(self): "Tests the `fid_range` keyword and the `step` keyword of .save()." # Function for clearing out all the counties before testing. def clear_counties(): County.objects.all().delete() State.objects.bulk_create([ State(name='Colorado'), State(name='Hawaii'), State(name='Texas') ]) # Initializing the LayerMapping object to use in these tests. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') # Bad feature id ranges should raise a type error. bad_ranges = (5.0, 'foo', co_shp) for bad in bad_ranges: with self.assertRaises(TypeError): lm.save(fid_range=bad) # Step keyword should not be allowed w/`fid_range`. fr = (3, 5) # layer[3:5] with self.assertRaises(LayerMapError): lm.save(fid_range=fr, step=10) lm.save(fid_range=fr) # Features IDs 3 & 4 are for Galveston County, Texas -- only # one model is returned because the `unique` keyword was set. qs = County.objects.all() self.assertEqual(1, qs.count()) self.assertEqual('Galveston', qs[0].name) # Features IDs 5 and beyond for Honolulu County, Hawaii, and # FID 0 is for Pueblo County, Colorado. clear_counties() lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:] lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1] # Only Pueblo & Honolulu counties should be present because of # the `unique` keyword. Have to set `order_by` on this QuerySet # or else MySQL will return a different ordering than the other dbs. qs = County.objects.order_by('name') self.assertEqual(2, qs.count()) hi, co = tuple(qs) hi_idx, co_idx = tuple(map(NAMES.index, ('Honolulu', 'Pueblo'))) self.assertEqual('Pueblo', co.name) self.assertEqual(NUMS[co_idx], len(co.mpoly)) self.assertEqual('Honolulu', hi.name) self.assertEqual(NUMS[hi_idx], len(hi.mpoly)) # Testing the `step` keyword -- should get the same counties # regardless of we use a step that divides equally, that is odd, # or that is larger than the dataset. for st in (4, 7, 1000): clear_counties() lm.save(step=st, strict=True) self.county_helper(county_feat=False) def test_model_inheritance(self): "Tests LayerMapping on inherited models. See #12093." icity_mapping = { 'name': 'Name', 'population': 'Population', 'density': 'Density', 'point': 'POINT', 'dt': 'Created', } # Parent model has geometry field. lm1 = LayerMapping(ICity1, city_shp, icity_mapping) lm1.save() # Grandparent has geometry field. lm2 = LayerMapping(ICity2, city_shp, icity_mapping) lm2.save() self.assertEqual(6, ICity1.objects.count()) self.assertEqual(3, ICity2.objects.count()) def test_invalid_layer(self): "Tests LayerMapping on invalid geometries. See #15378." invalid_mapping = {'point': 'POINT'} lm = LayerMapping(Invalid, invalid_shp, invalid_mapping, source_srs=4326) lm.save(silent=True) def test_charfield_too_short(self): mapping = copy(city_mapping) mapping['name_short'] = 'Name' lm = LayerMapping(City, city_shp, mapping) with self.assertRaises(InvalidString): lm.save(silent=True, strict=True) def test_textfield(self): "String content fits also in a TextField" mapping = copy(city_mapping) mapping['name_txt'] = 'Name' lm = LayerMapping(City, city_shp, mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 3) self.assertEqual(City.objects.get(name='Houston').name_txt, "Houston") def test_encoded_name(self): """ Test a layer containing utf-8-encoded name """ city_shp = os.path.join(shp_path, 'ch-city', 'ch-city.shp') lm = LayerMapping(City, city_shp, city_mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 1) self.assertEqual(City.objects.all()[0].name, "Zürich") def test_null_geom_with_unique(self): """LayerMapping may be created with a unique and a null geometry.""" State.objects.bulk_create([State(name='Colorado'), State(name='Hawaii'), State(name='Texas')]) hw = State.objects.get(name='Hawaii') hu = County.objects.create(name='Honolulu', state=hw, mpoly=None) lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') lm.save(silent=True, strict=True) hu.refresh_from_db() self.assertIsNotNone(hu.mpoly) self.assertEqual(hu.mpoly.ogr.num_coords, 449) def test_null_number_imported(self): """LayerMapping import of GeoJSON with a null numeric value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.count(), 3) self.assertEqual(HasNulls.objects.filter(num=0).count(), 1) self.assertEqual(HasNulls.objects.filter(num__isnull=True).count(), 1) def test_null_string_imported(self): "Test LayerMapping import of GeoJSON with a null string value." lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(name='None').count(), 0) num_empty = 1 if connection.features.interprets_empty_strings_as_nulls else 0 self.assertEqual(HasNulls.objects.filter(name='').count(), num_empty) self.assertEqual(HasNulls.objects.filter(name__isnull=True).count(), 1) def test_nullable_boolean_imported(self): """LayerMapping import of GeoJSON with a nullable boolean value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(boolean=True).count(), 1) self.assertEqual(HasNulls.objects.filter(boolean=False).count(), 1) self.assertEqual(HasNulls.objects.filter(boolean__isnull=True).count(), 1) def test_nullable_datetime_imported(self): """LayerMapping import of GeoJSON with a nullable date/time value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(datetime__lt=datetime.date(1994, 8, 15)).count(), 1) self.assertEqual(HasNulls.objects.filter(datetime='2018-11-29T03:02:52').count(), 1) self.assertEqual(HasNulls.objects.filter(datetime__isnull=True).count(), 1) def test_uuids_imported(self): """LayerMapping import of GeoJSON with UUIDs.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(uuid='1378c26f-cbe6-44b0-929f-eb330d4991f5').count(), 1) def test_null_number_imported_not_allowed(self): """ LayerMapping import of GeoJSON with nulls to fields that don't permit them. """ lm = LayerMapping(DoesNotAllowNulls, has_nulls_geojson, has_nulls_mapping) lm.save(silent=True) # When a model fails to save due to IntegrityError (null in non-null # column), subsequent saves fail with "An error occurred in the current # transaction. You can't execute queries until the end of the 'atomic' # block." On Oracle and MySQL, the one object that did load appears in # this count. On other databases, no records appear. self.assertLessEqual(DoesNotAllowNulls.objects.count(), 1) class OtherRouter: def db_for_read(self, model, **hints): return 'other' def db_for_write(self, model, **hints): return self.db_for_read(model, **hints) def allow_relation(self, obj1, obj2, **hints): # ContentType objects are created during a post-migrate signal while # performing fixture teardown using the default database alias and # don't abide by the database specified by this router. return True def allow_migrate(self, db, app_label, **hints): return True @override_settings(DATABASE_ROUTERS=[OtherRouter()]) class LayerMapRouterTest(TestCase): databases = {'default', 'other'} @unittest.skipUnless(len(settings.DATABASES) > 1, 'multiple databases required') def test_layermapping_default_db(self): lm = LayerMapping(City, city_shp, city_mapping) self.assertEqual(lm.using, 'other')
a3d5c514a34b7e4f3658439e38e3435a715415975728446fd688e4c3bf5bc9b8
from django.contrib.gis.db import models class NamedModel(models.Model): name = models.CharField(max_length=25) class Meta: abstract = True def __str__(self): return self.name class State(NamedModel): pass class County(NamedModel): state = models.ForeignKey(State, models.CASCADE) mpoly = models.MultiPolygonField(srid=4269, null=True) # Multipolygon in NAD83 class CountyFeat(NamedModel): poly = models.PolygonField(srid=4269) class City(NamedModel): name_txt = models.TextField(default='') name_short = models.CharField(max_length=5) population = models.IntegerField() density = models.DecimalField(max_digits=7, decimal_places=1) dt = models.DateField() point = models.PointField() class Meta: app_label = 'layermap' class Interstate(NamedModel): length = models.DecimalField(max_digits=6, decimal_places=2) path = models.LineStringField() class Meta: app_label = 'layermap' # Same as `City` above, but for testing model inheritance. class CityBase(NamedModel): population = models.IntegerField() density = models.DecimalField(max_digits=7, decimal_places=1) point = models.PointField() class ICity1(CityBase): dt = models.DateField() class Meta(CityBase.Meta): pass class ICity2(ICity1): dt_time = models.DateTimeField(auto_now=True) class Meta(ICity1.Meta): pass class Invalid(models.Model): point = models.PointField() class HasNulls(models.Model): uuid = models.UUIDField(primary_key=True, editable=False) geom = models.PolygonField(srid=4326, blank=True, null=True) datetime = models.DateTimeField(blank=True, null=True) integer = models.IntegerField(blank=True, null=True) num = models.FloatField(blank=True, null=True) boolean = models.BooleanField(blank=True, null=True) name = models.CharField(blank=True, null=True, max_length=20) class DoesNotAllowNulls(models.Model): uuid = models.UUIDField(primary_key=True, editable=False) geom = models.PolygonField(srid=4326) datetime = models.DateTimeField() integer = models.IntegerField() num = models.FloatField() boolean = models.BooleanField() name = models.CharField(max_length=20) # Mapping dictionaries for the models above. co_mapping = { 'name': 'Name', # ForeignKey's use another mapping dictionary for the _related_ Model (State in this case). 'state': {'name': 'State'}, 'mpoly': 'MULTIPOLYGON', # Will convert POLYGON features into MULTIPOLYGONS. } cofeat_mapping = { 'name': 'Name', 'poly': 'POLYGON', } city_mapping = { 'name': 'Name', 'population': 'Population', 'density': 'Density', 'dt': 'Created', 'point': 'POINT', } inter_mapping = { 'name': 'Name', 'length': 'Length', 'path': 'LINESTRING', } has_nulls_mapping = { 'geom': 'POLYGON', 'uuid': 'uuid', 'datetime': 'datetime', 'name': 'name', 'integer': 'integer', 'num': 'num', 'boolean': 'boolean', }
7de726894e2c7c263d38fe54cb9708bee19dd9271d02be6793e1458076aa8a4e
import json from django.contrib.gis.db.models.fields import BaseSpatialField from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.db.models.lookups import DistanceLookupBase, GISLookup from django.contrib.gis.gdal import GDALRaster from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.measure import D from django.contrib.gis.shortcuts import numpy from django.db import connection from django.db.models import Q from django.test import TransactionTestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..data.rasters.textrasters import JSON_RASTER from .models import RasterModel, RasterRelatedModel @skipUnlessDBFeature('supports_raster') class RasterFieldTest(TransactionTestCase): available_apps = ['gis_tests.rasterapp'] def setUp(self): rast = GDALRaster({ "srid": 4326, "origin": [0, 0], "scale": [-1, 1], "skew": [0, 0], "width": 5, "height": 5, "nr_of_bands": 2, "bands": [{"data": range(25)}, {"data": range(25, 50)}], }) model_instance = RasterModel.objects.create( rast=rast, rastprojected=rast, geom="POINT (-95.37040 29.70486)", ) RasterRelatedModel.objects.create(rastermodel=model_instance) def test_field_null_value(self): """ Test creating a model where the RasterField has a null value. """ r = RasterModel.objects.create(rast=None) r.refresh_from_db() self.assertIsNone(r.rast) def test_access_band_data_directly_from_queryset(self): RasterModel.objects.create(rast=JSON_RASTER) qs = RasterModel.objects.all() qs[0].rast.bands[0].data() def test_model_creation(self): """ Test RasterField through a test model. """ # Create model instance from JSON raster r = RasterModel.objects.create(rast=JSON_RASTER) r.refresh_from_db() # Test raster metadata properties self.assertEqual((5, 5), (r.rast.width, r.rast.height)) self.assertEqual([0.0, -1.0, 0.0, 0.0, 0.0, 1.0], r.rast.geotransform) self.assertIsNone(r.rast.bands[0].nodata_value) # Compare srs self.assertEqual(r.rast.srs.srid, 4326) # Compare pixel values band = r.rast.bands[0].data() # If numpy, convert result to list if numpy: band = band.flatten().tolist() # Loop through rows in band data and assert single # value is as expected. self.assertEqual( [ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0 ], band ) def test_implicit_raster_transformation(self): """ Test automatic transformation of rasters with srid different from the field srid. """ # Parse json raster rast = json.loads(JSON_RASTER) # Update srid to another value rast['srid'] = 3086 # Save model and get it from db r = RasterModel.objects.create(rast=rast) r.refresh_from_db() # Confirm raster has been transformed to the default srid self.assertEqual(r.rast.srs.srid, 4326) # Confirm geotransform is in lat/lon expected = [ -87.9298551266551, 9.459646421449934e-06, 0.0, 23.94249275457565, 0.0, -9.459646421449934e-06, ] for val, exp in zip(r.rast.geotransform, expected): self.assertAlmostEqual(exp, val) def test_verbose_name_arg(self): """ RasterField should accept a positional verbose name argument. """ self.assertEqual( RasterModel._meta.get_field('rast').verbose_name, 'A Verbose Raster Name' ) def test_all_gis_lookups_with_rasters(self): """ Evaluate all possible lookups for all input combinations (i.e. raster-raster, raster-geom, geom-raster) and for projected and unprojected coordinate systems. This test just checks that the lookup can be called, but doesn't check if the result makes logical sense. """ from django.contrib.gis.db.backends.postgis.operations import PostGISOperations # Create test raster and geom. rast = GDALRaster(json.loads(JSON_RASTER)) stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326) stx_pnt.transform(3086) lookups = [ (name, lookup) for name, lookup in BaseSpatialField.get_lookups().items() if issubclass(lookup, GISLookup) ] self.assertNotEqual(lookups, [], 'No lookups found') # Loop through all the GIS lookups. for name, lookup in lookups: # Construct lookup filter strings. combo_keys = [ field + name for field in [ 'rast__', 'rast__', 'rastprojected__0__', 'rast__', 'rastprojected__', 'geom__', 'rast__', ] ] if issubclass(lookup, DistanceLookupBase): # Set lookup values for distance lookups. combo_values = [ (rast, 50, 'spheroid'), (rast, 0, 50, 'spheroid'), (rast, 0, D(km=1)), (stx_pnt, 0, 500), (stx_pnt, D(km=1000)), (rast, 500), (json.loads(JSON_RASTER), 500), ] elif name == 'relate': # Set lookup values for the relate lookup. combo_values = [ (rast, 'T*T***FF*'), (rast, 0, 'T*T***FF*'), (rast, 0, 'T*T***FF*'), (stx_pnt, 0, 'T*T***FF*'), (stx_pnt, 'T*T***FF*'), (rast, 'T*T***FF*'), (json.loads(JSON_RASTER), 'T*T***FF*'), ] elif name == 'isvalid': # The isvalid lookup doesn't make sense for rasters. continue elif PostGISOperations.gis_operators[name].func: # Set lookup values for all function based operators. combo_values = [ rast, (rast, 0), (rast, 0), (stx_pnt, 0), stx_pnt, rast, json.loads(JSON_RASTER) ] else: # Override band lookup for these, as it's not supported. combo_keys[2] = 'rastprojected__' + name # Set lookup values for all other operators. combo_values = [rast, None, rast, stx_pnt, stx_pnt, rast, json.loads(JSON_RASTER)] # Create query filter combinations. self.assertEqual( len(combo_keys), len(combo_values), 'Number of lookup names and values should be the same', ) combos = [x for x in zip(combo_keys, combo_values) if x[1]] self.assertEqual( [(n, x) for n, x in enumerate(combos) if x in combos[:n]], [], 'There are repeated test lookups', ) combos = [{k: v} for k, v in combos] for combo in combos: # Apply this query filter. qs = RasterModel.objects.filter(**combo) # Evaluate normal filter qs. self.assertIn(qs.count(), [0, 1]) # Evaluate on conditional Q expressions. qs = RasterModel.objects.filter(Q(**combos[0]) & Q(**combos[1])) self.assertIn(qs.count(), [0, 1]) def test_dwithin_gis_lookup_output_with_rasters(self): """ Check the logical functionality of the dwithin lookup for different input parameters. """ # Create test raster and geom. rast = GDALRaster(json.loads(JSON_RASTER)) stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326) stx_pnt.transform(3086) # Filter raster with different lookup raster formats. qs = RasterModel.objects.filter(rastprojected__dwithin=(rast, D(km=1))) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rastprojected__dwithin=(json.loads(JSON_RASTER), D(km=1))) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rastprojected__dwithin=(JSON_RASTER, D(km=1))) self.assertEqual(qs.count(), 1) # Filter in an unprojected coordinate system. qs = RasterModel.objects.filter(rast__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) # Filter with band index transform. qs = RasterModel.objects.filter(rast__1__dwithin=(rast, 1, 40)) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rast__1__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rast__dwithin=(rast, 1, 40)) self.assertEqual(qs.count(), 1) # Filter raster by geom. qs = RasterModel.objects.filter(rast__dwithin=(stx_pnt, 500)) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rastprojected__dwithin=(stx_pnt, D(km=10000))) self.assertEqual(qs.count(), 1) qs = RasterModel.objects.filter(rast__dwithin=(stx_pnt, 5)) self.assertEqual(qs.count(), 0) qs = RasterModel.objects.filter(rastprojected__dwithin=(stx_pnt, D(km=100))) self.assertEqual(qs.count(), 0) # Filter geom by raster. qs = RasterModel.objects.filter(geom__dwithin=(rast, 500)) self.assertEqual(qs.count(), 1) # Filter through related model. qs = RasterRelatedModel.objects.filter(rastermodel__rast__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) # Filter through related model with band index transform qs = RasterRelatedModel.objects.filter(rastermodel__rast__1__dwithin=(rast, 40)) self.assertEqual(qs.count(), 1) # Filter through conditional statements. qs = RasterModel.objects.filter(Q(rast__dwithin=(rast, 40)) & Q(rastprojected__dwithin=(stx_pnt, D(km=10000)))) self.assertEqual(qs.count(), 1) # Filter through different lookup. qs = RasterModel.objects.filter(rastprojected__bbcontains=rast) self.assertEqual(qs.count(), 1) def test_lookup_input_tuple_too_long(self): rast = GDALRaster(json.loads(JSON_RASTER)) msg = 'Tuple too long for lookup bbcontains.' with self.assertRaisesMessage(ValueError, msg): RasterModel.objects.filter(rast__bbcontains=(rast, 1, 2)) def test_lookup_input_band_not_allowed(self): rast = GDALRaster(json.loads(JSON_RASTER)) qs = RasterModel.objects.filter(rast__bbcontains=(rast, 1)) msg = 'Band indices are not allowed for this operator, it works on bbox only.' with self.assertRaisesMessage(ValueError, msg): qs.count() def test_isvalid_lookup_with_raster_error(self): qs = RasterModel.objects.filter(rast__isvalid=True) msg = 'IsValid function requires a GeometryField in position 1, got RasterField.' with self.assertRaisesMessage(TypeError, msg): qs.count() def test_result_of_gis_lookup_with_rasters(self): # Point is in the interior qs = RasterModel.objects.filter(rast__contains=GEOSGeometry('POINT (-0.5 0.5)', 4326)) self.assertEqual(qs.count(), 1) # Point is in the exterior qs = RasterModel.objects.filter(rast__contains=GEOSGeometry('POINT (0.5 0.5)', 4326)) self.assertEqual(qs.count(), 0) # A point on the boundary is not contained properly qs = RasterModel.objects.filter(rast__contains_properly=GEOSGeometry('POINT (0 0)', 4326)) self.assertEqual(qs.count(), 0) # Raster is located left of the point qs = RasterModel.objects.filter(rast__left=GEOSGeometry('POINT (1 0)', 4326)) self.assertEqual(qs.count(), 1) def test_lookup_with_raster_bbox(self): rast = GDALRaster(json.loads(JSON_RASTER)) # Shift raster upwards rast.origin.y = 2 # The raster in the model is not strictly below qs = RasterModel.objects.filter(rast__strictly_below=rast) self.assertEqual(qs.count(), 0) # Shift raster further upwards rast.origin.y = 6 # The raster in the model is strictly below qs = RasterModel.objects.filter(rast__strictly_below=rast) self.assertEqual(qs.count(), 1) def test_lookup_with_polygonized_raster(self): rast = GDALRaster(json.loads(JSON_RASTER)) # Move raster to overlap with the model point on the left side rast.origin.x = -95.37040 + 1 rast.origin.y = 29.70486 # Raster overlaps with point in model qs = RasterModel.objects.filter(geom__intersects=rast) self.assertEqual(qs.count(), 1) # Change left side of raster to be nodata values rast.bands[0].data(data=[0, 0, 0, 1, 1], shape=(5, 1)) rast.bands[0].nodata_value = 0 qs = RasterModel.objects.filter(geom__intersects=rast) # Raster does not overlap anymore after polygonization # where the nodata zone is not included. self.assertEqual(qs.count(), 0) def test_lookup_value_error(self): # Test with invalid dict lookup parameter obj = {} msg = "Couldn't create spatial object from lookup value '%s'." % obj with self.assertRaisesMessage(ValueError, msg): RasterModel.objects.filter(geom__intersects=obj) # Test with invalid string lookup parameter obj = '00000' msg = "Couldn't create spatial object from lookup value '%s'." % obj with self.assertRaisesMessage(ValueError, msg): RasterModel.objects.filter(geom__intersects=obj) def test_db_function_errors(self): """ Errors are raised when using DB functions with raster content. """ point = GEOSGeometry("SRID=3086;POINT (-697024.9213808845 683729.1705516104)") rast = GDALRaster(json.loads(JSON_RASTER)) msg = "Distance function requires a geometric argument in position 2." with self.assertRaisesMessage(TypeError, msg): RasterModel.objects.annotate(distance_from_point=Distance("geom", rast)) with self.assertRaisesMessage(TypeError, msg): RasterModel.objects.annotate(distance_from_point=Distance("rastprojected", rast)) msg = "Distance function requires a GeometryField in position 1, got RasterField." with self.assertRaisesMessage(TypeError, msg): RasterModel.objects.annotate(distance_from_point=Distance("rastprojected", point)).count() def test_lhs_with_index_rhs_without_index(self): with CaptureQueriesContext(connection) as queries: RasterModel.objects.filter(rast__0__contains=json.loads(JSON_RASTER)).exists() # It's easier to check the indexes in the generated SQL than to write # tests that cover all index combinations. self.assertRegex(queries[-1]['sql'], r'WHERE ST_Contains\([^)]*, 1, [^)]*, 1\)')
37f874e888664d3ff05893b21ed1040e0977b90891912a3c9ad3092a11cb5ae1
import json import math import re from decimal import Decimal from django.contrib.gis.db.models import functions from django.contrib.gis.geos import ( GEOSGeometry, LineString, Point, Polygon, fromstr, ) from django.contrib.gis.measure import Area from django.db import NotSupportedError, connection from django.db.models import Sum from django.test import TestCase, skipUnlessDBFeature from ..utils import FuncTestMixin, mysql, oracle, postgis, spatialite from .models import City, Country, CountryWebMercator, State, Track class GISFunctionsTests(FuncTestMixin, TestCase): """ Testing functions from django/contrib/gis/db/models/functions.py. Area/Distance/Length/Perimeter are tested in distapp/tests. Please keep the tests in function's alphabetic order. """ fixtures = ['initial'] def test_asgeojson(self): if not connection.features.has_AsGeoJSON_function: with self.assertRaises(NotSupportedError): list(Country.objects.annotate(json=functions.AsGeoJSON('mpoly'))) return pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = ( '{"type":"Point","crs":{"type":"name","properties":' '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}' ) victoria_json = ( '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],' '"coordinates":[-123.305196,48.462611]}' ) chicago_json = ( '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},' '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}' ) # MySQL ignores the crs option. if mysql: houston_json = json.loads(houston_json) del houston_json['crs'] chicago_json = json.loads(chicago_json) del chicago_json['crs'] # Precision argument should only be an integer with self.assertRaises(TypeError): City.objects.annotate(geojson=functions.AsGeoJSON('point', precision='foo')) # Reference queries and values. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo'; self.assertJSONEqual( pueblo_json, City.objects.annotate(geojson=functions.AsGeoJSON('point')).get(name='Pueblo').geojson ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we want to include the CRS by using the `crs` keyword. self.assertJSONEqual( City.objects.annotate(json=functions.AsGeoJSON('point', crs=True)).get(name='Houston').json, houston_json, ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we include the bounding box by using the `bbox` keyword. self.assertJSONEqual( victoria_json, City.objects.annotate( geojson=functions.AsGeoJSON('point', bbox=True) ).get(name='Victoria').geojson ) # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Chicago'; # Finally, we set every available keyword. # MariaDB doesn't limit the number of decimals in bbox. if mysql and connection.mysql_is_mariadb: chicago_json['bbox'] = [-87.650175, 41.850385, -87.650175, 41.850385] self.assertJSONEqual( City.objects.annotate( geojson=functions.AsGeoJSON('point', bbox=True, crs=True, precision=5) ).get(name='Chicago').geojson, chicago_json, ) @skipUnlessDBFeature("has_AsGML_function") def test_asgml(self): # Should throw a TypeError when trying to obtain GML from a # non-geometry field. qs = City.objects.all() with self.assertRaises(TypeError): qs.annotate(gml=functions.AsGML('name')) ptown = City.objects.annotate(gml=functions.AsGML('point', precision=9)).get(name='Pueblo') if oracle: # No precision parameter for Oracle :-/ gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326" xmlns:gml="http://www.opengis.net/gml">' r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ ' r'</gml:coordinates></gml:Point>' ) else: gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>' r'-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>' ) self.assertTrue(gml_regex.match(ptown.gml)) self.assertIn( '<gml:pos srsDimension="2">', City.objects.annotate(gml=functions.AsGML('point', version=3)).get(name='Pueblo').gml ) @skipUnlessDBFeature("has_AsKML_function") def test_askml(self): # Should throw a TypeError when trying to obtain KML from a # non-geometry field. with self.assertRaises(TypeError): City.objects.annotate(kml=functions.AsKML('name')) # Ensuring the KML is as expected. ptown = City.objects.annotate(kml=functions.AsKML('point', precision=9)).get(name='Pueblo') self.assertEqual('<Point><coordinates>-104.609252,38.255001</coordinates></Point>', ptown.kml) @skipUnlessDBFeature("has_AsSVG_function") def test_assvg(self): with self.assertRaises(TypeError): City.objects.annotate(svg=functions.AsSVG('point', precision='foo')) # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; svg1 = 'cx="-104.609252" cy="-38.255001"' # Even though relative, only one point so it's practically the same except for # the 'c' letter prefix on the x,y values. svg2 = svg1.replace('c', '') self.assertEqual(svg1, City.objects.annotate(svg=functions.AsSVG('point')).get(name='Pueblo').svg) self.assertEqual(svg2, City.objects.annotate(svg=functions.AsSVG('point', relative=5)).get(name='Pueblo').svg) @skipUnlessDBFeature("has_Azimuth_function") def test_azimuth(self): # Returns the azimuth in radians. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(1, 1, srid=4326)) self.assertAlmostEqual(City.objects.annotate(azimuth=azimuth_expr).first().azimuth, math.pi / 4) # Returns None if the two points are coincident. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(0, 0, srid=4326)) self.assertIsNone(City.objects.annotate(azimuth=azimuth_expr).first().azimuth) @skipUnlessDBFeature("has_BoundingCircle_function") def test_bounding_circle(self): def circle_num_points(num_seg): # num_seg is the number of segments per quarter circle. return (4 * num_seg) + 1 expected_areas = (169, 136) if postgis else (171, 126) qs = Country.objects.annotate(circle=functions.BoundingCircle('mpoly')).order_by('name') self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0) self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0) if postgis: # By default num_seg=48. self.assertEqual(qs[0].circle.num_points, circle_num_points(48)) self.assertEqual(qs[1].circle.num_points, circle_num_points(48)) qs = Country.objects.annotate(circle=functions.BoundingCircle('mpoly', num_seg=12)).order_by('name') if postgis: self.assertGreater(qs[0].circle.area, 168.4, 0) self.assertLess(qs[0].circle.area, 169.5, 0) self.assertAlmostEqual(qs[1].circle.area, 136, 0) self.assertEqual(qs[0].circle.num_points, circle_num_points(12)) self.assertEqual(qs[1].circle.num_points, circle_num_points(12)) else: self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0) self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0) @skipUnlessDBFeature("has_Centroid_function") def test_centroid(self): qs = State.objects.exclude(poly__isnull=True).annotate(centroid=functions.Centroid('poly')) tol = 1.8 if mysql else (0.1 if oracle else 0.00001) for state in qs: self.assertTrue(state.poly.centroid.equals_exact(state.centroid, tol)) with self.assertRaisesMessage(TypeError, "'Centroid' takes exactly 1 argument (2 given)"): State.objects.annotate(centroid=functions.Centroid('poly', 'poly')) @skipUnlessDBFeature("has_Difference_function") def test_difference(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(diff=functions.Difference('mpoly', geom)) # Oracle does something screwy with the Texas geometry. if oracle: qs = qs.exclude(name='Texas') for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.diff)) @skipUnlessDBFeature("has_Difference_function", "has_Transform_function") def test_difference_mixed_srid(self): """Testing with mixed SRID (Country has default 4326).""" geom = Point(556597.4, 2632018.6, srid=3857) # Spherical Mercator qs = Country.objects.annotate(difference=functions.Difference('mpoly', geom)) # Oracle does something screwy with the Texas geometry. if oracle: qs = qs.exclude(name='Texas') for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.difference)) @skipUnlessDBFeature("has_Envelope_function") def test_envelope(self): countries = Country.objects.annotate(envelope=functions.Envelope('mpoly')) for country in countries: self.assertTrue(country.envelope.equals(country.mpoly.envelope)) @skipUnlessDBFeature("has_ForcePolygonCW_function") def test_force_polygon_cw(self): rings = ( ((0, 0), (5, 0), (0, 5), (0, 0)), ((1, 1), (1, 3), (3, 1), (1, 1)), ) rhr_rings = ( ((0, 0), (0, 5), (5, 0), (0, 0)), ((1, 1), (3, 1), (1, 3), (1, 1)), ) State.objects.create(name='Foo', poly=Polygon(*rings)) st = State.objects.annotate(force_polygon_cw=functions.ForcePolygonCW('poly')).get(name='Foo') self.assertEqual(rhr_rings, st.force_polygon_cw.coords) @skipUnlessDBFeature("has_GeoHash_function") def test_geohash(self): # Reference query: # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston'; # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston'; ref_hash = '9vk1mfq8jx0c8e0386z6' h1 = City.objects.annotate(geohash=functions.GeoHash('point')).get(name='Houston') h2 = City.objects.annotate(geohash=functions.GeoHash('point', precision=5)).get(name='Houston') self.assertEqual(ref_hash, h1.geohash[:len(ref_hash)]) self.assertEqual(ref_hash[:5], h2.geohash) @skipUnlessDBFeature('has_GeometryDistance_function') def test_geometry_distance(self): point = Point(-90, 40, srid=4326) qs = City.objects.annotate(distance=functions.GeometryDistance('point', point)).order_by('distance') self.assertEqual([city.distance for city in qs], [ 2.99091995527296, 5.33507274054713, 9.33852187483721, 9.91769193646233, 11.556465744884, 14.713098433352, 34.3635252198568, 276.987855073372, ]) @skipUnlessDBFeature("has_Intersection_function") def test_intersection(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(inter=functions.Intersection('mpoly', geom)) for c in qs: if spatialite or (mysql and not connection.features.supports_empty_geometry_collection) or oracle: # When the intersection is empty, some databases return None. expected = None else: expected = c.mpoly.intersection(geom) self.assertEqual(c.inter, expected) @skipUnlessDBFeature("has_IsValid_function") def test_isvalid(self): valid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))') invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))') State.objects.create(name='valid', poly=valid_geom) State.objects.create(name='invalid', poly=invalid_geom) valid = State.objects.filter(name='valid').annotate(isvalid=functions.IsValid('poly')).first() invalid = State.objects.filter(name='invalid').annotate(isvalid=functions.IsValid('poly')).first() self.assertIs(valid.isvalid, True) self.assertIs(invalid.isvalid, False) @skipUnlessDBFeature("has_Area_function") def test_area_with_regular_aggregate(self): # Create projected country objects, for this test to work on all backends. for c in Country.objects.all(): CountryWebMercator.objects.create(name=c.name, mpoly=c.mpoly.transform(3857, clone=True)) # Test in projected coordinate system qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area('mpoly'))) # Some backends (e.g. Oracle) cannot group by multipolygon values, so # defer such fields in the aggregation query. for c in qs.defer('mpoly'): result = c.area_sum # If the result is a measure object, get value. if isinstance(result, Area): result = result.sq_m self.assertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0) @skipUnlessDBFeature("has_Area_function") def test_area_lookups(self): # Create projected countries so the test works on all backends. CountryWebMercator.objects.bulk_create( CountryWebMercator(name=c.name, mpoly=c.mpoly.transform(3857, clone=True)) for c in Country.objects.all() ) qs = CountryWebMercator.objects.annotate(area=functions.Area('mpoly')) self.assertEqual(qs.get(area__lt=Area(sq_km=500000)), CountryWebMercator.objects.get(name='New Zealand')) with self.assertRaisesMessage(ValueError, 'AreaField only accepts Area measurement objects.'): qs.get(area__lt=500000) @skipUnlessDBFeature("has_LineLocatePoint_function") def test_line_locate_point(self): pos_expr = functions.LineLocatePoint(LineString((0, 0), (0, 3), srid=4326), Point(0, 1, srid=4326)) self.assertAlmostEqual(State.objects.annotate(pos=pos_expr).first().pos, 0.3333333) @skipUnlessDBFeature("has_MakeValid_function") def test_make_valid(self): invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))') State.objects.create(name='invalid', poly=invalid_geom) invalid = State.objects.filter(name='invalid').annotate(repaired=functions.MakeValid('poly')).first() self.assertIs(invalid.repaired.valid, True) self.assertEqual(invalid.repaired, fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))', srid=invalid.poly.srid)) @skipUnlessDBFeature("has_MemSize_function") def test_memsize(self): ptown = City.objects.annotate(size=functions.MemSize('point')).get(name='Pueblo') self.assertTrue(20 <= ptown.size <= 40) # Exact value may depend on PostGIS version @skipUnlessDBFeature("has_NumGeom_function") def test_num_geom(self): # Both 'countries' only have two geometries. for c in Country.objects.annotate(num_geom=functions.NumGeometries('mpoly')): self.assertEqual(2, c.num_geom) qs = City.objects.filter(point__isnull=False).annotate(num_geom=functions.NumGeometries('point')) for city in qs: # Oracle and PostGIS return 1 for the number of geometries on # non-collections, whereas MySQL returns None. if mysql: self.assertIsNone(city.num_geom) else: self.assertEqual(1, city.num_geom) @skipUnlessDBFeature("has_NumPoint_function") def test_num_points(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name='Foo', line=LineString(coords)) qs = Track.objects.annotate(num_points=functions.NumPoints('line')) self.assertEqual(qs.first().num_points, 2) mpoly_qs = Country.objects.annotate(num_points=functions.NumPoints('mpoly')) if not connection.features.supports_num_points_poly: for c in mpoly_qs: self.assertIsNone(c.num_points) return for c in mpoly_qs: self.assertEqual(c.mpoly.num_points, c.num_points) for c in City.objects.annotate(num_points=functions.NumPoints('point')): self.assertEqual(c.num_points, 1) @skipUnlessDBFeature("has_PointOnSurface_function") def test_point_on_surface(self): qs = Country.objects.annotate(point_on_surface=functions.PointOnSurface('mpoly')) for country in qs: self.assertTrue(country.mpoly.intersection(country.point_on_surface)) @skipUnlessDBFeature("has_Reverse_function") def test_reverse_geom(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name='Foo', line=LineString(coords)) track = Track.objects.annotate(reverse_geom=functions.Reverse('line')).get(name='Foo') coords.reverse() self.assertEqual(tuple(coords), track.reverse_geom.coords) @skipUnlessDBFeature("has_Scale_function") def test_scale(self): xfac, yfac = 2, 3 tol = 5 # The low precision tolerance is for SpatiaLite qs = Country.objects.annotate(scaled=functions.Scale('mpoly', xfac, yfac)) for country in qs: for p1, p2 in zip(country.mpoly, country.scaled): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): self.assertAlmostEqual(c1[0] * xfac, c2[0], tol) self.assertAlmostEqual(c1[1] * yfac, c2[1], tol) # Test float/Decimal values qs = Country.objects.annotate(scaled=functions.Scale('mpoly', 1.5, Decimal('2.5'))) self.assertGreater(qs[0].scaled.area, qs[0].mpoly.area) @skipUnlessDBFeature("has_SnapToGrid_function") def test_snap_to_grid(self): # Let's try and break snap_to_grid() with bad combinations of arguments. for bad_args in ((), range(3), range(5)): with self.assertRaises(ValueError): Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args)) for bad_args in (('1.0',), (1.0, None), tuple(map(str, range(4)))): with self.assertRaises(TypeError): Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args)) # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org # from the world borders dataset he provides. wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,' '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,' '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,' '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,' '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,' '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,' '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,' '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))') Country.objects.create(name='San Marino', mpoly=fromstr(wkt)) # Because floating-point arithmetic isn't exact, we set a tolerance # to pass into GEOS `equals_exact`. tol = 0.000000001 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))') self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid('mpoly', 0.1) ).get(name='San Marino').snap, tol ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))') self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid('mpoly', 0.05, 0.23) ).get(name='San Marino').snap, tol ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( 'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))' ) self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid('mpoly', 0.05, 0.23, 0.5, 0.17) ).get(name='San Marino').snap, tol ) ) @skipUnlessDBFeature("has_SymDifference_function") def test_sym_difference(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(sym_difference=functions.SymDifference('mpoly', geom)) # Oracle does something screwy with the Texas geometry. if oracle: qs = qs.exclude(name='Texas') for country in qs: self.assertTrue(country.mpoly.sym_difference(geom).equals(country.sym_difference)) @skipUnlessDBFeature("has_Transform_function") def test_transform(self): # Pre-transformed points for Houston and Pueblo. ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774) prec = 3 # Precision is low due to version variations in PROJ and GDAL. # Asserting the result of the transform operation with the values in # the pre-transformed points. h = City.objects.annotate(pt=functions.Transform('point', ptown.srid)).get(name='Pueblo') self.assertEqual(2774, h.pt.srid) self.assertAlmostEqual(ptown.x, h.pt.x, prec) self.assertAlmostEqual(ptown.y, h.pt.y, prec) @skipUnlessDBFeature("has_Translate_function") def test_translate(self): xfac, yfac = 5, -23 qs = Country.objects.annotate(translated=functions.Translate('mpoly', xfac, yfac)) for c in qs: for p1, p2 in zip(c.mpoly, c.translated): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): # The low precision is for SpatiaLite self.assertAlmostEqual(c1[0] + xfac, c2[0], 5) self.assertAlmostEqual(c1[1] + yfac, c2[1], 5) # Some combined function tests @skipUnlessDBFeature( "has_Difference_function", "has_Intersection_function", "has_SymDifference_function", "has_Union_function") def test_diff_intersection_union(self): geom = Point(5, 23, srid=4326) qs = Country.objects.all().annotate( difference=functions.Difference('mpoly', geom), sym_difference=functions.SymDifference('mpoly', geom), union=functions.Union('mpoly', geom), intersection=functions.Intersection('mpoly', geom), ) if oracle: # Should be able to execute the queries; however, they won't be the same # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or # SpatiaLite). return for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.difference)) if not (spatialite or mysql): self.assertEqual(c.mpoly.intersection(geom), c.intersection) self.assertTrue(c.mpoly.sym_difference(geom).equals(c.sym_difference)) self.assertTrue(c.mpoly.union(geom).equals(c.union)) @skipUnlessDBFeature("has_Union_function") def test_union(self): """Union with all combinations of geometries/geometry fields.""" geom = Point(-95.363151, 29.763374, srid=4326) union = City.objects.annotate(union=functions.Union('point', geom)).get(name='Dallas').union expected = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)', srid=4326) self.assertTrue(expected.equals(union)) union = City.objects.annotate(union=functions.Union(geom, 'point')).get(name='Dallas').union self.assertTrue(expected.equals(union)) union = City.objects.annotate(union=functions.Union('point', 'point')).get(name='Dallas').union expected = GEOSGeometry('POINT(-96.801611 32.782057)', srid=4326) self.assertTrue(expected.equals(union)) union = City.objects.annotate(union=functions.Union(geom, geom)).get(name='Dallas').union self.assertTrue(geom.equals(union)) @skipUnlessDBFeature("has_Union_function", "has_Transform_function") def test_union_mixed_srid(self): """The result SRID depends on the order of parameters.""" geom = Point(61.42915, 55.15402, srid=4326) geom_3857 = geom.transform(3857, clone=True) tol = 0.001 for city in City.objects.annotate(union=functions.Union('point', geom_3857)): expected = city.point | geom self.assertTrue(city.union.equals_exact(expected, tol)) self.assertEqual(city.union.srid, 4326) for city in City.objects.annotate(union=functions.Union(geom_3857, 'point')): expected = geom_3857 | city.point.transform(3857, clone=True) self.assertTrue(expected.equals_exact(city.union, tol)) self.assertEqual(city.union.srid, 3857) def test_argument_validation(self): with self.assertRaisesMessage(ValueError, 'SRID is required for all geometries.'): City.objects.annotate(geo=functions.GeoFunc(Point(1, 1))) msg = 'GeoFunc function requires a GeometryField in position 1, got CharField.' with self.assertRaisesMessage(TypeError, msg): City.objects.annotate(geo=functions.GeoFunc('name')) msg = 'GeoFunc function requires a geometric argument in position 1.' with self.assertRaisesMessage(TypeError, msg): City.objects.annotate(union=functions.GeoFunc(1, 'point')).get(name='Dallas')
4c0d17cc0be866a26ccc565bb786818406f635e274e506f7ef83cae6fcf239e2
import tempfile import unittest from io import StringIO from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union, functions from django.contrib.gis.geos import ( GeometryCollection, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import NotSupportedError, connection from django.test import TestCase, skipUnlessDBFeature from ..utils import ( mysql, no_oracle, oracle, postgis, skipUnlessGISLookup, spatialite, ) from .models import ( City, Country, Feature, MinusOneSRID, NonConcreteModel, PennsylvaniaCity, State, Track, ) class GeoModelTest(TestCase): fixtures = ['initial'] def test_fixtures(self): "Testing geographic model initialization from fixtures." # Ensuring that data was loaded from initial data fixtures. self.assertEqual(2, Country.objects.count()) self.assertEqual(8, City.objects.count()) self.assertEqual(2, State.objects.count()) def test_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." # Testing on a Point pnt = Point(0, 0) nullcity = City(name='NullCity', point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: with self.assertRaisesMessage(TypeError, 'Cannot set'): nullcity.point = bad # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name='NullCity').point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual(Point(23, 5, srid=4326), City.objects.get(name='NullCity').point) nullcity.save() self.assertEqual(Point(23, 5, srid=4326), City.objects.get(name='NullCity').point) nullcity.delete() # Testing on a Polygon shell = LinearRing((0, 0), (0, 90), (100, 90), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') self.assertEqual(ply, ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertIsInstance(ns.poly.srs, gdal.SpatialReference) self.assertEqual('WGS 84', ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual(ply, State.objects.get(name='NullState').poly) ns.delete() @skipUnlessDBFeature("supports_transform") def test_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." # San Antonio in 'WGS84' (SRID 4326) sa_4326 = 'POINT (-98.493183 29.424170)' wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857) other_srid_pnt = wgs_pnt.transform(3857, clone=True) # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. if oracle: tx = Country.objects.get(mpoly__contains=other_srid_pnt) else: tx = Country.objects.get(mpoly__intersects=other_srid_pnt) self.assertEqual('Texas', tx.name) # Creating San Antonio. Remember the Alamo. sa = City.objects.create(name='San Antonio', point=other_srid_pnt) # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name='San Antonio') self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual(-1, m1.geom.srid) def test_createnull(self): "Testing creating a model instance and the geometry being None" c = City() self.assertIsNone(c.point) def test_geometryfield(self): "Testing the general GeometryField." Feature(name='Point', geom=Point(1, 1)).save() Feature(name='LineString', geom=LineString((0, 0), (1, 1), (5, 5))).save() Feature(name='Polygon', geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))).save() Feature(name='GeometryCollection', geom=GeometryCollection(Point(2, 2), LineString((0, 0), (2, 2)), Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))).save() f_1 = Feature.objects.get(name='Point') self.assertIsInstance(f_1.geom, Point) self.assertEqual((1.0, 1.0), f_1.geom.tuple) f_2 = Feature.objects.get(name='LineString') self.assertIsInstance(f_2.geom, LineString) self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple) f_3 = Feature.objects.get(name='Polygon') self.assertIsInstance(f_3.geom, Polygon) f_4 = Feature.objects.get(name='GeometryCollection') self.assertIsInstance(f_4.geom, GeometryCollection) self.assertEqual(f_3.geom, f_4.geom[2]) # TODO: fix on Oracle: ORA-22901: cannot compare nested table or VARRAY or # LOB attributes of an object type. @no_oracle @skipUnlessDBFeature("supports_transform") def test_inherited_geofields(self): "Database functions on inherited Geometry fields." # Creating a Pennsylvanian city. PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)') # All transformation SQL will need to be performed on the # _parent_ table. qs = PennsylvaniaCity.objects.annotate(new_point=functions.Transform('point', srid=32128)) self.assertEqual(1, qs.count()) for pc in qs: self.assertEqual(32128, pc.new_point.srid) def test_raw_sql_query(self): "Testing raw SQL query." cities1 = City.objects.all() point_select = connection.ops.select % 'point' cities2 = list(City.objects.raw( 'select id, name, %s as point from geoapp_city' % point_select )) self.assertEqual(len(cities1), len(cities2)) with self.assertNumQueries(0): # Ensure point isn't deferred. self.assertIsInstance(cities2[0].point, Point) def test_dumpdata_loaddata_cycle(self): """ Test a dumpdata/loaddata cycle with geographic data. """ out = StringIO() original_data = list(City.objects.all().order_by('name')) call_command('dumpdata', 'geoapp.City', stdout=out) result = out.getvalue() houston = City.objects.get(name='Houston') self.assertIn('"point": "%s"' % houston.point.ewkt, result) # Reload now dumped data with tempfile.NamedTemporaryFile(mode='w', suffix='.json') as tmp: tmp.write(result) tmp.seek(0) call_command('loaddata', tmp.name, verbosity=0) self.assertEqual(original_data, list(City.objects.all().order_by('name'))) @skipUnlessDBFeature("supports_empty_geometries") def test_empty_geometries(self): geometry_classes = [ Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection, ] for klass in geometry_classes: g = klass(srid=4326) feature = Feature.objects.create(name='Empty %s' % klass.__name__, geom=g) feature.refresh_from_db() if klass is LinearRing: # LinearRing isn't representable in WKB, so GEOSGeomtry.wkb # uses LineString instead. g = LineString(srid=4326) self.assertEqual(feature.geom, g) self.assertEqual(feature.geom.srid, g.srid) class GeoLookupTest(TestCase): fixtures = ['initial'] def test_disjoint_lookup(self): "Testing the `disjoint` lookup type." if (connection.vendor == 'mysql' and not connection.mysql_is_mariadb and connection.mysql_version < (8, 0, 0)): raise unittest.SkipTest('MySQL < 8 gives different results.') ptown = City.objects.get(name='Pueblo') qs1 = City.objects.filter(point__disjoint=ptown.point) self.assertEqual(7, qs1.count()) qs2 = State.objects.filter(poly__disjoint=ptown.point) self.assertEqual(1, qs2.count()) self.assertEqual('Kansas', qs2[0].name) def test_contains_contained_lookups(self): "Testing the 'contained', 'contains', and 'bbcontains' lookup types." # Getting Texas, yes we were a country -- once ;) texas = Country.objects.get(name='Texas') # Seeing what cities are in Texas, should get Houston and Dallas, # and Oklahoma City because 'contained' only checks on the # _bounding box_ of the Geometries. if connection.features.supports_contained_lookup: qs = City.objects.filter(point__contained=texas.mpoly) self.assertEqual(3, qs.count()) cities = ['Houston', 'Dallas', 'Oklahoma City'] for c in qs: self.assertIn(c.name, cities) # Pulling out some cities. houston = City.objects.get(name='Houston') wellington = City.objects.get(name='Wellington') pueblo = City.objects.get(name='Pueblo') okcity = City.objects.get(name='Oklahoma City') lawrence = City.objects.get(name='Lawrence') # Now testing contains on the countries using the points for # Houston and Wellington. tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX self.assertEqual('Texas', tx.name) self.assertEqual('New Zealand', nz.name) # Testing `contains` on the states using the point for Lawrence. ks = State.objects.get(poly__contains=lawrence.point) self.assertEqual('Kansas', ks.name) # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas) # are not contained in Texas or New Zealand. self.assertEqual(len(Country.objects.filter(mpoly__contains=pueblo.point)), 0) # Query w/GEOSGeometry object self.assertEqual(len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0) # Query w/WKT # OK City is contained w/in bounding box of Texas. if connection.features.supports_bbcontains_lookup: qs = Country.objects.filter(mpoly__bbcontains=okcity.point) self.assertEqual(1, len(qs)) self.assertEqual('Texas', qs[0].name) @skipUnlessDBFeature("supports_crosses_lookup") def test_crosses_lookup(self): Track.objects.create( name='Line1', line=LineString([(-95, 29), (-60, 0)]) ) self.assertEqual( Track.objects.filter(line__crosses=LineString([(-95, 0), (-60, 29)])).count(), 1 ) self.assertEqual( Track.objects.filter(line__crosses=LineString([(-95, 30), (0, 30)])).count(), 0 ) @skipUnlessDBFeature("supports_isvalid_lookup") def test_isvalid_lookup(self): invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))') State.objects.create(name='invalid', poly=invalid_geom) qs = State.objects.all() if oracle or (mysql and connection.mysql_version < (8, 0, 0)): # Kansas has adjacent vertices with distance 6.99244813842e-12 # which is smaller than the default Oracle tolerance. # It's invalid on MySQL < 8 also. qs = qs.exclude(name='Kansas') self.assertEqual(State.objects.filter(name='Kansas', poly__isvalid=False).count(), 1) self.assertEqual(qs.filter(poly__isvalid=False).count(), 1) self.assertEqual(qs.filter(poly__isvalid=True).count(), qs.count() - 1) @skipUnlessDBFeature("supports_left_right_lookups") def test_left_right_lookups(self): "Testing the 'left' and 'right' lookup types." # Left: A << B => true if xmax(A) < xmin(B) # Right: A >> B => true if xmin(A) > xmax(B) # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source. # Getting the borders for Colorado & Kansas co_border = State.objects.get(name='Colorado').poly ks_border = State.objects.get(name='Kansas').poly # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. # These cities should be strictly to the right of the CO border. cities = ['Houston', 'Dallas', 'Oklahoma City', 'Lawrence', 'Chicago', 'Wellington'] qs = City.objects.filter(point__right=co_border) self.assertEqual(6, len(qs)) for c in qs: self.assertIn(c.name, cities) # These cities should be strictly to the right of the KS border. cities = ['Chicago', 'Wellington'] qs = City.objects.filter(point__right=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. vic = City.objects.get(point__left=co_border) self.assertEqual('Victoria', vic.name) cities = ['Pueblo', 'Victoria'] qs = City.objects.filter(point__left=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) @skipUnlessGISLookup("strictly_above", "strictly_below") def test_strictly_above_below_lookups(self): dallas = City.objects.get(name='Dallas') self.assertQuerysetEqual( City.objects.filter(point__strictly_above=dallas.point).order_by('name'), ['Chicago', 'Lawrence', 'Oklahoma City', 'Pueblo', 'Victoria'], lambda b: b.name ) self.assertQuerysetEqual( City.objects.filter(point__strictly_below=dallas.point).order_by('name'), ['Houston', 'Wellington'], lambda b: b.name ) def test_equals_lookups(self): "Testing the 'same_as' and 'equals' lookup types." pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326) c1 = City.objects.get(point=pnt) c2 = City.objects.get(point__same_as=pnt) c3 = City.objects.get(point__equals=pnt) for c in [c1, c2, c3]: self.assertEqual('Houston', c.name) @skipUnlessDBFeature("supports_null_geometries") def test_null_geometries(self): "Testing NULL geometry support, and the `isnull` lookup type." # Creating a state with a NULL boundary. State.objects.create(name='Puerto Rico') # Querying for both NULL and Non-NULL values. nullqs = State.objects.filter(poly__isnull=True) validqs = State.objects.filter(poly__isnull=False) # Puerto Rico should be NULL (it's a commonwealth unincorporated territory) self.assertEqual(1, len(nullqs)) self.assertEqual('Puerto Rico', nullqs[0].name) # GeometryField=None is an alias for __isnull=True. self.assertCountEqual(State.objects.filter(poly=None), nullqs) self.assertCountEqual(State.objects.exclude(poly=None), validqs) # The valid states should be Colorado & Kansas self.assertEqual(2, len(validqs)) state_names = [s.name for s in validqs] self.assertIn('Colorado', state_names) self.assertIn('Kansas', state_names) # Saving another commonwealth w/a NULL geometry. nmi = State.objects.create(name='Northern Mariana Islands', poly=None) self.assertIsNone(nmi.poly) # Assigning a geometry and saving -- then UPDATE back to NULL. nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))' nmi.save() State.objects.filter(name='Northern Mariana Islands').update(poly=None) self.assertIsNone(State.objects.get(name='Northern Mariana Islands').poly) @skipUnlessDBFeature('supports_null_geometries', 'supports_crosses_lookup', 'supports_relate_lookup') def test_null_geometries_excluded_in_lookups(self): """NULL features are excluded in spatial lookup functions.""" null = State.objects.create(name='NULL', poly=None) queries = [ ('equals', Point(1, 1)), ('disjoint', Point(1, 1)), ('touches', Point(1, 1)), ('crosses', LineString((0, 0), (1, 1), (5, 5))), ('within', Point(1, 1)), ('overlaps', LineString((0, 0), (1, 1), (5, 5))), ('contains', LineString((0, 0), (1, 1), (5, 5))), ('intersects', LineString((0, 0), (1, 1), (5, 5))), ('relate', (Point(1, 1), 'T*T***FF*')), ('same_as', Point(1, 1)), ('exact', Point(1, 1)), ('coveredby', Point(1, 1)), ('covers', Point(1, 1)), ] for lookup, geom in queries: with self.subTest(lookup=lookup): self.assertNotIn(null, State.objects.filter(**{'poly__%s' % lookup: geom})) @skipUnlessDBFeature("supports_relate_lookup") def test_relate_lookup(self): "Testing the 'relate' lookup type." # To make things more interesting, we will have our Texas reference point in # different SRIDs. pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847) pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326) # Not passing in a geometry as first param raises a TypeError when # initializing the QuerySet. with self.assertRaises(ValueError): Country.objects.filter(mpoly__relate=(23, 'foo')) # Making sure the right exception is raised for the given # bad arguments. for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]: qs = Country.objects.filter(mpoly__relate=bad_args) with self.assertRaises(e): qs.count() # Relate works differently for the different backends. if postgis or spatialite: contains_mask = 'T*T***FF*' within_mask = 'T*F**F***' intersects_mask = 'T********' elif oracle: contains_mask = 'contains' within_mask = 'inside' # TODO: This is not quite the same as the PostGIS mask above intersects_mask = 'overlapbdyintersect' # Testing contains relation mask. self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name) # Testing within relation mask. ks = State.objects.get(name='Kansas') self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name) # Testing intersection relation mask. if not oracle: self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name) self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name) self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name) # With a complex geometry expression mask = 'anyinteract' if oracle else within_mask self.assertFalse(City.objects.exclude(point__relate=(functions.Union('point', 'point'), mask))) def test_gis_lookups_with_complex_expressions(self): multiple_arg_lookups = {'dwithin', 'relate'} # These lookups are tested elsewhere. lookups = connection.ops.gis_operators.keys() - multiple_arg_lookups self.assertTrue(lookups, 'No lookups found') for lookup in lookups: with self.subTest(lookup): City.objects.filter(**{'point__' + lookup: functions.Union('point', 'point')}).exists() class GeoQuerySetTest(TestCase): # TODO: GeoQuerySet is removed, organize these test better. fixtures = ['initial'] @skipUnlessDBFeature("supports_extent_aggr") def test_extent(self): """ Testing the `Extent` aggregate. """ # Reference query: # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');` # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203) expected = (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820) qs = City.objects.filter(name__in=('Houston', 'Dallas')) extent = qs.aggregate(Extent('point'))['point__extent'] for val, exp in zip(extent, expected): self.assertAlmostEqual(exp, val, 4) self.assertIsNone(City.objects.filter(name=('Smalltown')).aggregate(Extent('point'))['point__extent']) @skipUnlessDBFeature("supports_extent_aggr") def test_extent_with_limit(self): """ Testing if extent supports limit. """ extent1 = City.objects.all().aggregate(Extent('point'))['point__extent'] extent2 = City.objects.all()[:3].aggregate(Extent('point'))['point__extent'] self.assertNotEqual(extent1, extent2) def test_make_line(self): """ Testing the `MakeLine` aggregate. """ if not connection.features.supports_make_line_aggr: with self.assertRaises(NotSupportedError): City.objects.all().aggregate(MakeLine('point')) return # MakeLine on an inappropriate field returns simply None self.assertIsNone(State.objects.aggregate(MakeLine('poly'))['poly__makeline']) # Reference query: # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; ref_line = GEOSGeometry( 'LINESTRING(-95.363151 29.763374,-96.801611 32.782057,' '-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,' '-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)', srid=4326 ) # We check for equality with a tolerance of 10e-5 which is a lower bound # of the precisions of ref_line coordinates line = City.objects.aggregate(MakeLine('point'))['point__makeline'] self.assertTrue( ref_line.equals_exact(line, tolerance=10e-5), "%s != %s" % (ref_line, line) ) @skipUnlessDBFeature('supports_union_aggr') def test_unionagg(self): """ Testing the `Union` aggregate. """ tx = Country.objects.get(name='Texas').mpoly # Houston, Dallas -- Ordering may differ depending on backend or GEOS version. union = GEOSGeometry('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)') qs = City.objects.filter(point__within=tx) with self.assertRaises(ValueError): qs.aggregate(Union('name')) # Using `field_name` keyword argument in one query and specifying an # order in the other (which should not be used because this is # an aggregate method on a spatial column) u1 = qs.aggregate(Union('point'))['point__union'] u2 = qs.order_by('name').aggregate(Union('point'))['point__union'] self.assertTrue(union.equals(u1)) self.assertTrue(union.equals(u2)) qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery) (#14483). """ tex_cities = City.objects.filter( point__within=Country.objects.filter(name='Texas').values('mpoly')).order_by('name') self.assertEqual(list(tex_cities.values_list('name', flat=True)), ['Dallas', 'Houston']) def test_non_concrete_field(self): NonConcreteModel.objects.create(point=Point(0, 0), name='name') list(NonConcreteModel.objects.all()) def test_values_srid(self): for c, v in zip(City.objects.all(), City.objects.values()): self.assertEqual(c.point.srid, v['point'].srid)
f5a75afb79c12481efc0a42d3b515bb85ab972db1be25394dcce3192649a6c46
from xml.dom import minidom from django.conf import settings from django.contrib.sites.models import Site from django.test import TestCase, modify_settings, override_settings from .models import City @modify_settings(INSTALLED_APPS={'append': 'django.contrib.sites'}) @override_settings(ROOT_URLCONF='gis_tests.geoapp.urls') class GeoFeedTest(TestCase): fixtures = ['initial'] @classmethod def setUpTestData(cls): Site(id=settings.SITE_ID, domain="example.com", name="example.com").save() def assertChildNodes(self, elem, expected): "Taken from syndication/tests.py." actual = {n.nodeName for n in elem.childNodes} expected = set(expected) self.assertEqual(actual, expected) def test_geofeed_rss(self): "Tests geographic feeds using GeoRSS over RSSv2." # Uses `GEOSGeometry` in `item_geometry` doc1 = minidom.parseString(self.client.get('/feeds/rss1/').content) # Uses a 2-tuple in `item_geometry` doc2 = minidom.parseString(self.client.get('/feeds/rss2/').content) feed1, feed2 = doc1.firstChild, doc2.firstChild # Making sure the box got added to the second GeoRSS feed. self.assertChildNodes(feed2.getElementsByTagName('channel')[0], ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'georss:box', 'atom:link'] ) # Incrementing through the feeds. for feed in [feed1, feed2]: # Ensuring the georss namespace was added to the <rss> element. self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len(items), City.objects.count()) # Ensuring the georss element was added to each item in the feed. for item in items: self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'georss:point']) def test_geofeed_atom(self): "Testing geographic feeds using GeoRSS over Atom." doc1 = minidom.parseString(self.client.get('/feeds/atom1/').content) doc2 = minidom.parseString(self.client.get('/feeds/atom2/').content) feed1, feed2 = doc1.firstChild, doc2.firstChild # Making sure the box got added to the second GeoRSS feed. self.assertChildNodes(feed2, ['title', 'link', 'id', 'updated', 'entry', 'georss:box']) for feed in [feed1, feed2]: # Ensuring the georsss namespace was added to the <feed> element. self.assertEqual(feed.getAttribute('xmlns:georss'), 'http://www.georss.org/georss') entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), City.objects.count()) # Ensuring the georss element was added to each entry in the feed. for entry in entries: self.assertChildNodes(entry, ['title', 'link', 'id', 'summary', 'georss:point']) def test_geofeed_w3c(self): "Testing geographic feeds using W3C Geo." doc = minidom.parseString(self.client.get('/feeds/w3cgeo1/').content) feed = doc.firstChild # Ensuring the geo namespace was added to the <feed> element. self.assertEqual(feed.getAttribute('xmlns:geo'), 'http://www.w3.org/2003/01/geo/wgs84_pos#') chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertEqual(len(items), City.objects.count()) # Ensuring the geo:lat and geo:lon element was added to each item in the feed. for item in items: self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'geo:lat', 'geo:lon']) # Boxes and Polygons aren't allowed in W3C Geo feeds. with self.assertRaises(ValueError): # Box in <channel> self.client.get('/feeds/w3cgeo2/') with self.assertRaises(ValueError): # Polygons in <entry> self.client.get('/feeds/w3cgeo3/')
3465defe8bae677523173d2571cc32d3a1f2d9ddcaf4f3943380702cdc59d88b
from django.contrib.gis.sitemaps import KMLSitemap, KMZSitemap from .models import City, Country sitemaps = { 'kml': KMLSitemap([City, Country]), 'kmz': KMZSitemap([City, Country]), }
132eff815e6729b6c07c275452de355d524ab5e24666b2d32be5215429427da4
from django.contrib.gis import views as gis_views from django.contrib.gis.sitemaps import views as gis_sitemap_views from django.contrib.sitemaps import views as sitemap_views from django.urls import path from .feeds import feed_dict from .sitemaps import sitemaps urlpatterns = [ path('feeds/<path:url>/', gis_views.feed, {'feed_dict': feed_dict}), ] urlpatterns += [ path('sitemaps/<section>.xml', sitemap_views.sitemap, {'sitemaps': sitemaps}), ] urlpatterns += [ path( 'sitemaps/kml/<label>/<model>/<field_name>.kml', gis_sitemap_views.kml, name='django.contrib.gis.sitemaps.views.kml'), path( 'sitemaps/kml/<label>/<<model>/<field_name>.kmz', gis_sitemap_views.kmz, name='django.contrib.gis.sitemaps.views.kmz'), ]
5fbe21f86942600b04dccb2b3bc8d2baf7cc524f7d2ab75909f67313291b2449
from datetime import datetime from django.contrib.gis.db.models import Extent from django.contrib.gis.shortcuts import render_to_kmz from django.db.models import Count, Min from django.test import TestCase, skipUnlessDBFeature from ..utils import no_oracle from .models import City, PennsylvaniaCity, State, Truth class GeoRegressionTests(TestCase): fixtures = ['initial'] def test_update(self): "Testing QuerySet.update() (#10411)." pueblo = City.objects.get(name='Pueblo') bak = pueblo.point.clone() pueblo.point.y += 0.005 pueblo.point.x += 0.005 City.objects.filter(name='Pueblo').update(point=pueblo.point) pueblo.refresh_from_db() self.assertAlmostEqual(bak.y + 0.005, pueblo.point.y, 6) self.assertAlmostEqual(bak.x + 0.005, pueblo.point.x, 6) City.objects.filter(name='Pueblo').update(point=bak) pueblo.refresh_from_db() self.assertAlmostEqual(bak.y, pueblo.point.y, 6) self.assertAlmostEqual(bak.x, pueblo.point.x, 6) def test_kmz(self): "Testing `render_to_kmz` with non-ASCII data. See #11624." name = "Åland Islands" places = [{ 'name': name, 'description': name, 'kml': '<Point><coordinates>5.0,23.0</coordinates></Point>' }] render_to_kmz('gis/kml/placemarks.kml', {'places': places}) @skipUnlessDBFeature("supports_extent_aggr") def test_extent(self): "Testing `extent` on a table with a single point. See #11827." pnt = City.objects.get(name='Pueblo').point ref_ext = (pnt.x, pnt.y, pnt.x, pnt.y) extent = City.objects.filter(name='Pueblo').aggregate(Extent('point'))['point__extent'] for ref_val, val in zip(ref_ext, extent): self.assertAlmostEqual(ref_val, val, 4) def test_unicode_date(self): "Testing dates are converted properly, even on SpatiaLite. See #16408." founded = datetime(1857, 5, 23) PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)', founded=founded) self.assertEqual(founded, PennsylvaniaCity.objects.datetimes('founded', 'day')[0]) self.assertEqual(founded, PennsylvaniaCity.objects.aggregate(Min('founded'))['founded__min']) def test_empty_count(self): "Testing that PostGISAdapter.__eq__ does check empty strings. See #13670." # contrived example, but need a geo lookup paired with an id__in lookup pueblo = City.objects.get(name='Pueblo') state = State.objects.filter(poly__contains=pueblo.point) cities_within_state = City.objects.filter(id__in=state) # .count() should not throw TypeError in __eq__ self.assertEqual(cities_within_state.count(), 1) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test_defer_or_only_with_annotate(self): "Regression for #16409. Make sure defer() and only() work with annotate()" self.assertIsInstance(list(City.objects.annotate(Count('point')).defer('name')), list) self.assertIsInstance(list(City.objects.annotate(Count('point')).only('name')), list) def test_boolean_conversion(self): "Testing Boolean value conversion with the spatial backend, see #15169." t1 = Truth.objects.create(val=True) t2 = Truth.objects.create(val=False) val1 = Truth.objects.get(pk=t1.pk).val val2 = Truth.objects.get(pk=t2.pk).val # verify types -- shouldn't be 0/1 self.assertIsInstance(val1, bool) self.assertIsInstance(val2, bool) # verify values self.assertIs(val1, True) self.assertIs(val2, False)
91d31534bb9e6cf7701244f716dbc268a95ed34ebaf816df0d90fd2c5aae435e
import zipfile from io import BytesIO from xml.dom import minidom from django.conf import settings from django.contrib.sites.models import Site from django.test import TestCase, modify_settings, override_settings from .models import City, Country @modify_settings(INSTALLED_APPS={'append': ['django.contrib.sites', 'django.contrib.sitemaps']}) @override_settings(ROOT_URLCONF='gis_tests.geoapp.urls') class GeoSitemapTest(TestCase): @classmethod def setUpTestData(cls): Site(id=settings.SITE_ID, domain="example.com", name="example.com").save() def assertChildNodes(self, elem, expected): "Taken from syndication/tests.py." actual = {n.nodeName for n in elem.childNodes} expected = set(expected) self.assertEqual(actual, expected) def test_geositemap_kml(self): "Tests KML/KMZ geographic sitemaps." for kml_type in ('kml', 'kmz'): doc = minidom.parseString(self.client.get('/sitemaps/%s.xml' % kml_type).content) # Ensuring the right sitemaps namespace is present. urlset = doc.firstChild self.assertEqual(urlset.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9') urls = urlset.getElementsByTagName('url') self.assertEqual(2, len(urls)) # Should only be 2 sitemaps. for url in urls: self.assertChildNodes(url, ['loc']) # Getting the relative URL since we don't have a real site. kml_url = url.getElementsByTagName('loc')[0].childNodes[0].data.split('http://example.com')[1] if kml_type == 'kml': kml_doc = minidom.parseString(self.client.get(kml_url).content) elif kml_type == 'kmz': # Have to decompress KMZ before parsing. buf = BytesIO(self.client.get(kml_url).content) with zipfile.ZipFile(buf) as zf: self.assertEqual(1, len(zf.filelist)) self.assertEqual('doc.kml', zf.filelist[0].filename) kml_doc = minidom.parseString(zf.read('doc.kml')) # Ensuring the correct number of placemarks are in the KML doc. if 'city' in kml_url: model = City elif 'country' in kml_url: model = Country self.assertEqual(model.objects.count(), len(kml_doc.getElementsByTagName('Placemark')))
d6fc804a839cad61f58e913e146a310309a1bf980e68b3f41c925749139fac24
""" Tests for geography support in PostGIS """ import os from unittest import skipIf, skipUnless from django.contrib.gis.db import models from django.contrib.gis.db.models.functions import Area, Distance from django.contrib.gis.measure import D from django.db import NotSupportedError, connection from django.db.models.functions import Cast from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from ..utils import FuncTestMixin, oracle, postgis, spatialite from .models import City, County, Zipcode class GeographyTest(TestCase): fixtures = ['initial'] def test01_fixture_load(self): "Ensure geography features loaded properly." self.assertEqual(8, City.objects.count()) @skipIf(spatialite, "SpatiaLite doesn't support distance lookups with Distance objects.") @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic") def test02_distance_lookup(self): "Testing distance lookup support on non-point geography fields." z = Zipcode.objects.get(code='77002') cities1 = list(City.objects .filter(point__distance_lte=(z.poly, D(mi=500))) .order_by('name') .values_list('name', flat=True)) cities2 = list(City.objects .filter(point__dwithin=(z.poly, D(mi=500))) .order_by('name') .values_list('name', flat=True)) for cities in [cities1, cities2]: self.assertEqual(['Dallas', 'Houston', 'Oklahoma City'], cities) @skipUnless(postgis, "This is a PostGIS-specific test") def test04_invalid_operators_functions(self): "Ensuring exceptions are raised for operators & functions invalid on geography fields." # Only a subset of the geometry functions & operator are available # to PostGIS geography types. For more information, visit: # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions z = Zipcode.objects.get(code='77002') # ST_Within not available. with self.assertRaises(ValueError): City.objects.filter(point__within=z.poly).count() # `@` operator not available. with self.assertRaises(ValueError): City.objects.filter(point__contained=z.poly).count() # Regression test for #14060, `~=` was never really implemented for PostGIS. htown = City.objects.get(name='Houston') with self.assertRaises(ValueError): City.objects.get(point__exact=htown.point) def test05_geography_layermapping(self): "Testing LayerMapping support on models with geography fields." # There is a similar test in `layermap` that uses the same data set, # but the County model here is a bit different. from django.contrib.gis.utils import LayerMapping # Getting the shapefile and mapping dictionary. shp_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data')) co_shp = os.path.join(shp_path, 'counties', 'counties.shp') co_mapping = { 'name': 'Name', 'state': 'State', 'mpoly': 'MULTIPOLYGON', } # Reference county names, number of polygons, and state names. names = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo'] num_polys = [1, 2, 1, 19, 1] # Number of polygons for each. st_names = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado'] lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique='name') lm.save(silent=True, strict=True) for c, name, num_poly, state in zip(County.objects.order_by('name'), names, num_polys, st_names): self.assertEqual(4326, c.mpoly.srid) self.assertEqual(num_poly, len(c.mpoly)) self.assertEqual(name, c.name) self.assertEqual(state, c.state) class GeographyFunctionTests(FuncTestMixin, TestCase): fixtures = ['initial'] @skipUnlessDBFeature("supports_extent_aggr") def test_cast_aggregate(self): """ Cast a geography to a geometry field for an aggregate function that expects a geometry input. """ if not connection.ops.geography: self.skipTest("This test needs geography support") expected = (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820) res = City.objects.filter( name__in=('Houston', 'Dallas') ).aggregate(extent=models.Extent(Cast('point', models.PointField()))) for val, exp in zip(res['extent'], expected): self.assertAlmostEqual(exp, val, 4) @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic") def test_distance_function(self): """ Testing Distance() support on non-point geography fields. """ if oracle: ref_dists = [0, 4899.68, 8081.30, 9115.15] elif spatialite: # SpatiaLite returns non-zero distance for polygons and points # covered by that polygon. ref_dists = [326.61, 4899.68, 8081.30, 9115.15] else: ref_dists = [0, 4891.20, 8071.64, 9123.95] htown = City.objects.get(name='Houston') qs = Zipcode.objects.annotate( distance=Distance('poly', htown.point), distance2=Distance(htown.point, 'poly'), ) for z, ref in zip(qs, ref_dists): self.assertAlmostEqual(z.distance.m, ref, 2) if postgis: # PostGIS casts geography to geometry when distance2 is calculated. ref_dists = [0, 4899.68, 8081.30, 9115.15] for z, ref in zip(qs, ref_dists): self.assertAlmostEqual(z.distance2.m, ref, 2) if not spatialite: # Distance function combined with a lookup. hzip = Zipcode.objects.get(code='77002') self.assertEqual(qs.get(distance__lte=0), hzip) @skipUnlessDBFeature("has_Area_function", "supports_area_geodetic") def test_geography_area(self): """ Testing that Area calculations work on geography columns. """ # SELECT ST_Area(poly) FROM geogapp_zipcode WHERE code='77002'; z = Zipcode.objects.annotate(area=Area('poly')).get(code='77002') # Round to the nearest thousand as possible values (depending on # the database and geolib) include 5439084, 5439100, 5439101. rounded_value = z.area.sq_m rounded_value -= z.area.sq_m % 1000 self.assertEqual(rounded_value, 5439000) @skipUnlessDBFeature("has_Area_function") @skipIfDBFeature("supports_area_geodetic") def test_geodetic_area_raises_if_not_supported(self): with self.assertRaisesMessage(NotSupportedError, 'Area on geodetic coordinate systems not supported.'): Zipcode.objects.annotate(area=Area('poly')).get(code='77002')
766b84ca1aa101b411b5de030c3f81cf043a6bd2e7768be1ea6198c65552e527
from unittest import skipIf from django.contrib.gis.db.models import fields from django.contrib.gis.geos import MultiPolygon, Polygon from django.core.exceptions import ImproperlyConfigured from django.db import connection, migrations, models from django.db.migrations.migration import Migration from django.db.migrations.state import ProjectState from django.test import ( TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from ..utils import mysql, spatialite try: GeometryColumns = connection.ops.geometry_columns() HAS_GEOMETRY_COLUMNS = True except NotImplementedError: HAS_GEOMETRY_COLUMNS = False class OperationTestCase(TransactionTestCase): available_apps = ['gis_tests.gis_migrations'] def tearDown(self): # Delete table after testing if hasattr(self, 'current_state'): self.apply_operations('gis', self.current_state, [migrations.DeleteModel('Neighborhood')]) super().tearDown() @property def has_spatial_indexes(self): if mysql: with connection.cursor() as cursor: return connection.introspection.supports_spatial_index(cursor, 'gis_neighborhood') return True def get_table_description(self, table): with connection.cursor() as cursor: return connection.introspection.get_table_description(cursor, table) def assertColumnExists(self, table, column): self.assertIn(column, [c.name for c in self.get_table_description(table)]) def assertColumnNotExists(self, table, column): self.assertNotIn(column, [c.name for c in self.get_table_description(table)]) def apply_operations(self, app_label, project_state, operations): migration = Migration('name', app_label) migration.operations = operations with connection.schema_editor() as editor: return migration.apply(project_state, editor) def set_up_test_model(self, force_raster_creation=False): test_fields = [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=100, unique=True)), ('geom', fields.MultiPolygonField(srid=4326)) ] if connection.features.supports_raster or force_raster_creation: test_fields += [('rast', fields.RasterField(srid=4326, null=True))] operations = [migrations.CreateModel('Neighborhood', test_fields)] self.current_state = self.apply_operations('gis', ProjectState(), operations) def assertGeometryColumnsCount(self, expected_count): self.assertEqual( GeometryColumns.objects.filter(**{ '%s__iexact' % GeometryColumns.table_name_col(): 'gis_neighborhood', }).count(), expected_count ) def assertSpatialIndexExists(self, table, column, raster=False): with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) if raster: self.assertTrue(any( 'st_convexhull(%s)' % column in c['definition'] for c in constraints.values() if c['definition'] is not None )) else: self.assertIn([column], [c['columns'] for c in constraints.values()]) def alter_gis_model(self, migration_class, model_name, field_name, blank=False, field_class=None, field_class_kwargs=None): args = [model_name, field_name] if field_class: field_class_kwargs = field_class_kwargs or {'srid': 4326, 'blank': blank} args.append(field_class(**field_class_kwargs)) operation = migration_class(*args) old_state = self.current_state.clone() operation.state_forwards('gis', self.current_state) with connection.schema_editor() as editor: operation.database_forwards('gis', editor, old_state, self.current_state) class OperationTests(OperationTestCase): def setUp(self): super().setUp() self.set_up_test_model() def test_add_geom_field(self): """ Test the AddField operation with a geometry-enabled column. """ self.alter_gis_model(migrations.AddField, 'Neighborhood', 'path', False, fields.LineStringField) self.assertColumnExists('gis_neighborhood', 'path') # Test GeometryColumns when available if HAS_GEOMETRY_COLUMNS: self.assertGeometryColumnsCount(2) # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists('gis_neighborhood', 'path') @skipUnlessDBFeature('supports_raster') def test_add_raster_field(self): """ Test the AddField operation with a raster-enabled column. """ self.alter_gis_model(migrations.AddField, 'Neighborhood', 'heatmap', False, fields.RasterField) self.assertColumnExists('gis_neighborhood', 'heatmap') # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists('gis_neighborhood', 'heatmap', raster=True) def test_add_blank_geom_field(self): """ Should be able to add a GeometryField with blank=True. """ self.alter_gis_model(migrations.AddField, 'Neighborhood', 'path', True, fields.LineStringField) self.assertColumnExists('gis_neighborhood', 'path') # Test GeometryColumns when available if HAS_GEOMETRY_COLUMNS: self.assertGeometryColumnsCount(2) # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists('gis_neighborhood', 'path') @skipUnlessDBFeature('supports_raster') def test_add_blank_raster_field(self): """ Should be able to add a RasterField with blank=True. """ self.alter_gis_model(migrations.AddField, 'Neighborhood', 'heatmap', True, fields.RasterField) self.assertColumnExists('gis_neighborhood', 'heatmap') # Test spatial indices when available if self.has_spatial_indexes: self.assertSpatialIndexExists('gis_neighborhood', 'heatmap', raster=True) def test_remove_geom_field(self): """ Test the RemoveField operation with a geometry-enabled column. """ self.alter_gis_model(migrations.RemoveField, 'Neighborhood', 'geom') self.assertColumnNotExists('gis_neighborhood', 'geom') # Test GeometryColumns when available if HAS_GEOMETRY_COLUMNS: self.assertGeometryColumnsCount(0) @skipUnlessDBFeature('supports_raster') def test_remove_raster_field(self): """ Test the RemoveField operation with a raster-enabled column. """ self.alter_gis_model(migrations.RemoveField, 'Neighborhood', 'rast') self.assertColumnNotExists('gis_neighborhood', 'rast') def test_create_model_spatial_index(self): if not self.has_spatial_indexes: self.skipTest('No support for Spatial indexes') self.assertSpatialIndexExists('gis_neighborhood', 'geom') if connection.features.supports_raster: self.assertSpatialIndexExists('gis_neighborhood', 'rast', raster=True) @skipUnlessDBFeature("supports_3d_storage") @skipIf(spatialite, "Django currently doesn't support altering Spatialite geometry fields") def test_alter_geom_field_dim(self): Neighborhood = self.current_state.apps.get_model('gis', 'Neighborhood') p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) Neighborhood.objects.create(name='TestDim', geom=MultiPolygon(p1, p1)) # Add 3rd dimension. self.alter_gis_model( migrations.AlterField, 'Neighborhood', 'geom', False, fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 3} ) self.assertTrue(Neighborhood.objects.first().geom.hasz) # Rewind to 2 dimensions. self.alter_gis_model( migrations.AlterField, 'Neighborhood', 'geom', False, fields.MultiPolygonField, field_class_kwargs={'srid': 4326, 'dim': 2} ) self.assertFalse(Neighborhood.objects.first().geom.hasz) @skipIfDBFeature('supports_raster') class NoRasterSupportTests(OperationTestCase): def test_create_raster_model_on_db_without_raster_support(self): msg = 'Raster fields require backends with raster support.' with self.assertRaisesMessage(ImproperlyConfigured, msg): self.set_up_test_model(force_raster_creation=True) def test_add_raster_field_on_db_without_raster_support(self): msg = 'Raster fields require backends with raster support.' with self.assertRaisesMessage(ImproperlyConfigured, msg): self.set_up_test_model() self.alter_gis_model( migrations.AddField, 'Neighborhood', 'heatmap', False, fields.RasterField )
a54163607bef6389051a350fa04bf3a837f111678d1389a6d13684acaa6b4f6f
# Copyright (c) 2008-2009 Aryeh Leib Taurog, http://www.aryehleib.com # All rights reserved. # # Modified from original contribution by Aryeh Leib Taurog, which was # released under the New BSD license. import unittest from django.contrib.gis.geos.mutable_list import ListMixin class UserListA(ListMixin): _mytype = tuple def __init__(self, i_list, *args, **kwargs): self._list = self._mytype(i_list) super().__init__(*args, **kwargs) def __len__(self): return len(self._list) def __str__(self): return str(self._list) def __repr__(self): return repr(self._list) def _set_list(self, length, items): # this would work: # self._list = self._mytype(items) # but then we wouldn't be testing length parameter itemList = ['x'] * length for i, v in enumerate(items): itemList[i] = v self._list = self._mytype(itemList) def _get_single_external(self, index): return self._list[index] class UserListB(UserListA): _mytype = list def _set_single(self, index, value): self._list[index] = value def nextRange(length): nextRange.start += 100 return range(nextRange.start, nextRange.start + length) nextRange.start = 0 class ListMixinTest(unittest.TestCase): """ Tests base class ListMixin by comparing a list clone which is a ListMixin subclass with a real Python list. """ limit = 3 listType = UserListA def lists_of_len(self, length=None): if length is None: length = self.limit pl = list(range(length)) return pl, self.listType(pl) def limits_plus(self, b): return range(-self.limit - b, self.limit + b) def step_range(self): return [*range(-1 - self.limit, 0), *range(1, 1 + self.limit)] def test01_getslice(self): 'Slice retrieval' pl, ul = self.lists_of_len() for i in self.limits_plus(1): self.assertEqual(pl[i:], ul[i:], 'slice [%d:]' % (i)) self.assertEqual(pl[:i], ul[:i], 'slice [:%d]' % (i)) for j in self.limits_plus(1): self.assertEqual(pl[i:j], ul[i:j], 'slice [%d:%d]' % (i, j)) for k in self.step_range(): self.assertEqual(pl[i:j:k], ul[i:j:k], 'slice [%d:%d:%d]' % (i, j, k)) for k in self.step_range(): self.assertEqual(pl[i::k], ul[i::k], 'slice [%d::%d]' % (i, k)) self.assertEqual(pl[:i:k], ul[:i:k], 'slice [:%d:%d]' % (i, k)) for k in self.step_range(): self.assertEqual(pl[::k], ul[::k], 'slice [::%d]' % (k)) def test02_setslice(self): 'Slice assignment' def setfcn(x, i, j, k, L): x[i:j:k] = range(L) pl, ul = self.lists_of_len() for slen in range(self.limit + 1): ssl = nextRange(slen) ul[:] = ssl pl[:] = ssl self.assertEqual(pl, ul[:], 'set slice [:]') for i in self.limits_plus(1): ssl = nextRange(slen) ul[i:] = ssl pl[i:] = ssl self.assertEqual(pl, ul[:], 'set slice [%d:]' % (i)) ssl = nextRange(slen) ul[:i] = ssl pl[:i] = ssl self.assertEqual(pl, ul[:], 'set slice [:%d]' % (i)) for j in self.limits_plus(1): ssl = nextRange(slen) ul[i:j] = ssl pl[i:j] = ssl self.assertEqual(pl, ul[:], 'set slice [%d:%d]' % (i, j)) for k in self.step_range(): ssl = nextRange(len(ul[i:j:k])) ul[i:j:k] = ssl pl[i:j:k] = ssl self.assertEqual(pl, ul[:], 'set slice [%d:%d:%d]' % (i, j, k)) sliceLen = len(ul[i:j:k]) with self.assertRaises(ValueError): setfcn(ul, i, j, k, sliceLen + 1) if sliceLen > 2: with self.assertRaises(ValueError): setfcn(ul, i, j, k, sliceLen - 1) for k in self.step_range(): ssl = nextRange(len(ul[i::k])) ul[i::k] = ssl pl[i::k] = ssl self.assertEqual(pl, ul[:], 'set slice [%d::%d]' % (i, k)) ssl = nextRange(len(ul[:i:k])) ul[:i:k] = ssl pl[:i:k] = ssl self.assertEqual(pl, ul[:], 'set slice [:%d:%d]' % (i, k)) for k in self.step_range(): ssl = nextRange(len(ul[::k])) ul[::k] = ssl pl[::k] = ssl self.assertEqual(pl, ul[:], 'set slice [::%d]' % (k)) def test03_delslice(self): 'Delete slice' for Len in range(self.limit): pl, ul = self.lists_of_len(Len) del pl[:] del ul[:] self.assertEqual(pl[:], ul[:], 'del slice [:]') for i in range(-Len - 1, Len + 1): pl, ul = self.lists_of_len(Len) del pl[i:] del ul[i:] self.assertEqual(pl[:], ul[:], 'del slice [%d:]' % (i)) pl, ul = self.lists_of_len(Len) del pl[:i] del ul[:i] self.assertEqual(pl[:], ul[:], 'del slice [:%d]' % (i)) for j in range(-Len - 1, Len + 1): pl, ul = self.lists_of_len(Len) del pl[i:j] del ul[i:j] self.assertEqual(pl[:], ul[:], 'del slice [%d:%d]' % (i, j)) for k in [*range(-Len - 1, 0), *range(1, Len)]: pl, ul = self.lists_of_len(Len) del pl[i:j:k] del ul[i:j:k] self.assertEqual(pl[:], ul[:], 'del slice [%d:%d:%d]' % (i, j, k)) for k in [*range(-Len - 1, 0), *range(1, Len)]: pl, ul = self.lists_of_len(Len) del pl[:i:k] del ul[:i:k] self.assertEqual(pl[:], ul[:], 'del slice [:%d:%d]' % (i, k)) pl, ul = self.lists_of_len(Len) del pl[i::k] del ul[i::k] self.assertEqual(pl[:], ul[:], 'del slice [%d::%d]' % (i, k)) for k in [*range(-Len - 1, 0), *range(1, Len)]: pl, ul = self.lists_of_len(Len) del pl[::k] del ul[::k] self.assertEqual(pl[:], ul[:], 'del slice [::%d]' % (k)) def test04_get_set_del_single(self): 'Get/set/delete single item' pl, ul = self.lists_of_len() for i in self.limits_plus(0): self.assertEqual(pl[i], ul[i], 'get single item [%d]' % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() pl[i] = 100 ul[i] = 100 self.assertEqual(pl[:], ul[:], 'set single item [%d]' % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() del pl[i] del ul[i] self.assertEqual(pl[:], ul[:], 'del single item [%d]' % i) def test05_out_of_range_exceptions(self): 'Out of range exceptions' def setfcn(x, i): x[i] = 20 def getfcn(x, i): return x[i] def delfcn(x, i): del x[i] pl, ul = self.lists_of_len() for i in (-1 - self.limit, self.limit): with self.assertRaises(IndexError): # 'set index %d' % i) setfcn(ul, i) with self.assertRaises(IndexError): # 'get index %d' % i) getfcn(ul, i) with self.assertRaises(IndexError): # 'del index %d' % i) delfcn(ul, i) def test06_list_methods(self): 'List methods' pl, ul = self.lists_of_len() pl.append(40) ul.append(40) self.assertEqual(pl[:], ul[:], 'append') pl.extend(range(50, 55)) ul.extend(range(50, 55)) self.assertEqual(pl[:], ul[:], 'extend') pl.reverse() ul.reverse() self.assertEqual(pl[:], ul[:], 'reverse') for i in self.limits_plus(1): pl, ul = self.lists_of_len() pl.insert(i, 50) ul.insert(i, 50) self.assertEqual(pl[:], ul[:], 'insert at %d' % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() self.assertEqual(pl.pop(i), ul.pop(i), 'popped value at %d' % i) self.assertEqual(pl[:], ul[:], 'after pop at %d' % i) pl, ul = self.lists_of_len() self.assertEqual(pl.pop(), ul.pop(i), 'popped value') self.assertEqual(pl[:], ul[:], 'after pop') pl, ul = self.lists_of_len() def popfcn(x, i): x.pop(i) with self.assertRaises(IndexError): popfcn(ul, self.limit) with self.assertRaises(IndexError): popfcn(ul, -1 - self.limit) pl, ul = self.lists_of_len() for val in range(self.limit): self.assertEqual(pl.index(val), ul.index(val), 'index of %d' % val) for val in self.limits_plus(2): self.assertEqual(pl.count(val), ul.count(val), 'count %d' % val) for val in range(self.limit): pl, ul = self.lists_of_len() pl.remove(val) ul.remove(val) self.assertEqual(pl[:], ul[:], 'after remove val %d' % val) def indexfcn(x, v): return x.index(v) def removefcn(x, v): return x.remove(v) with self.assertRaises(ValueError): indexfcn(ul, 40) with self.assertRaises(ValueError): removefcn(ul, 40) def test07_allowed_types(self): 'Type-restricted list' pl, ul = self.lists_of_len() ul._allowed = int ul[1] = 50 ul[:2] = [60, 70, 80] def setfcn(x, i, v): x[i] = v with self.assertRaises(TypeError): setfcn(ul, 2, 'hello') with self.assertRaises(TypeError): setfcn(ul, slice(0, 3, 2), ('hello', 'goodbye')) def test08_min_length(self): 'Length limits' pl, ul = self.lists_of_len(5) ul._minlength = 3 def delfcn(x, i): del x[:i] def setfcn(x, i): x[:i] = [] for i in range(len(ul) - ul._minlength + 1, len(ul)): with self.assertRaises(ValueError): delfcn(ul, i) with self.assertRaises(ValueError): setfcn(ul, i) del ul[:len(ul) - ul._minlength] ul._maxlength = 4 for i in range(0, ul._maxlength - len(ul)): ul.append(i) with self.assertRaises(ValueError): ul.append(10) def test09_iterable_check(self): 'Error on assigning non-iterable to slice' pl, ul = self.lists_of_len(self.limit + 1) def setfcn(x, i, v): x[i] = v with self.assertRaises(TypeError): setfcn(ul, slice(0, 3, 2), 2) def test10_checkindex(self): 'Index check' pl, ul = self.lists_of_len() for i in self.limits_plus(0): if i < 0: self.assertEqual(ul._checkindex(i), i + self.limit, '_checkindex(neg index)') else: self.assertEqual(ul._checkindex(i), i, '_checkindex(pos index)') for i in (-self.limit - 1, self.limit): with self.assertRaises(IndexError): ul._checkindex(i) def test_11_sorting(self): 'Sorting' pl, ul = self.lists_of_len() pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort() ul.sort() self.assertEqual(pl[:], ul[:], 'sort') mid = pl[len(pl) // 2] pl.sort(key=lambda x: (mid - x) ** 2) ul.sort(key=lambda x: (mid - x) ** 2) self.assertEqual(pl[:], ul[:], 'sort w/ key') pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort(reverse=True) ul.sort(reverse=True) self.assertEqual(pl[:], ul[:], 'sort w/ reverse') mid = pl[len(pl) // 2] pl.sort(key=lambda x: (mid - x) ** 2) ul.sort(key=lambda x: (mid - x) ** 2) self.assertEqual(pl[:], ul[:], 'sort w/ key') def test_12_arithmetic(self): 'Arithmetic' pl, ul = self.lists_of_len() al = list(range(10, 14)) self.assertEqual(list(pl + al), list(ul + al), 'add') self.assertEqual(type(ul), type(ul + al), 'type of add result') self.assertEqual(list(al + pl), list(al + ul), 'radd') self.assertEqual(type(al), type(al + ul), 'type of radd result') objid = id(ul) pl += al ul += al self.assertEqual(pl[:], ul[:], 'in-place add') self.assertEqual(objid, id(ul), 'in-place add id') for n in (-1, 0, 1, 3): pl, ul = self.lists_of_len() self.assertEqual(list(pl * n), list(ul * n), 'mul by %d' % n) self.assertEqual(type(ul), type(ul * n), 'type of mul by %d result' % n) self.assertEqual(list(n * pl), list(n * ul), 'rmul by %d' % n) self.assertEqual(type(ul), type(n * ul), 'type of rmul by %d result' % n) objid = id(ul) pl *= n ul *= n self.assertEqual(pl[:], ul[:], 'in-place mul by %d' % n) self.assertEqual(objid, id(ul), 'in-place mul by %d id' % n) pl, ul = self.lists_of_len() self.assertEqual(pl, ul, 'cmp for equal') self.assertNotEqual(ul, pl + [2], 'cmp for not equal') self.assertGreaterEqual(pl, ul, 'cmp for gte self') self.assertLessEqual(pl, ul, 'cmp for lte self') self.assertGreaterEqual(ul, pl, 'cmp for self gte') self.assertLessEqual(ul, pl, 'cmp for self lte') self.assertGreater(pl + [5], ul, 'cmp') self.assertGreaterEqual(pl + [5], ul, 'cmp') self.assertLess(pl, ul + [2], 'cmp') self.assertLessEqual(pl, ul + [2], 'cmp') self.assertGreater(ul + [5], pl, 'cmp') self.assertGreaterEqual(ul + [5], pl, 'cmp') self.assertLess(ul, pl + [2], 'cmp') self.assertLessEqual(ul, pl + [2], 'cmp') pl[1] = 20 self.assertGreater(pl, ul, 'cmp for gt self') self.assertLess(ul, pl, 'cmp for self lt') pl[1] = -20 self.assertLess(pl, ul, 'cmp for lt self') self.assertGreater(ul, pl, 'cmp for gt self') class ListMixinTestSingle(ListMixinTest): listType = UserListB
587d3de707a9357454764326811068eb801d89e94062e0184bd7c150374fefb6
import ctypes import itertools import json import pickle import random from binascii import a2b_hex from io import BytesIO from unittest import mock from django.contrib.gis import gdal from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromfile, fromstr, ) from django.contrib.gis.geos.libgeos import geos_version_tuple from django.contrib.gis.shortcuts import numpy from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from ..test_data import TestDataMixin class GEOSTest(SimpleTestCase, TestDataMixin): def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: geom = fromstr(g.wkt) if geom.hasz: self.assertEqual(g.ewkt, geom.wkt) def test_hex(self): "Testing HEX output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) self.assertEqual(g.hex, geom.hex.decode()) def test_hexewkb(self): "Testing (HEX)EWKB output." # For testing HEX(EWKB). ogc_hex = b'01010000000000000000000000000000000000F03F' ogc_hex_3d = b'01010000800000000000000000000000000000F03F0000000000000040' # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));` hexewkb_2d = b'0101000020E61000000000000000000000000000000000F03F' # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));` hexewkb_3d = b'01010000A0E61000000000000000000000000000000000F03F0000000000000040' pnt_2d = Point(0, 1, srid=4326) pnt_3d = Point(0, 1, 2, srid=4326) # OGC-compliant HEX will not have SRID value. self.assertEqual(ogc_hex, pnt_2d.hex) self.assertEqual(ogc_hex_3d, pnt_3d.hex) # HEXEWKB should be appropriate for its dimension -- have to use an # a WKBWriter w/dimension set accordingly, else GEOS will insert # garbage into 3D coordinate if there is none. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True) # Same for EWKB. self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb) # Redundant sanity check. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid) def test_kml(self): "Testing KML output." for tg in self.geometries.wkt_out: geom = fromstr(tg.wkt) kml = getattr(tg, 'kml', False) if kml: self.assertEqual(kml, geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with self.assertRaises((GEOSException, ValueError)): fromstr(err.wkt) # Bad WKB with self.assertRaises(GEOSException): GEOSGeometry(memoryview(b'0')) class NotAGeometry: pass # Some other object with self.assertRaises(TypeError): GEOSGeometry(NotAGeometry()) # None with self.assertRaises(TypeError): GEOSGeometry(None) def test_wkb(self): "Testing WKB output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) wkb = geom.wkb self.assertEqual(wkb.hex().upper(), g.hex) def test_create_hex(self): "Testing creation from HEX." for g in self.geometries.hex_wkt: geom_h = GEOSGeometry(g.hex) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_create_wkb(self): "Testing creation from WKB." for g in self.geometries.hex_wkt: wkb = memoryview(bytes.fromhex(g.hex)) geom_h = GEOSGeometry(wkb) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_ewkt(self): "Testing EWKT." srids = (-1, 32140) for srid in srids: for p in self.geometries.polygons: ewkt = 'SRID=%d;%s' % (srid, p.wkt) poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export def test_json(self): "Testing GeoJSON input/output (via GDAL)." for g in self.geometries.json_geoms: geom = GEOSGeometry(g.wkt) if not hasattr(g, 'not_equal'): # Loading jsons to prevent decimal differences self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json)) def test_json_srid(self): geojson_data = { "type": "Point", "coordinates": [2, 49], "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4322" } } } self.assertEqual(GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322)) def test_fromfile(self): "Testing the fromfile() factory." ref_pnt = GEOSGeometry('POINT(5 23)') wkt_f = BytesIO() wkt_f.write(ref_pnt.wkt.encode()) wkb_f = BytesIO() wkb_f.write(bytes(ref_pnt.wkb)) # Other tests use `fromfile()` on string filenames so those # aren't tested here. for fh in (wkt_f, wkb_f): fh.seek(0) pnt = fromfile(fh) self.assertEqual(ref_pnt, pnt) def test_eq(self): "Testing equivalence." p = fromstr('POINT(5 23)') self.assertEqual(p, p.wkt) self.assertNotEqual(p, 'foo') ls = fromstr('LINESTRING(0 0, 1 1, 5 5)') self.assertEqual(ls, ls.wkt) self.assertNotEqual(p, 'bar') self.assertEqual(p, 'POINT(5.0 23.0)') # Error shouldn't be raise on equivalence testing with # an invalid type. for g in (p, ls): self.assertNotEqual(g, None) self.assertNotEqual(g, {'foo': 'bar'}) self.assertNotEqual(g, False) def test_hash(self): point_1 = Point(5, 23) point_2 = Point(5, 23, srid=4326) point_3 = Point(5, 23, srid=32632) multipoint_1 = MultiPoint(point_1, srid=4326) multipoint_2 = MultiPoint(point_2) multipoint_3 = MultiPoint(point_3) self.assertNotEqual(hash(point_1), hash(point_2)) self.assertNotEqual(hash(point_1), hash(point_3)) self.assertNotEqual(hash(point_2), hash(point_3)) self.assertNotEqual(hash(multipoint_1), hash(multipoint_2)) self.assertEqual(hash(multipoint_2), hash(multipoint_3)) self.assertNotEqual(hash(multipoint_1), hash(point_1)) self.assertNotEqual(hash(multipoint_2), hash(point_2)) self.assertNotEqual(hash(multipoint_3), hash(point_3)) def test_eq_with_srid(self): "Testing non-equivalence with different srids." p0 = Point(5, 23) p1 = Point(5, 23, srid=4326) p2 = Point(5, 23, srid=32632) # GEOS self.assertNotEqual(p0, p1) self.assertNotEqual(p1, p2) # EWKT self.assertNotEqual(p0, p1.ewkt) self.assertNotEqual(p1, p0.ewkt) self.assertNotEqual(p1, p2.ewkt) # Equivalence with matching SRIDs self.assertEqual(p2, p2) self.assertEqual(p2, p2.ewkt) # WKT contains no SRID so will not equal self.assertNotEqual(p2, p2.wkt) # SRID of 0 self.assertEqual(p0, 'SRID=0;POINT (5 23)') self.assertNotEqual(p1, 'SRID=0;POINT (5 23)') def test_points(self): "Testing Point objects." prev = fromstr('POINT(0 0)') for p in self.geometries.points: # Creating the point from the WKT pnt = fromstr(p.wkt) self.assertEqual(pnt.geom_type, 'Point') self.assertEqual(pnt.geom_typeid, 0) self.assertEqual(pnt.dims, 0) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual(pnt, fromstr(p.wkt)) self.assertEqual(False, pnt == prev) # Use assertEqual to test __eq__ # Making sure that the point's X, Y components are what we expect self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.y, pnt.tuple[1], 9) # Testing the third dimension, and getting the tuple arguments if hasattr(p, 'z'): self.assertIs(pnt.hasz, True) self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.tuple[2], 9) tup_args = (p.x, p.y, p.z) set_tup1 = (2.71, 3.14, 5.23) set_tup2 = (5.23, 2.71, 3.14) else: self.assertIs(pnt.hasz, False) self.assertIsNone(pnt.z) tup_args = (p.x, p.y) set_tup1 = (2.71, 3.14) set_tup2 = (3.14, 2.71) # Centroid operation on point should be point itself self.assertEqual(p.centroid, pnt.centroid.tuple) # Now testing the different constructors pnt2 = Point(tup_args) # e.g., Point((1, 2)) pnt3 = Point(*tup_args) # e.g., Point(1, 2) self.assertEqual(pnt, pnt2) self.assertEqual(pnt, pnt3) # Now testing setting the x and y pnt.y = 3.14 pnt.x = 2.71 self.assertEqual(3.14, pnt.y) self.assertEqual(2.71, pnt.x) # Setting via the tuple/coords property pnt.tuple = set_tup1 self.assertEqual(set_tup1, pnt.tuple) pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) prev = pnt # setting the previous geometry def test_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: mpnt = fromstr(mp.wkt) self.assertEqual(mpnt.geom_type, 'MultiPoint') self.assertEqual(mpnt.geom_typeid, 4) self.assertEqual(mpnt.dims, 0) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) with self.assertRaises(IndexError): mpnt.__getitem__(len(mpnt)) self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt)) for p in mpnt: self.assertEqual(p.geom_type, 'Point') self.assertEqual(p.geom_typeid, 0) self.assertIs(p.empty, False) self.assertIs(p.valid, True) def test_linestring(self): "Testing LineString objects." prev = fromstr('POINT(0 0)') for l in self.geometries.linestrings: ls = fromstr(l.wkt) self.assertEqual(ls.geom_type, 'LineString') self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.dims, 1) self.assertIs(ls.empty, False) self.assertIs(ls.ring, False) if hasattr(l, 'centroid'): self.assertEqual(l.centroid, ls.centroid.tuple) if hasattr(l, 'tup'): self.assertEqual(l.tup, ls.tuple) self.assertEqual(ls, fromstr(l.wkt)) self.assertEqual(False, ls == prev) # Use assertEqual to test __eq__ with self.assertRaises(IndexError): ls.__getitem__(len(ls)) prev = ls # Creating a LineString from a tuple, list, and numpy array self.assertEqual(ls, LineString(ls.tuple)) # tuple self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list # Point individual arguments self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) if numpy: self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array with self.assertRaisesMessage(TypeError, 'Each coordinate should be a sequence (list or tuple)'): LineString((0, 0)) with self.assertRaisesMessage(ValueError, 'LineString requires at least 2 points, got 1.'): LineString([(0, 0)]) if numpy: with self.assertRaisesMessage(ValueError, 'LineString requires at least 2 points, got 1.'): LineString(numpy.array([(0, 0)])) with mock.patch('django.contrib.gis.geos.linestring.numpy', False): with self.assertRaisesMessage(TypeError, 'Invalid initialization input for LineStrings.'): LineString('wrong input') # Test __iter__(). self.assertEqual(list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)]) def test_multilinestring(self): "Testing MultiLineString objects." prev = fromstr('POINT(0 0)') for l in self.geometries.multilinestrings: ml = fromstr(l.wkt) self.assertEqual(ml.geom_type, 'MultiLineString') self.assertEqual(ml.geom_typeid, 5) self.assertEqual(ml.dims, 1) self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9) self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9) self.assertEqual(ml, fromstr(l.wkt)) self.assertEqual(False, ml == prev) # Use assertEqual to test __eq__ prev = ml for ls in ml: self.assertEqual(ls.geom_type, 'LineString') self.assertEqual(ls.geom_typeid, 1) self.assertIs(ls.empty, False) with self.assertRaises(IndexError): ml.__getitem__(len(ml)) self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt) self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml))) def test_linearring(self): "Testing LinearRing objects." for rr in self.geometries.linearrings: lr = fromstr(rr.wkt) self.assertEqual(lr.geom_type, 'LinearRing') self.assertEqual(lr.geom_typeid, 2) self.assertEqual(lr.dims, 1) self.assertEqual(rr.n_p, len(lr)) self.assertIs(lr.valid, True) self.assertIs(lr.empty, False) # Creating a LinearRing from a tuple, list, and numpy array self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(*lr.tuple)) self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple])) if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple))) with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 3.'): LinearRing((0, 0), (1, 1), (0, 0)) with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 1.'): LinearRing([(0, 0)]) if numpy: with self.assertRaisesMessage(ValueError, 'LinearRing requires at least 4 points, got 1.'): LinearRing(numpy.array([(0, 0)])) def test_linearring_json(self): self.assertJSONEqual( LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json, '{"coordinates": [[0, 0], [0, 1], [1, 1], [0, 0]], "type": "LineString"}', ) def test_polygons_from_bbox(self): "Testing `from_bbox` class method." bbox = (-180, -90, 180, 90) p = Polygon.from_bbox(bbox) self.assertEqual(bbox, p.extent) # Testing numerical precision x = 3.14159265358979323 bbox = (0, 0, 1, x) p = Polygon.from_bbox(bbox) y = p.extent[-1] self.assertEqual(format(x, '.13f'), format(y, '.13f')) def test_polygons(self): "Testing Polygon objects." prev = fromstr('POINT(0 0)') for p in self.geometries.polygons: # Creating the Polygon, testing its properties. poly = fromstr(p.wkt) self.assertEqual(poly.geom_type, 'Polygon') self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.dims, 2) self.assertIs(poly.empty, False) self.assertIs(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_p, poly.num_points) # Area & Centroid self.assertAlmostEqual(p.area, poly.area, 9) self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9) self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9) # Testing the geometry equivalence self.assertEqual(poly, fromstr(p.wkt)) # Should not be equal to previous geometry self.assertEqual(False, poly == prev) # Use assertEqual to test __eq__ self.assertNotEqual(poly, prev) # Use assertNotEqual to test __ne__ # Testing the exterior ring ring = poly.exterior_ring self.assertEqual(ring.geom_type, 'LinearRing') self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ # Testing __getitem__ and __setitem__ on invalid indices with self.assertRaises(IndexError): poly.__getitem__(len(poly)) with self.assertRaises(IndexError): poly.__setitem__(len(poly), False) with self.assertRaises(IndexError): poly.__getitem__(-1 * len(poly) - 1) # Testing __iter__ for r in poly: self.assertEqual(r.geom_type, 'LinearRing') self.assertEqual(r.geom_typeid, 2) # Testing polygon construction. with self.assertRaises(TypeError): Polygon(0, [1, 2, 3]) with self.assertRaises(TypeError): Polygon('foo') # Polygon(shell, (hole1, ... holeN)) ext_ring, *int_rings = poly self.assertEqual(poly, Polygon(ext_ring, int_rings)) # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN) ring_tuples = tuple(r.tuple for r in poly) self.assertEqual(poly, Polygon(*ring_tuples)) # Constructing with tuples of LinearRings. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt) self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt) def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string('{{ polygons.0.wkt }}') polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({'polygons': polygons})) self.assertIn('MULTIPOLYGON (((100', content) def test_polygon_comparison(self): p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0))) self.assertGreater(p1, p2) self.assertLess(p2, p1) p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0))) p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0))) self.assertGreater(p4, p3) self.assertLess(p3, p4) def test_multipolygons(self): "Testing MultiPolygon objects." fromstr('POINT (0 0)') for mp in self.geometries.multipolygons: mpoly = fromstr(mp.wkt) self.assertEqual(mpoly.geom_type, 'MultiPolygon') self.assertEqual(mpoly.geom_typeid, 6) self.assertEqual(mpoly.dims, 2) self.assertEqual(mp.valid, mpoly.valid) if mp.valid: self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, len(mpoly)) with self.assertRaises(IndexError): mpoly.__getitem__(len(mpoly)) for p in mpoly: self.assertEqual(p.geom_type, 'Polygon') self.assertEqual(p.geom_typeid, 3) self.assertIs(p.valid, True) self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt) def test_memory_hijinks(self): "Testing Geometry __del__() on rings and polygons." # #### Memory issues with rings and poly # These tests are needed to ensure sanity with writable geometries. # Getting a polygon with interior rings, and pulling out the interior rings poly = fromstr(self.geometries.polygons[1].wkt) ring1 = poly[0] ring2 = poly[1] # These deletes should be 'harmless' since they are done on child geometries del ring1 del ring2 ring1 = poly[0] ring2 = poly[1] # Deleting the polygon del poly # Access to these rings is OK since they are clones. str(ring1) str(ring2) def test_coord_seq(self): "Testing Coordinate Sequence objects." for p in self.geometries.polygons: if p.ext_ring_cs: # Constructing the polygon and getting the coordinate sequence poly = fromstr(p.wkt) cs = poly.exterior_ring.coord_seq self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too. self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works # Checks __getitem__ and __setitem__ for i in range(len(p.ext_ring_cs)): c1 = p.ext_ring_cs[i] # Expected value c2 = cs[i] # Value from coordseq self.assertEqual(c1, c2) # Constructing the test value to set the coordinate sequence with if len(c1) == 2: tset = (5, 23) else: tset = (5, 23, 8) cs[i] = tset # Making sure every set point matches what we expect for j in range(len(tset)): cs[i] = tset self.assertEqual(tset[j], cs[i][j]) def test_relate_pattern(self): "Testing relate() and relate_pattern()." g = fromstr('POINT (0 0)') with self.assertRaises(GEOSException): g.relate_pattern(0, 'invalid pattern, yo') for rg in self.geometries.relate_geoms: a = fromstr(rg.wkt_a) b = fromstr(rg.wkt_b) self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern)) self.assertEqual(rg.pattern, a.relate(b)) def test_intersection(self): "Testing intersects() and intersection()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) i1 = fromstr(self.geometries.intersect_geoms[i].wkt) self.assertIs(a.intersects(b), True) i2 = a.intersection(b) self.assertEqual(i1, i2) self.assertEqual(i1, a & b) # __and__ is intersection operator a &= b # testing __iand__ self.assertEqual(i1, a) def test_union(self): "Testing union()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertEqual(u1, u2) self.assertEqual(u1, a | b) # __or__ is union operator a |= b # testing __ior__ self.assertEqual(u1, a) def test_unary_union(self): "Testing unary_union." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = GeometryCollection(a, b).unary_union self.assertTrue(u1.equals(u2)) def test_difference(self): "Testing difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertEqual(d1, d2) self.assertEqual(d1, a - b) # __sub__ is difference operator a -= b # testing __isub__ self.assertEqual(d1, a) def test_symdifference(self): "Testing sym_difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertEqual(d1, d2) self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator a ^= b # testing __ixor__ self.assertEqual(d1, a) def test_buffer(self): bg = self.geometries.buffer_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer(bg.width, quadsegs=1.1) self._test_buffer(self.geometries.buffer_geoms, 'buffer') def test_buffer_with_style(self): bg = self.geometries.buffer_with_style_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, quadsegs=1.1) # Can't use a floating-point for the end cap style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, end_cap_style=1.2) # Can't use a end cap style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, end_cap_style=55) # Can't use a floating-point for the join style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, join_style=1.3) # Can't use a join style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, join_style=66) self._test_buffer( itertools.chain(self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms), 'buffer_with_style', ) def _test_buffer(self, geometries, buffer_method_name): for bg in geometries: g = fromstr(bg.wkt) # The buffer we expect exp_buf = fromstr(bg.buffer_wkt) # Constructing our buffer buf_kwargs = { kwarg_name: getattr(bg, kwarg_name) for kwarg_name in ('width', 'quadsegs', 'end_cap_style', 'join_style', 'mitre_limit') if hasattr(bg, kwarg_name) } buf = getattr(g, buffer_method_name)(**buf_kwargs) self.assertEqual(exp_buf.num_coords, buf.num_coords) self.assertEqual(len(exp_buf), len(buf)) # Now assuring that each point in the buffer is almost equal for j in range(len(exp_buf)): exp_ring = exp_buf[j] buf_ring = buf[j] self.assertEqual(len(exp_ring), len(buf_ring)) for k in range(len(exp_ring)): # Asserting the X, Y of each point are almost equal (due to floating point imprecision) self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9) self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9) def test_covers(self): poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0))) self.assertTrue(poly.covers(Point(5, 5))) self.assertFalse(poly.covers(Point(100, 100))) def test_closed(self): ls_closed = LineString((0, 0), (1, 1), (0, 0)) ls_not_closed = LineString((0, 0), (1, 1)) self.assertFalse(ls_not_closed.closed) self.assertTrue(ls_closed.closed) def test_srid(self): "Testing the SRID property and keyword." # Testing SRID keyword on Point pnt = Point(5, 23, srid=4326) self.assertEqual(4326, pnt.srid) pnt.srid = 3084 self.assertEqual(3084, pnt.srid) with self.assertRaises(ctypes.ArgumentError): pnt.srid = '4326' # Testing SRID keyword on fromstr(), and on Polygon rings. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269) self.assertEqual(4269, poly.srid) for ring in poly: self.assertEqual(4269, ring.srid) poly.srid = 4326 self.assertEqual(4326, poly.shell.srid) # Testing SRID keyword on GeometryCollection gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021) self.assertEqual(32021, gc.srid) for i in range(len(gc)): self.assertEqual(32021, gc[i].srid) # GEOS may get the SRID from HEXEWKB # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS # using `SELECT GeomFromText('POINT (5 23)', 4326);`. hex = '0101000020E610000000000000000014400000000000003740' p1 = fromstr(hex) self.assertEqual(4326, p1.srid) p2 = fromstr(p1.hex) self.assertIsNone(p2.srid) p3 = fromstr(p1.hex, srid=-1) # -1 is intended. self.assertEqual(-1, p3.srid) # Testing that geometry SRID could be set to its own value pnt_wo_srid = Point(1, 1) pnt_wo_srid.srid = pnt_wo_srid.srid # Input geometries that have an SRID. self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid) self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid) with self.assertRaisesMessage(ValueError, 'Input geometry already has SRID: %d.' % pnt.srid): GEOSGeometry(pnt.ewkt, srid=1) with self.assertRaisesMessage(ValueError, 'Input geometry already has SRID: %d.' % pnt.srid): GEOSGeometry(pnt.ewkb, srid=1) def test_custom_srid(self): """Test with a null srid and a srid unknown to GDAL.""" for srid in [None, 999999]: pnt = Point(111200, 220900, srid=srid) self.assertTrue(pnt.ewkt.startswith(("SRID=%s;" % srid if srid else '') + "POINT (111200")) self.assertIsInstance(pnt.ogr, gdal.OGRGeometry) self.assertIsNone(pnt.srs) # Test conversion from custom to a known srid c2w = gdal.CoordTransform( gdal.SpatialReference( '+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 ' '+datum=WGS84 +units=m +no_defs' ), gdal.SpatialReference(4326)) new_pnt = pnt.transform(c2w, clone=True) self.assertEqual(new_pnt.srid, 4326) self.assertAlmostEqual(new_pnt.x, 1, 3) self.assertAlmostEqual(new_pnt.y, 2, 3) def test_mutable_geometries(self): "Testing the mutability of Polygons and Geometry Collections." # ### Testing the mutability of Polygons ### for p in self.geometries.polygons: poly = fromstr(p.wkt) # Should only be able to use __setitem__ with LinearRing geometries. with self.assertRaises(TypeError): poly.__setitem__(0, LineString((1, 1), (2, 2))) # Constructing the new shell by adding 500 to every point in the old shell. shell_tup = poly.shell.tuple new_coords = [] for point in shell_tup: new_coords.append((point[0] + 500., point[1] + 500.)) new_shell = LinearRing(*tuple(new_coords)) # Assigning polygon's exterior ring w/the new shell poly.exterior_ring = new_shell str(new_shell) # new shell is still accessible self.assertEqual(poly.exterior_ring, new_shell) self.assertEqual(poly[0], new_shell) # ### Testing the mutability of Geometry Collections for tg in self.geometries.multipoints: mp = fromstr(tg.wkt) for i in range(len(mp)): # Creating a random point. pnt = mp[i] new = Point(random.randint(21, 100), random.randint(21, 100)) # Testing the assignment mp[i] = new str(new) # what was used for the assignment is still accessible self.assertEqual(mp[i], new) self.assertEqual(mp[i].wkt, new.wkt) self.assertNotEqual(pnt, mp[i]) # MultiPolygons involve much more memory management because each # Polygon w/in the collection has its own rings. for tg in self.geometries.multipolygons: mpoly = fromstr(tg.wkt) for i in range(len(mpoly)): poly = mpoly[i] old_poly = mpoly[i] # Offsetting the each ring in the polygon by 500. for j in range(len(poly)): r = poly[j] for k in range(len(r)): r[k] = (r[k][0] + 500., r[k][1] + 500.) poly[j] = r self.assertNotEqual(mpoly[i], poly) # Testing the assignment mpoly[i] = poly str(poly) # Still accessible self.assertEqual(mpoly[i], poly) self.assertNotEqual(mpoly[i], old_poly) # Extreme (!!) __setitem__ -- no longer works, have to detect # in the first object that __setitem__ is called in the subsequent # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)? # mpoly[0][0][0] = (3.14, 2.71) # self.assertEqual((3.14, 2.71), mpoly[0][0][0]) # Doing it more slowly.. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0]) # del mpoly def test_point_list_assignment(self): p = Point(0, 0) p[:] = (1, 2, 3) self.assertEqual(p, Point(1, 2, 3)) p[:] = () self.assertEqual(p.wkt, Point()) p[:] = (1, 2) self.assertEqual(p.wkt, Point(1, 2)) with self.assertRaises(ValueError): p[:] = (1,) with self.assertRaises(ValueError): p[:] = (1, 2, 3, 4, 5) def test_linestring_list_assignment(self): ls = LineString((0, 0), (1, 1)) ls[:] = () self.assertEqual(ls, LineString()) ls[:] = ((0, 0), (1, 1), (2, 2)) self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2))) with self.assertRaises(ValueError): ls[:] = (1,) def test_linearring_list_assignment(self): ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) ls[:] = () self.assertEqual(ls, LinearRing()) ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) with self.assertRaises(ValueError): ls[:] = ((0, 0), (1, 1), (2, 2)) def test_polygon_list_assignment(self): pol = Polygon() pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),) self.assertEqual(pol, Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),)) pol[:] = () self.assertEqual(pol, Polygon()) def test_geometry_collection_list_assignment(self): p = Point() gc = GeometryCollection() gc[:] = [p] self.assertEqual(gc, GeometryCollection(p)) gc[:] = () self.assertEqual(gc, GeometryCollection()) def test_threed(self): "Testing three-dimensional geometries." # Testing a 3D Point pnt = Point(2, 3, 8) self.assertEqual((2., 3., 8.), pnt.coords) with self.assertRaises(TypeError): pnt.tuple = (1., 2.) pnt.coords = (1., 2., 3.) self.assertEqual((1., 2., 3.), pnt.coords) # Testing a 3D LineString ls = LineString((2., 3., 8.), (50., 250., -117.)) self.assertEqual(((2., 3., 8.), (50., 250., -117.)), ls.tuple) with self.assertRaises(TypeError): ls.__setitem__(0, (1., 2.)) ls[0] = (1., 2., 3.) self.assertEqual((1., 2., 3.), ls[0]) def test_distance(self): "Testing the distance() function." # Distance to self should be 0. pnt = Point(0, 0) self.assertEqual(0.0, pnt.distance(Point(0, 0))) # Distance should be 1 self.assertEqual(1.0, pnt.distance(Point(0, 1))) # Distance should be ~ sqrt(2) self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11) # Distances are from the closest vertex in each geometry -- # should be 3 (distance from (2, 2) to (5, 2)). ls1 = LineString((0, 0), (1, 1), (2, 2)) ls2 = LineString((5, 2), (6, 1), (7, 0)) self.assertEqual(3, ls1.distance(ls2)) def test_length(self): "Testing the length property." # Points have 0 length. pnt = Point(0, 0) self.assertEqual(0.0, pnt.length) # Should be ~ sqrt(2) ls = LineString((0, 0), (1, 1)) self.assertAlmostEqual(1.41421356237, ls.length, 11) # Should be circumference of Polygon poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) self.assertEqual(4.0, poly.length) # Should be sum of each element's length in collection. mpoly = MultiPolygon(poly.clone(), poly) self.assertEqual(8.0, mpoly.length) def test_emptyCollections(self): "Testing empty geometries and collections." geoms = [ GeometryCollection([]), fromstr('GEOMETRYCOLLECTION EMPTY'), GeometryCollection(), fromstr('POINT EMPTY'), Point(), fromstr('LINESTRING EMPTY'), LineString(), fromstr('POLYGON EMPTY'), Polygon(), fromstr('MULTILINESTRING EMPTY'), MultiLineString(), fromstr('MULTIPOLYGON EMPTY'), MultiPolygon(()), MultiPolygon(), ] if numpy: geoms.append(LineString(numpy.array([]))) for g in geoms: self.assertIs(g.empty, True) # Testing len() and num_geom. if isinstance(g, Polygon): self.assertEqual(1, len(g)) # Has one empty linear ring self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g[0])) elif isinstance(g, (Point, LineString)): self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g)) else: self.assertEqual(0, g.num_geom) self.assertEqual(0, len(g)) # Testing __getitem__ (doesn't work on Point or Polygon) if isinstance(g, Point): with self.assertRaises(IndexError): g.x elif isinstance(g, Polygon): lr = g.shell self.assertEqual('LINEARRING EMPTY', lr.wkt) self.assertEqual(0, len(lr)) self.assertIs(lr.empty, True) with self.assertRaises(IndexError): lr.__getitem__(0) else: with self.assertRaises(IndexError): g.__getitem__(0) def test_collection_dims(self): gc = GeometryCollection([]) self.assertEqual(gc.dims, -1) gc = GeometryCollection(Point(0, 0)) self.assertEqual(gc.dims, 0) gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0)) self.assertEqual(gc.dims, 1) gc = GeometryCollection(LineString((0, 0), (1, 1)), Polygon(((0, 0), (0, 1), (1, 1), (0, 0))), Point(0, 0)) self.assertEqual(gc.dims, 2) def test_collections_of_collections(self): "Testing GeometryCollection handling of other collections." # Creating a GeometryCollection WKT string composed of other # collections and polygons. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid] coll.extend(mls.wkt for mls in self.geometries.multilinestrings) coll.extend(p.wkt for p in self.geometries.polygons) coll.extend(mp.wkt for mp in self.geometries.multipoints) gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll) # Should construct ok from WKT gc1 = GEOSGeometry(gc_wkt) # Should also construct ok from individual geometry arguments. gc2 = GeometryCollection(*tuple(g for g in gc1)) # And, they should be equal. self.assertEqual(gc1, gc2) def test_gdal(self): "Testing `ogr` and `srs` properties." g1 = fromstr('POINT(5 23)') self.assertIsInstance(g1.ogr, gdal.OGRGeometry) self.assertIsNone(g1.srs) g1_3d = fromstr('POINT(5 23 8)') self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry) self.assertEqual(g1_3d.ogr.z, 8) g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326) self.assertIsInstance(g2.ogr, gdal.OGRGeometry) self.assertIsInstance(g2.srs, gdal.SpatialReference) self.assertEqual(g2.hex, g2.ogr.hex) self.assertEqual('WGS 84', g2.srs.name) def test_copy(self): "Testing use with the Python `copy` module." import copy poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))') cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr) def test_transform(self): "Testing `transform` method." orig = GEOSGeometry('POINT (-104.609 38.255)', 4326) trans = GEOSGeometry('POINT (992385.4472045 481455.4944650)', 2774) # Using a srid, a SpatialReference object, and a CoordTransform object # for transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(gdal.SpatialReference('EPSG:2774')) ct = gdal.CoordTransform(gdal.SpatialReference('WGS84'), gdal.SpatialReference(2774)) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) prec = 3 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec) def test_transform_3d(self): p3d = GEOSGeometry('POINT (5 23 100)', 4326) p3d.transform(2774) self.assertAlmostEqual(p3d.z, 100, 3) def test_transform_noop(self): """ Testing `transform` method (SRID match) """ # transform() should no-op if source & dest SRIDs match, # regardless of whether GDAL is available. g = GEOSGeometry('POINT (-104.609 38.255)', 4326) gt = g.tuple g.transform(4326) self.assertEqual(g.tuple, gt) self.assertEqual(g.srid, 4326) g = GEOSGeometry('POINT (-104.609 38.255)', 4326) g1 = g.transform(4326, clone=True) self.assertEqual(g1.tuple, g.tuple) self.assertEqual(g1.srid, 4326) self.assertIsNot(g1, g, "Clone didn't happen") def test_transform_nosrid(self): """ Testing `transform` method (no SRID or negative SRID) """ g = GEOSGeometry('POINT (-104.609 38.255)', srid=None) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry('POINT (-104.609 38.255)', srid=None) with self.assertRaises(GEOSException): g.transform(2774, clone=True) g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1) with self.assertRaises(GEOSException): g.transform(2774, clone=True) def test_extent(self): "Testing `extent` method." # The xmin, ymin, xmax, ymax of the MultiPoint should be returned. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50)) self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) pnt = Point(5.23, 17.8) # Extent of points is just the point itself repeated. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent) # Testing on the 'real world' Polygon. poly = fromstr(self.geometries.polygons[3].wkt) ring = poly.shell x, y = ring.x, ring.y xmin, ymin = min(x), min(y) xmax, ymax = max(x), max(y) self.assertEqual((xmin, ymin, xmax, ymax), poly.extent) def test_pickle(self): "Testing pickling and unpickling support." # Creating a list of test geometries for pickling, # and setting the SRID on some of them. def get_geoms(lst, srid=None): return [GEOSGeometry(tg.wkt, srid) for tg in lst] tgeoms = get_geoms(self.geometries.points) tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326)) tgeoms.extend(get_geoms(self.geometries.polygons, 3084)) tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857)) tgeoms.append(Point(srid=4326)) tgeoms.append(Point()) for geom in tgeoms: s1 = pickle.dumps(geom) g1 = pickle.loads(s1) self.assertEqual(geom, g1) self.assertEqual(geom.srid, g1.srid) def test_prepared(self): "Testing PreparedGeometry support." # Creating a simple multipolygon and getting a prepared version. mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))') prep = mpoly.prepared # A set of test points. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)] for pnt in pnts: # Results should be the same (but faster) self.assertEqual(mpoly.contains(pnt), prep.contains(pnt)) self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt)) self.assertEqual(mpoly.covers(pnt), prep.covers(pnt)) self.assertTrue(prep.crosses(fromstr('LINESTRING(1 1, 15 15)'))) self.assertTrue(prep.disjoint(Point(-5, -5))) poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1))) self.assertTrue(prep.overlaps(poly)) poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0))) self.assertTrue(prep.touches(poly)) poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1))) self.assertTrue(prep.within(poly)) # Original geometry deletion should not crash the prepared one (#21662) del mpoly self.assertTrue(prep.covers(Point(5, 5))) def test_line_merge(self): "Testing line merge support" ref_geoms = (fromstr('LINESTRING(1 1, 1 1, 3 3)'), fromstr('MULTILINESTRING((1 1, 3 3), (3 3, 4 2))'), ) ref_merged = (fromstr('LINESTRING(1 1, 3 3)'), fromstr('LINESTRING (1 1, 3 3, 4 2)'), ) for geom, merged in zip(ref_geoms, ref_merged): self.assertEqual(merged, geom.merged) def test_valid_reason(self): "Testing IsValidReason support" g = GEOSGeometry("POINT(0 0)") self.assertTrue(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertEqual(g.valid_reason, "Valid Geometry") g = GEOSGeometry("LINESTRING(0 0, 0 0)") self.assertFalse(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertTrue(g.valid_reason.startswith("Too few points in geometry component")) def test_linearref(self): "Testing linear referencing" ls = fromstr('LINESTRING(0 0, 0 10, 10 10, 10 0)') mls = fromstr('MULTILINESTRING((0 0, 0 10), (10 0, 10 10))') self.assertEqual(ls.project(Point(0, 20)), 10.0) self.assertEqual(ls.project(Point(7, 6)), 24) self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3) self.assertEqual(ls.interpolate(10), Point(0, 10)) self.assertEqual(ls.interpolate(24), Point(10, 6)) self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10)) self.assertEqual(mls.project(Point(0, 20)), 10) self.assertEqual(mls.project(Point(7, 6)), 16) self.assertEqual(mls.interpolate(9), Point(0, 9)) self.assertEqual(mls.interpolate(17), Point(10, 7)) def test_deconstructible(self): """ Geometry classes should be deconstructible. """ point = Point(4.337844, 50.827537, srid=4326) path, args, kwargs = point.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.point.Point') self.assertEqual(args, (4.337844, 50.827537)) self.assertEqual(kwargs, {'srid': 4326}) ls = LineString(((0, 0), (1, 1))) path, args, kwargs = ls.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.linestring.LineString') self.assertEqual(args, (((0, 0), (1, 1)),)) self.assertEqual(kwargs, {}) ls2 = LineString([Point(0, 0), Point(1, 1)], srid=4326) path, args, kwargs = ls2.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.linestring.LineString') self.assertEqual(args, ([Point(0, 0), Point(1, 1)],)) self.assertEqual(kwargs, {'srid': 4326}) ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) poly = Polygon(ext_coords, int_coords) path, args, kwargs = poly.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.polygon.Polygon') self.assertEqual(args, (ext_coords, int_coords)) self.assertEqual(kwargs, {}) lr = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) path, args, kwargs = lr.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.linestring.LinearRing') self.assertEqual(args, ((0, 0), (0, 1), (1, 1), (0, 0))) self.assertEqual(kwargs, {}) mp = MultiPoint(Point(0, 0), Point(1, 1)) path, args, kwargs = mp.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.collections.MultiPoint') self.assertEqual(args, (Point(0, 0), Point(1, 1))) self.assertEqual(kwargs, {}) ls1 = LineString((0, 0), (1, 1)) ls2 = LineString((2, 2), (3, 3)) mls = MultiLineString(ls1, ls2) path, args, kwargs = mls.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.collections.MultiLineString') self.assertEqual(args, (ls1, ls2)) self.assertEqual(kwargs, {}) p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1))) mp = MultiPolygon(p1, p2) path, args, kwargs = mp.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.collections.MultiPolygon') self.assertEqual(args, (p1, p2)) self.assertEqual(kwargs, {}) poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) path, args, kwargs = gc.deconstruct() self.assertEqual(path, 'django.contrib.gis.geos.collections.GeometryCollection') self.assertEqual(args, (Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)) self.assertEqual(kwargs, {}) def test_subclassing(self): """ GEOSGeometry subclass may itself be subclassed without being forced-cast to the parent class during `__init__`. """ class ExtendedPolygon(Polygon): def __init__(self, *args, data=0, **kwargs): super().__init__(*args, **kwargs) self._data = data def __str__(self): return "EXT_POLYGON - data: %d - %s" % (self._data, self.wkt) ext_poly = ExtendedPolygon(((0, 0), (0, 1), (1, 1), (0, 0)), data=3) self.assertEqual(type(ext_poly), ExtendedPolygon) # ExtendedPolygon.__str__ should be called (instead of Polygon.__str__). self.assertEqual(str(ext_poly), "EXT_POLYGON - data: 3 - POLYGON ((0 0, 0 1, 1 1, 0 0))") self.assertJSONEqual( ext_poly.json, '{"coordinates": [[[0, 0], [0, 1], [1, 1], [0, 0]]], "type": "Polygon"}', ) def test_geos_version_tuple(self): versions = ( (b'3.0.0rc4-CAPI-1.3.3', (3, 0, 0)), (b'3.0.0-CAPI-1.4.1', (3, 0, 0)), (b'3.4.0dev-CAPI-1.8.0', (3, 4, 0)), (b'3.4.0dev-CAPI-1.8.0 r0', (3, 4, 0)), (b'3.6.2-CAPI-1.10.2 4d2925d6', (3, 6, 2)), ) for version_string, version_tuple in versions: with self.subTest(version_string=version_string): with mock.patch('django.contrib.gis.geos.libgeos.geos_version', lambda: version_string): self.assertEqual(geos_version_tuple(), version_tuple) def test_from_gml(self): self.assertEqual( GEOSGeometry('POINT(0 0)'), GEOSGeometry.from_gml( '<gml:Point gml:id="p21" srsName="http://www.opengis.net/def/crs/EPSG/0/4326">' ' <gml:pos srsDimension="2">0 0</gml:pos>' '</gml:Point>' ), ) def test_from_ewkt(self): self.assertEqual(GEOSGeometry.from_ewkt('SRID=1;POINT(1 1)'), Point(1, 1, srid=1)) self.assertEqual(GEOSGeometry.from_ewkt('POINT(1 1)'), Point(1, 1)) def test_from_ewkt_empty_string(self): msg = 'Expected WKT but got an empty string.' with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt('') with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt('SRID=1;') def test_from_ewkt_invalid_srid(self): msg = 'EWKT has invalid SRID part.' with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt('SRUD=1;POINT(1 1)') with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt('SRID=WGS84;POINT(1 1)') def test_fromstr_scientific_wkt(self): self.assertEqual(GEOSGeometry('POINT(1.0e-1 1.0e+1)'), Point(.1, 10)) def test_normalize(self): g = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1)) self.assertIsNone(g.normalize()) self.assertTrue(g.equals_exact(MultiPoint(Point(2, 2), Point(1, 1), Point(0, 0)))) def test_empty_point(self): p = Point(srid=4326) self.assertEqual(p.ogr.ewkt, p.ewkt) self.assertEqual(p.transform(2774, clone=True), Point(srid=2774)) p.transform(2774) self.assertEqual(p, Point(srid=2774))
fa331f10fc4d66865d7a48ed3926f84e772504d25e180b18277cfdd175035207
from django.contrib.gis.db.models import Collect, Count, Extent, F, Union from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point from django.db import NotSupportedError, connection from django.test import TestCase, skipUnlessDBFeature from django.test.utils import override_settings from django.utils import timezone from ..utils import no_oracle from .models import ( Article, Author, Book, City, DirectoryEntry, Event, Location, Parcel, ) class RelatedGeoModelTest(TestCase): fixtures = ['initial'] def test02_select_related(self): "Testing `select_related` on geographic models (see #7126)." qs1 = City.objects.order_by('id') qs2 = City.objects.order_by('id').select_related() qs3 = City.objects.order_by('id').select_related('location') # Reference data for what's in the fixtures. cities = ( ('Aurora', 'TX', -97.516111, 33.058333), ('Roswell', 'NM', -104.528056, 33.387222), ('Kecksburg', 'PA', -79.460734, 40.18476), ) for qs in (qs1, qs2, qs3): for ref, c in zip(cities, qs): nm, st, lon, lat = ref self.assertEqual(nm, c.name) self.assertEqual(st, c.state) self.assertAlmostEqual(lon, c.location.point.x, 6) self.assertAlmostEqual(lat, c.location.point.y, 6) @skipUnlessDBFeature("supports_extent_aggr") def test_related_extent_aggregate(self): "Testing the `Extent` aggregate on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Extent('location__point')) # One for all locations, one that excludes New Mexico (Roswell). all_extent = (-104.528056, 29.763374, -79.460734, 40.18476) txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476) e1 = City.objects.aggregate(Extent('location__point'))['location__point__extent'] e2 = City.objects.exclude(state='NM').aggregate(Extent('location__point'))['location__point__extent'] e3 = aggs['location__point__extent'] # The tolerance value is to four decimal places because of differences # between the Oracle and PostGIS spatial backends on the extent calculation. tol = 4 for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]: for ref_val, e_val in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol) @skipUnlessDBFeature("supports_extent_aggr") def test_related_extent_annotate(self): """ Test annotation with Extent GeoAggregate. """ cities = City.objects.annotate(points_extent=Extent('location__point')).order_by('name') tol = 4 self.assertAlmostEqual( cities[0].points_extent, (-97.516111, 33.058333, -97.516111, 33.058333), tol ) @skipUnlessDBFeature('supports_union_aggr') def test_related_union_aggregate(self): "Testing the `Union` aggregate on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Union('location__point')) # These are the points that are components of the aggregate geographic # union that is returned. Each point # corresponds to City PK. p1 = Point(-104.528056, 33.387222) p2 = Point(-97.516111, 33.058333) p3 = Point(-79.460734, 40.18476) p4 = Point(-96.801611, 32.782057) p5 = Point(-95.363151, 29.763374) # The second union aggregate is for a union # query that includes limiting information in the WHERE clause (in other # words a `.filter()` precedes the call to `.aggregate(Union()`). ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.aggregate(Union('location__point'))['location__point__union'] u2 = City.objects.exclude( name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth'), ).aggregate(Union('location__point'))['location__point__union'] u3 = aggs['location__point__union'] self.assertEqual(type(u1), MultiPoint) self.assertEqual(type(u3), MultiPoint) # Ordering of points in the result of the union is not defined and # implementation-dependent (DB backend, GEOS version) self.assertEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1}) self.assertEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2}) self.assertEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3}) def test05_select_related_fk_to_subclass(self): "Testing that calling select_related on a query over a model with an FK to a model subclass works" # Regression test for #9752. list(DirectoryEntry.objects.all().select_related()) def test06_f_expressions(self): "Testing F() expressions on GeometryFields." # Constructing a dummy parcel border and getting the City instance for # assigning the FK. b1 = GEOSGeometry( 'POLYGON((-97.501205 33.052520,-97.501205 33.052576,' '-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))', srid=4326 ) pcity = City.objects.get(name='Aurora') # First parcel has incorrect center point that is equal to the City; # it also has a second border that is different from the first as a # 100ft buffer around the City. c1 = pcity.location.point c2 = c1.transform(2276, clone=True) b2 = c2.buffer(100) Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2) # Now creating a second Parcel where the borders are the same, just # in different coordinate systems. The center points are also the # same (but in different coordinate systems), and this time they # actually correspond to the centroid of the border. c1 = b1.centroid c2 = c1.transform(2276, clone=True) b2 = b1 if connection.features.supports_transform else b1.transform(2276, clone=True) Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2) # Should return the second Parcel, which has the center within the # border. qs = Parcel.objects.filter(center1__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) # This time center2 is in a different coordinate system and needs to be # wrapped in transformation SQL. qs = Parcel.objects.filter(center2__within=F('border1')) if connection.features.supports_transform: self.assertEqual('P2', qs.get().name) else: msg = "This backend doesn't support the Transform function." with self.assertRaisesMessage(NotSupportedError, msg): list(qs) # Should return the first Parcel, which has the center point equal # to the point in the City ForeignKey. qs = Parcel.objects.filter(center1=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) # This time the city column should be wrapped in transformation SQL. qs = Parcel.objects.filter(border2__contains=F('city__location__point')) if connection.features.supports_transform: self.assertEqual('P1', qs.get().name) else: msg = "This backend doesn't support the Transform function." with self.assertRaisesMessage(NotSupportedError, msg): list(qs) def test07_values(self): "Testing values() and values_list()." gqs = Location.objects.all() gvqs = Location.objects.values() gvlqs = Location.objects.values_list() # Incrementing through each of the models, dictionaries, and tuples # returned by each QuerySet. for m, d, t in zip(gqs, gvqs, gvlqs): # The values should be Geometry objects and not raw strings returned # by the spatial database. self.assertIsInstance(d['point'], GEOSGeometry) self.assertIsInstance(t[1], GEOSGeometry) self.assertEqual(m.point, d['point']) self.assertEqual(m.point, t[1]) @override_settings(USE_TZ=True) def test_07b_values(self): "Testing values() and values_list() with aware datetime. See #21565." Event.objects.create(name="foo", when=timezone.now()) list(Event.objects.values_list('when')) def test08_defer_only(self): "Testing defer() and only() on Geographic models." qs = Location.objects.all() def_qs = Location.objects.defer('point') for loc, def_loc in zip(qs, def_qs): self.assertEqual(loc.point, def_loc.point) def test09_pk_relations(self): "Ensuring correct primary key column is selected across relations. See #10757." # The expected ID values -- notice the last two location IDs # are out of order. Dallas and Houston have location IDs that differ # from their PKs -- this is done to ensure that the related location # ID column is selected instead of ID column for the city. city_ids = (1, 2, 3, 4, 5) loc_ids = (1, 2, 3, 5, 4) ids_qs = City.objects.order_by('id').values('id', 'location__id') for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids): self.assertEqual(val_dict['id'], c_id) self.assertEqual(val_dict['location__id'], l_id) # TODO: fix on Oracle -- qs2 returns an empty result for an unknown reason @no_oracle def test10_combine(self): "Testing the combination of two QuerySets (#10807)." buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1) buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1) qs1 = City.objects.filter(location__point__within=buf1) qs2 = City.objects.filter(location__point__within=buf2) combined = qs1 | qs2 names = [c.name for c in combined] self.assertEqual(2, len(names)) self.assertIn('Aurora', names) self.assertIn('Kecksburg', names) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test12a_count(self): "Testing `Count` aggregate on geo-fields." # The City, 'Fort Worth' uses the same location as Dallas. dallas = City.objects.get(name='Dallas') # Count annotation should be 2 for the Dallas location now. loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id) self.assertEqual(2, loc.num_cities) def test12b_count(self): "Testing `Count` aggregate on non geo-fields." # Should only be one author (Trevor Paglen) returned by this query, and # the annotation should have 3 for the number of books, see #11087. # Also testing with a values(), see #11489. qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1) vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1) self.assertEqual(1, len(qs)) self.assertEqual(3, qs[0].num_books) self.assertEqual(1, len(vqs)) self.assertEqual(3, vqs[0]['num_books']) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test13c_count(self): "Testing `Count` aggregate with `.values()`. See #15305." qs = Location.objects.filter(id=5).annotate(num_cities=Count('city')).values('id', 'point', 'num_cities') self.assertEqual(1, len(qs)) self.assertEqual(2, qs[0]['num_cities']) self.assertIsInstance(qs[0]['point'], GEOSGeometry) # TODO: The phantom model does appear on Oracle. @no_oracle def test13_select_related_null_fk(self): "Testing `select_related` on a nullable ForeignKey." Book.objects.create(title='Without Author') b = Book.objects.select_related('author').get(title='Without Author') # Should be `None`, and not a 'dummy' model. self.assertIsNone(b.author) @skipUnlessDBFeature("supports_collect_aggr") def test_collect(self): """ Testing the `Collect` aggregate. """ # Reference query: # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id") # WHERE "relatedapp_city"."state" = 'TX'; ref_geom = GEOSGeometry( 'MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,' '-95.363151 29.763374,-96.801611 32.782057)' ) coll = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect'] # Even though Dallas and Ft. Worth share same point, Collect doesn't # consolidate -- that's why 4 points in MultiPoint. self.assertEqual(4, len(coll)) self.assertTrue(ref_geom.equals(coll)) def test15_invalid_select_related(self): "Testing doing select_related on the related name manager of a unique FK. See #13934." qs = Article.objects.select_related('author__article') # This triggers TypeError when `get_default_columns` has no `local_only` # keyword. The TypeError is swallowed if QuerySet is actually # evaluated as list generation swallows TypeError in CPython. str(qs.query) def test16_annotated_date_queryset(self): "Ensure annotated date querysets work if spatial backend is used. See #14648." birth_years = [dt.year for dt in list(Author.objects.annotate(num_books=Count('books')).dates('dob', 'year'))] birth_years.sort() self.assertEqual([1950, 1974], birth_years) # TODO: Related tests for KML, GML, and distance lookups.
b4c79175ac847e0210c70c1bdbab0b80bc036263bc9ea13dc122992d03daeeb7
import os import shutil import struct import tempfile from django.contrib.gis.gdal import GDAL_VERSION, GDALRaster from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.raster.band import GDALBand from django.contrib.gis.shortcuts import numpy from django.test import SimpleTestCase from ..data.rasters.textrasters import JSON_RASTER class GDALRasterTests(SimpleTestCase): """ Test a GDALRaster instance created from a file (GeoTiff). """ def setUp(self): self.rs_path = os.path.join(os.path.dirname(__file__), '../data/rasters/raster.tif') self.rs = GDALRaster(self.rs_path) def test_rs_name_repr(self): self.assertEqual(self.rs_path, self.rs.name) self.assertRegex(repr(self.rs), r"<Raster object at 0x\w+>") def test_rs_driver(self): self.assertEqual(self.rs.driver.name, 'GTiff') def test_rs_size(self): self.assertEqual(self.rs.width, 163) self.assertEqual(self.rs.height, 174) def test_rs_srs(self): self.assertEqual(self.rs.srs.srid, 3086) self.assertEqual(self.rs.srs.units, (1.0, 'metre')) def test_rs_srid(self): rast = GDALRaster({ 'width': 16, 'height': 16, 'srid': 4326, }) self.assertEqual(rast.srid, 4326) rast.srid = 3086 self.assertEqual(rast.srid, 3086) def test_geotransform_and_friends(self): # Assert correct values for file based raster self.assertEqual( self.rs.geotransform, [511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0] ) self.assertEqual(self.rs.origin, [511700.4680706557, 435103.3771231986]) self.assertEqual(self.rs.origin.x, 511700.4680706557) self.assertEqual(self.rs.origin.y, 435103.3771231986) self.assertEqual(self.rs.scale, [100.0, -100.0]) self.assertEqual(self.rs.scale.x, 100.0) self.assertEqual(self.rs.scale.y, -100.0) self.assertEqual(self.rs.skew, [0, 0]) self.assertEqual(self.rs.skew.x, 0) self.assertEqual(self.rs.skew.y, 0) # Create in-memory rasters and change gtvalues rsmem = GDALRaster(JSON_RASTER) # geotransform accepts both floats and ints rsmem.geotransform = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] self.assertEqual(rsmem.geotransform, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) rsmem.geotransform = range(6) self.assertEqual(rsmem.geotransform, [float(x) for x in range(6)]) self.assertEqual(rsmem.origin, [0, 3]) self.assertEqual(rsmem.origin.x, 0) self.assertEqual(rsmem.origin.y, 3) self.assertEqual(rsmem.scale, [1, 5]) self.assertEqual(rsmem.scale.x, 1) self.assertEqual(rsmem.scale.y, 5) self.assertEqual(rsmem.skew, [2, 4]) self.assertEqual(rsmem.skew.x, 2) self.assertEqual(rsmem.skew.y, 4) self.assertEqual(rsmem.width, 5) self.assertEqual(rsmem.height, 5) def test_geotransform_bad_inputs(self): rsmem = GDALRaster(JSON_RASTER) error_geotransforms = [ [1, 2], [1, 2, 3, 4, 5, 'foo'], [1, 2, 3, 4, 5, 6, 'foo'], ] msg = 'Geotransform must consist of 6 numeric values.' for geotransform in error_geotransforms: with self.subTest(i=geotransform), self.assertRaisesMessage(ValueError, msg): rsmem.geotransform = geotransform def test_rs_extent(self): self.assertEqual( self.rs.extent, (511700.4680706557, 417703.3771231986, 528000.4680706557, 435103.3771231986) ) def test_rs_bands(self): self.assertEqual(len(self.rs.bands), 1) self.assertIsInstance(self.rs.bands[0], GDALBand) def test_memory_based_raster_creation(self): # Create uint8 raster with full pixel data range (0-255) rast = GDALRaster({ 'datatype': 1, 'width': 16, 'height': 16, 'srid': 4326, 'bands': [{ 'data': range(256), 'nodata_value': 255, }], }) # Get array from raster result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # Assert data is same as original input self.assertEqual(result, list(range(256))) def test_file_based_raster_creation(self): # Prepare tempfile rstfile = tempfile.NamedTemporaryFile(suffix='.tif') # Create file-based raster from scratch GDALRaster({ 'datatype': self.rs.bands[0].datatype(), 'driver': 'tif', 'name': rstfile.name, 'width': 163, 'height': 174, 'nr_of_bands': 1, 'srid': self.rs.srs.wkt, 'origin': (self.rs.origin.x, self.rs.origin.y), 'scale': (self.rs.scale.x, self.rs.scale.y), 'skew': (self.rs.skew.x, self.rs.skew.y), 'bands': [{ 'data': self.rs.bands[0].data(), 'nodata_value': self.rs.bands[0].nodata_value, }], }) # Reload newly created raster from file restored_raster = GDALRaster(rstfile.name) self.assertEqual(restored_raster.srs.wkt, self.rs.srs.wkt) self.assertEqual(restored_raster.geotransform, self.rs.geotransform) if numpy: numpy.testing.assert_equal( restored_raster.bands[0].data(), self.rs.bands[0].data() ) else: self.assertEqual(restored_raster.bands[0].data(), self.rs.bands[0].data()) def test_vsi_raster_creation(self): # Open a raster as a file object. with open(self.rs_path, 'rb') as dat: # Instantiate a raster from the file binary buffer. vsimem = GDALRaster(dat.read()) # The data of the in-memory file is equal to the source file. result = vsimem.bands[0].data() target = self.rs.bands[0].data() if numpy: result = result.flatten().tolist() target = target.flatten().tolist() self.assertEqual(result, target) def test_vsi_raster_deletion(self): path = '/vsimem/raster.tif' # Create a vsi-based raster from scratch. vsimem = GDALRaster({ 'name': path, 'driver': 'tif', 'width': 4, 'height': 4, 'srid': 4326, 'bands': [{ 'data': range(16), }], }) # The virtual file exists. rst = GDALRaster(path) self.assertEqual(rst.width, 4) # Delete GDALRaster. del vsimem del rst # The virtual file has been removed. msg = 'Could not open the datasource at "/vsimem/raster.tif"' with self.assertRaisesMessage(GDALException, msg): GDALRaster(path) def test_vsi_invalid_buffer_error(self): msg = 'Failed creating VSI raster from the input buffer.' with self.assertRaisesMessage(GDALException, msg): GDALRaster(b'not-a-raster-buffer') def test_vsi_buffer_property(self): # Create a vsi-based raster from scratch. rast = GDALRaster({ 'name': '/vsimem/raster.tif', 'driver': 'tif', 'width': 4, 'height': 4, 'srid': 4326, 'bands': [{ 'data': range(16), }], }) # Do a round trip from raster to buffer to raster. result = GDALRaster(rast.vsi_buffer).bands[0].data() if numpy: result = result.flatten().tolist() # Band data is equal to nodata value except on input block of ones. self.assertEqual(result, list(range(16))) # The vsi buffer is None for rasters that are not vsi based. self.assertIsNone(self.rs.vsi_buffer) def test_offset_size_and_shape_on_raster_creation(self): rast = GDALRaster({ 'datatype': 1, 'width': 4, 'height': 4, 'srid': 4326, 'bands': [{ 'data': (1,), 'offset': (1, 1), 'size': (2, 2), 'shape': (1, 1), 'nodata_value': 2, }], }) # Get array from raster. result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # Band data is equal to nodata value except on input block of ones. self.assertEqual( result, [2, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2] ) def test_set_nodata_value_on_raster_creation(self): # Create raster filled with nodata values. rast = GDALRaster({ 'datatype': 1, 'width': 2, 'height': 2, 'srid': 4326, 'bands': [{'nodata_value': 23}], }) # Get array from raster. result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # All band data is equal to nodata value. self.assertEqual(result, [23] * 4) def test_set_nodata_none_on_raster_creation(self): if GDAL_VERSION < (2, 1): self.skipTest("GDAL >= 2.1 is required for this test.") # Create raster without data and without nodata value. rast = GDALRaster({ 'datatype': 1, 'width': 2, 'height': 2, 'srid': 4326, 'bands': [{'nodata_value': None}], }) # Get array from raster. result = rast.bands[0].data() if numpy: result = result.flatten().tolist() # Band data is equal to zero because no nodata value has been specified. self.assertEqual(result, [0] * 4) def test_raster_metadata_property(self): data = self.rs.metadata self.assertEqual(data['DEFAULT'], {'AREA_OR_POINT': 'Area'}) self.assertEqual(data['IMAGE_STRUCTURE'], {'INTERLEAVE': 'BAND'}) # Create file-based raster from scratch source = GDALRaster({ 'datatype': 1, 'width': 2, 'height': 2, 'srid': 4326, 'bands': [{'data': range(4), 'nodata_value': 99}], }) # Set metadata on raster and on a band. metadata = { 'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0', 'AREA_OR_POINT': 'Point'}, } source.metadata = metadata source.bands[0].metadata = metadata self.assertEqual(source.metadata['DEFAULT'], metadata['DEFAULT']) self.assertEqual(source.bands[0].metadata['DEFAULT'], metadata['DEFAULT']) # Update metadata on raster. metadata = { 'DEFAULT': {'VERSION': '2.0'}, } source.metadata = metadata self.assertEqual(source.metadata['DEFAULT']['VERSION'], '2.0') # Remove metadata on raster. metadata = { 'DEFAULT': {'OWNER': None}, } source.metadata = metadata self.assertNotIn('OWNER', source.metadata['DEFAULT']) def test_raster_info_accessor(self): if GDAL_VERSION < (2, 1): msg = 'GDAL ≥ 2.1 is required for using the info property.' with self.assertRaisesMessage(ValueError, msg): self.rs.info return gdalinfo = """ Driver: GTiff/GeoTIFF Files: {0} Size is 163, 174 Coordinate System is: PROJCS["NAD83 / Florida GDL Albers", GEOGCS["NAD83", DATUM["North_American_Datum_1983", SPHEROID["GRS 1980",6378137,298.257222101, AUTHORITY["EPSG","7019"]], TOWGS84[0,0,0,0,0,0,0], AUTHORITY["EPSG","6269"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.0174532925199433, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4269"]], PROJECTION["Albers_Conic_Equal_Area"], PARAMETER["standard_parallel_1",24], PARAMETER["standard_parallel_2",31.5], PARAMETER["latitude_of_center",24], PARAMETER["longitude_of_center",-84], PARAMETER["false_easting",400000], PARAMETER["false_northing",0], UNIT["metre",1, AUTHORITY["EPSG","9001"]], AXIS["X",EAST], AXIS["Y",NORTH], AUTHORITY["EPSG","3086"]] Origin = (511700.468070655711927,435103.377123198588379) Pixel Size = (100.000000000000000,-100.000000000000000) Metadata: AREA_OR_POINT=Area Image Structure Metadata: INTERLEAVE=BAND Corner Coordinates: Upper Left ( 511700.468, 435103.377) ( 82d51'46.16"W, 27d55' 1.53"N) Lower Left ( 511700.468, 417703.377) ( 82d51'52.04"W, 27d45'37.50"N) Upper Right ( 528000.468, 435103.377) ( 82d41'48.81"W, 27d54'56.30"N) Lower Right ( 528000.468, 417703.377) ( 82d41'55.54"W, 27d45'32.28"N) Center ( 519850.468, 426403.377) ( 82d46'50.64"W, 27d50'16.99"N) Band 1 Block=163x50 Type=Byte, ColorInterp=Gray NoData Value=15 """.format(self.rs_path) # Data info_dyn = [line.strip() for line in self.rs.info.split('\n') if line.strip() != ''] info_ref = [line.strip() for line in gdalinfo.split('\n') if line.strip() != ''] self.assertEqual(info_dyn, info_ref) def test_compressed_file_based_raster_creation(self): rstfile = tempfile.NamedTemporaryFile(suffix='.tif') # Make a compressed copy of an existing raster. compressed = self.rs.warp({'papsz_options': {'compress': 'packbits'}, 'name': rstfile.name}) # Check physically if compression worked. self.assertLess(os.path.getsize(compressed.name), os.path.getsize(self.rs.name)) # Create file-based raster with options from scratch. compressed = GDALRaster({ 'datatype': 1, 'driver': 'tif', 'name': rstfile.name, 'width': 40, 'height': 40, 'srid': 3086, 'origin': (500000, 400000), 'scale': (100, -100), 'skew': (0, 0), 'bands': [{ 'data': range(40 ^ 2), 'nodata_value': 255, }], 'papsz_options': { 'compress': 'packbits', 'pixeltype': 'signedbyte', 'blockxsize': 23, 'blockysize': 23, } }) # Check if options used on creation are stored in metadata. # Reopening the raster ensures that all metadata has been written # to the file. compressed = GDALRaster(compressed.name) self.assertEqual(compressed.metadata['IMAGE_STRUCTURE']['COMPRESSION'], 'PACKBITS',) self.assertEqual(compressed.bands[0].metadata['IMAGE_STRUCTURE']['PIXELTYPE'], 'SIGNEDBYTE') if GDAL_VERSION >= (2, 1): self.assertIn('Block=40x23', compressed.info) def test_raster_warp(self): # Create in memory raster source = GDALRaster({ 'datatype': 1, 'driver': 'MEM', 'name': 'sourceraster', 'width': 4, 'height': 4, 'nr_of_bands': 1, 'srid': 3086, 'origin': (500000, 400000), 'scale': (100, -100), 'skew': (0, 0), 'bands': [{ 'data': range(16), 'nodata_value': 255, }], }) # Test altering the scale, width, and height of a raster data = { 'scale': [200, -200], 'width': 2, 'height': 2, } target = source.warp(data) self.assertEqual(target.width, data['width']) self.assertEqual(target.height, data['height']) self.assertEqual(target.scale, data['scale']) self.assertEqual(target.bands[0].datatype(), source.bands[0].datatype()) self.assertEqual(target.name, 'sourceraster_copy.MEM') result = target.bands[0].data() if numpy: result = result.flatten().tolist() self.assertEqual(result, [5, 7, 13, 15]) # Test altering the name and datatype (to float) data = { 'name': '/path/to/targetraster.tif', 'datatype': 6, } target = source.warp(data) self.assertEqual(target.bands[0].datatype(), 6) self.assertEqual(target.name, '/path/to/targetraster.tif') self.assertEqual(target.driver.name, 'MEM') result = target.bands[0].data() if numpy: result = result.flatten().tolist() self.assertEqual( result, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0] ) def test_raster_warp_nodata_zone(self): # Create in memory raster. source = GDALRaster({ 'datatype': 1, 'driver': 'MEM', 'width': 4, 'height': 4, 'srid': 3086, 'origin': (500000, 400000), 'scale': (100, -100), 'skew': (0, 0), 'bands': [{ 'data': range(16), 'nodata_value': 23, }], }) # Warp raster onto a location that does not cover any pixels of the original. result = source.warp({'origin': (200000, 200000)}).bands[0].data() if numpy: result = result.flatten().tolist() # The result is an empty raster filled with the correct nodata value. self.assertEqual(result, [23] * 16) def test_raster_transform(self): # Prepare tempfile and nodata value rstfile = tempfile.NamedTemporaryFile(suffix='.tif') ndv = 99 # Create in file based raster source = GDALRaster({ 'datatype': 1, 'driver': 'tif', 'name': rstfile.name, 'width': 5, 'height': 5, 'nr_of_bands': 1, 'srid': 4326, 'origin': (-5, 5), 'scale': (2, -2), 'skew': (0, 0), 'bands': [{ 'data': range(25), 'nodata_value': ndv, }], }) # Transform raster into srid 4326. target = source.transform(3086) # Reload data from disk target = GDALRaster(target.name) self.assertEqual(target.srs.srid, 3086) self.assertEqual(target.width, 7) self.assertEqual(target.height, 7) self.assertEqual(target.bands[0].datatype(), source.bands[0].datatype()) self.assertAlmostEqual(target.origin[0], 9124842.791079799, 3) self.assertAlmostEqual(target.origin[1], 1589911.6476407414, 3) self.assertAlmostEqual(target.scale[0], 223824.82664250192, 3) self.assertAlmostEqual(target.scale[1], -223824.82664250192, 3) self.assertEqual(target.skew, [0, 0]) result = target.bands[0].data() if numpy: result = result.flatten().tolist() # The reprojection of a raster that spans over a large area # skews the data matrix and might introduce nodata values. self.assertEqual( result, [ ndv, ndv, ndv, ndv, 4, ndv, ndv, ndv, ndv, 2, 3, 9, ndv, ndv, ndv, 1, 2, 8, 13, 19, ndv, 0, 6, 6, 12, 18, 18, 24, ndv, 10, 11, 16, 22, 23, ndv, ndv, ndv, 15, 21, 22, ndv, ndv, ndv, ndv, 20, ndv, ndv, ndv, ndv, ] ) class GDALBandTests(SimpleTestCase): rs_path = os.path.join(os.path.dirname(__file__), '../data/rasters/raster.tif') def test_band_data(self): rs = GDALRaster(self.rs_path) band = rs.bands[0] self.assertEqual(band.width, 163) self.assertEqual(band.height, 174) self.assertEqual(band.description, '') self.assertEqual(band.datatype(), 1) self.assertEqual(band.datatype(as_string=True), 'GDT_Byte') self.assertEqual(band.color_interp(), 1) self.assertEqual(band.color_interp(as_string=True), 'GCI_GrayIndex') self.assertEqual(band.nodata_value, 15) if numpy: data = band.data() assert_array = numpy.loadtxt( os.path.join(os.path.dirname(__file__), '../data/rasters/raster.numpy.txt') ) numpy.testing.assert_equal(data, assert_array) self.assertEqual(data.shape, (band.height, band.width)) def test_band_statistics(self): with tempfile.TemporaryDirectory() as tmp_dir: rs_path = os.path.join(tmp_dir, 'raster.tif') shutil.copyfile(self.rs_path, rs_path) rs = GDALRaster(rs_path) band = rs.bands[0] pam_file = rs_path + '.aux.xml' smin, smax, smean, sstd = band.statistics(approximate=True) self.assertEqual(smin, 0) self.assertEqual(smax, 9) self.assertAlmostEqual(smean, 2.842331288343558) self.assertAlmostEqual(sstd, 2.3965567248965356) smin, smax, smean, sstd = band.statistics(approximate=False, refresh=True) self.assertEqual(smin, 0) self.assertEqual(smax, 9) self.assertAlmostEqual(smean, 2.828326634228898) self.assertAlmostEqual(sstd, 2.4260526986669095) self.assertEqual(band.min, 0) self.assertEqual(band.max, 9) self.assertAlmostEqual(band.mean, 2.828326634228898) self.assertAlmostEqual(band.std, 2.4260526986669095) # Statistics are persisted into PAM file on band close rs = band = None self.assertTrue(os.path.isfile(pam_file)) def test_read_mode_error(self): # Open raster in read mode rs = GDALRaster(self.rs_path, write=False) band = rs.bands[0] # Setting attributes in write mode raises exception in the _flush method with self.assertRaises(GDALException): setattr(band, 'nodata_value', 10) def test_band_data_setters(self): # Create in-memory raster and get band rsmem = GDALRaster({ 'datatype': 1, 'driver': 'MEM', 'name': 'mem_rst', 'width': 10, 'height': 10, 'nr_of_bands': 1, 'srid': 4326, }) bandmem = rsmem.bands[0] # Set nodata value bandmem.nodata_value = 99 self.assertEqual(bandmem.nodata_value, 99) # Set data for entire dataset bandmem.data(range(100)) if numpy: numpy.testing.assert_equal(bandmem.data(), numpy.arange(100).reshape(10, 10)) else: self.assertEqual(bandmem.data(), list(range(100))) # Prepare data for setting values in subsequent tests block = list(range(100, 104)) packed_block = struct.pack('<' + 'B B B B', *block) # Set data from list bandmem.data(block, (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from packed block bandmem.data(packed_block, (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from bytes bandmem.data(bytes(packed_block), (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from bytearray bandmem.data(bytearray(packed_block), (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from memoryview bandmem.data(memoryview(packed_block), (1, 1), (2, 2)) result = bandmem.data(offset=(1, 1), size=(2, 2)) if numpy: numpy.testing.assert_equal(result, numpy.array(block).reshape(2, 2)) else: self.assertEqual(result, block) # Set data from numpy array if numpy: bandmem.data(numpy.array(block, dtype='int8').reshape(2, 2), (1, 1), (2, 2)) numpy.testing.assert_equal( bandmem.data(offset=(1, 1), size=(2, 2)), numpy.array(block).reshape(2, 2) ) # Test json input data rsmemjson = GDALRaster(JSON_RASTER) bandmemjson = rsmemjson.bands[0] if numpy: numpy.testing.assert_equal( bandmemjson.data(), numpy.array(range(25)).reshape(5, 5) ) else: self.assertEqual(bandmemjson.data(), list(range(25))) def test_band_statistics_automatic_refresh(self): rsmem = GDALRaster({ 'srid': 4326, 'width': 2, 'height': 2, 'bands': [{'data': [0] * 4, 'nodata_value': 99}], }) band = rsmem.bands[0] # Populate statistics cache self.assertEqual(band.statistics(), (0, 0, 0, 0)) # Change data band.data([1, 1, 0, 0]) # Statistics are properly updated self.assertEqual(band.statistics(), (0.0, 1.0, 0.5, 0.5)) # Change nodata_value band.nodata_value = 0 # Statistics are properly updated self.assertEqual(band.statistics(), (1.0, 1.0, 1.0, 0.0)) def test_band_statistics_empty_band(self): rsmem = GDALRaster({ 'srid': 4326, 'width': 1, 'height': 1, 'bands': [{'data': [0], 'nodata_value': 0}], }) self.assertEqual(rsmem.bands[0].statistics(), (None, None, None, None)) def test_band_delete_nodata(self): rsmem = GDALRaster({ 'srid': 4326, 'width': 1, 'height': 1, 'bands': [{'data': [0], 'nodata_value': 1}], }) if GDAL_VERSION < (2, 1): msg = 'GDAL >= 2.1 required to delete nodata values.' with self.assertRaisesMessage(ValueError, msg): rsmem.bands[0].nodata_value = None else: rsmem.bands[0].nodata_value = None self.assertIsNone(rsmem.bands[0].nodata_value) def test_band_data_replication(self): band = GDALRaster({ 'srid': 4326, 'width': 3, 'height': 3, 'bands': [{'data': range(10, 19), 'nodata_value': 0}], }).bands[0] # Variations for input (data, shape, expected result). combos = ( ([1], (1, 1), [1] * 9), (range(3), (1, 3), [0, 0, 0, 1, 1, 1, 2, 2, 2]), (range(3), (3, 1), [0, 1, 2, 0, 1, 2, 0, 1, 2]), ) for combo in combos: band.data(combo[0], shape=combo[1]) if numpy: numpy.testing.assert_equal(band.data(), numpy.array(combo[2]).reshape(3, 3)) else: self.assertEqual(band.data(), list(combo[2]))
d0b928a2cd1fe422c3a64a5526d3f40bba3886f0c869404eab931fe90fd180df
import os import re from datetime import datetime from django.contrib.gis.gdal import ( DataSource, Envelope, GDALException, OGRGeometry, ) from django.contrib.gis.gdal.field import ( OFTDateTime, OFTInteger, OFTReal, OFTString, ) from django.test import SimpleTestCase from ..test_data import TEST_DATA, TestDS, get_ds_file wgs_84_wkt = ( 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",' '6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",' '0.017453292519943295]]' ) # Using a regex because of small differences depending on GDAL versions. wgs_84_wkt_regex = r'^GEOGCS\["(GCS_)?WGS[ _](19)?84".*$' datetime_format = '%Y-%m-%dT%H:%M:%S' # List of acceptable data sources. ds_list = ( TestDS( 'test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile', fields={'dbl': OFTReal, 'int': OFTInteger, 'str': OFTString}, extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS srs_wkt=wgs_84_wkt, field_values={ 'dbl': [float(i) for i in range(1, 6)], 'int': list(range(1, 6)), 'str': [str(i) for i in range(1, 6)], }, fids=range(5) ), TestDS( 'test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', driver='OGR_VRT', fields={ 'POINT_X': OFTString, 'POINT_Y': OFTString, 'NUM': OFTString, }, # VRT uses CSV, which all types are OFTString. extent=(1.0, 2.0, 100.0, 523.5), # Min/Max from CSV field_values={ 'POINT_X': ['1.0', '5.0', '100.0'], 'POINT_Y': ['2.0', '23.0', '523.5'], 'NUM': ['5', '17', '23'], }, fids=range(1, 4) ), TestDS( 'test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3, driver='ESRI Shapefile', fields={'float': OFTReal, 'int': OFTInteger, 'str': OFTString}, extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS srs_wkt=wgs_84_wkt, ), TestDS( 'has_nulls', nfeat=3, nfld=6, geom='POLYGON', gtype=3, driver='GeoJSON', ext='geojson', fields={ 'uuid': OFTString, 'name': OFTString, 'num': OFTReal, 'integer': OFTInteger, 'datetime': OFTDateTime, 'boolean': OFTInteger, }, extent=(-75.274200, 39.846504, -74.959717, 40.119040), # Got extent from QGIS field_values={ 'uuid': [ '1378c26f-cbe6-44b0-929f-eb330d4991f5', 'fa2ba67c-a135-4338-b924-a9622b5d869f', '4494c1f3-55ab-4256-b365-12115cb388d5', ], 'name': ['Philadelphia', None, 'north'], 'num': [1.001, None, 0.0], 'integer': [5, None, 8], 'boolean': [True, None, False], 'datetime': [ datetime.strptime('1994-08-14T11:32:14', datetime_format), None, datetime.strptime('2018-11-29T03:02:52', datetime_format), ] }, fids=range(3), ), ) bad_ds = (TestDS('foo'),) class DataSourceTest(SimpleTestCase): def test01_valid_shp(self): "Testing valid SHP Data Source files." for source in ds_list: # Loading up the data source ds = DataSource(source.ds) # Making sure the layer count is what's expected (only 1 layer in a SHP file) self.assertEqual(1, len(ds)) # Making sure GetName works self.assertEqual(source.ds, ds.name) # Making sure the driver name matches up self.assertEqual(source.driver, str(ds.driver)) # Making sure indexing works msg = 'Index out of range when accessing layers in a datasource: %s.' with self.assertRaisesMessage(IndexError, msg % len(ds)): ds.__getitem__(len(ds)) with self.assertRaisesMessage(IndexError, 'Invalid OGR layer name given: invalid.'): ds.__getitem__('invalid') def test02_invalid_shp(self): "Testing invalid SHP files for the Data Source." for source in bad_ds: with self.assertRaises(GDALException): DataSource(source.ds) def test03a_layers(self): "Testing Data Source Layers." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer, this tests DataSource.__iter__ for layer in ds: # Making sure we get the number of features we expect self.assertEqual(len(layer), source.nfeat) # Making sure we get the number of fields we expect self.assertEqual(source.nfld, layer.num_fields) self.assertEqual(source.nfld, len(layer.fields)) # Testing the layer's extent (an Envelope), and its properties self.assertIsInstance(layer.extent, Envelope) self.assertAlmostEqual(source.extent[0], layer.extent.min_x, 5) self.assertAlmostEqual(source.extent[1], layer.extent.min_y, 5) self.assertAlmostEqual(source.extent[2], layer.extent.max_x, 5) self.assertAlmostEqual(source.extent[3], layer.extent.max_y, 5) # Now checking the field names. flds = layer.fields for f in flds: self.assertIn(f, source.fields) # Negative FIDs are not allowed. with self.assertRaisesMessage(IndexError, 'Negative indices are not allowed on OGR Layers.'): layer.__getitem__(-1) with self.assertRaisesMessage(IndexError, 'Invalid feature id: 50000.'): layer.__getitem__(50000) if hasattr(source, 'field_values'): # Testing `Layer.get_fields` (which uses Layer.__iter__) for fld_name, fld_value in source.field_values.items(): self.assertEqual(fld_value, layer.get_fields(fld_name)) # Testing `Layer.__getitem__`. for i, fid in enumerate(source.fids): feat = layer[fid] self.assertEqual(fid, feat.fid) # Maybe this should be in the test below, but we might as well test # the feature values here while in this loop. for fld_name, fld_value in source.field_values.items(): self.assertEqual(fld_value[i], feat.get(fld_name)) msg = 'Index out of range when accessing field in a feature: %s.' with self.assertRaisesMessage(IndexError, msg % len(feat)): feat.__getitem__(len(feat)) with self.assertRaisesMessage(IndexError, 'Invalid OFT field name given: invalid.'): feat.__getitem__('invalid') def test03b_layer_slice(self): "Test indexing and slicing on Layers." # Using the first data-source because the same slice # can be used for both the layer and the control values. source = ds_list[0] ds = DataSource(source.ds) sl = slice(1, 3) feats = ds[0][sl] for fld_name in ds[0].fields: test_vals = [feat.get(fld_name) for feat in feats] control_vals = source.field_values[fld_name][sl] self.assertEqual(control_vals, test_vals) def test03c_layer_references(self): """ Ensure OGR objects keep references to the objects they belong to. """ source = ds_list[0] # See ticket #9448. def get_layer(): # This DataSource object is not accessible outside this # scope. However, a reference should still be kept alive # on the `Layer` returned. ds = DataSource(source.ds) return ds[0] # Making sure we can call OGR routines on the Layer returned. lyr = get_layer() self.assertEqual(source.nfeat, len(lyr)) self.assertEqual(source.gtype, lyr.geom_type.num) # Same issue for Feature/Field objects, see #18640 self.assertEqual(str(lyr[0]['str']), "1") def test04_features(self): "Testing Data Source Features." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer for layer in ds: # Incrementing through each feature in the layer for feat in layer: # Making sure the number of fields, and the geometry type # are what's expected. self.assertEqual(source.nfld, len(list(feat))) self.assertEqual(source.gtype, feat.geom_type) # Making sure the fields match to an appropriate OFT type. for k, v in source.fields.items(): # Making sure we get the proper OGR Field instance, using # a string value index for the feature. self.assertIsInstance(feat[k], v) self.assertIsInstance(feat.fields[0], str) # Testing Feature.__iter__ for fld in feat: self.assertIn(fld.name, source.fields) def test05_geometries(self): "Testing Geometries from Data Source Features." for source in ds_list: ds = DataSource(source.ds) # Incrementing through each layer and feature. for layer in ds: for feat in layer: g = feat.geom # Making sure we get the right Geometry name & type self.assertEqual(source.geom, g.geom_name) self.assertEqual(source.gtype, g.geom_type) # Making sure the SpatialReference is as expected. if hasattr(source, 'srs_wkt'): self.assertIsNotNone(re.match(wgs_84_wkt_regex, g.srs.wkt)) def test06_spatial_filter(self): "Testing the Layer.spatial_filter property." ds = DataSource(get_ds_file('cities', 'shp')) lyr = ds[0] # When not set, it should be None. self.assertIsNone(lyr.spatial_filter) # Must be set a/an OGRGeometry or 4-tuple. with self.assertRaises(TypeError): lyr._set_spatial_filter('foo') # Setting the spatial filter with a tuple/list with the extent of # a buffer centering around Pueblo. with self.assertRaises(ValueError): lyr._set_spatial_filter(list(range(5))) filter_extent = (-105.609252, 37.255001, -103.609252, 39.255001) lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001) self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter) feats = [feat for feat in lyr] self.assertEqual(1, len(feats)) self.assertEqual('Pueblo', feats[0].get('Name')) # Setting the spatial filter with an OGRGeometry for buffer centering # around Houston. filter_geom = OGRGeometry( 'POLYGON((-96.363151 28.763374,-94.363151 28.763374,' '-94.363151 30.763374,-96.363151 30.763374,-96.363151 28.763374))' ) lyr.spatial_filter = filter_geom self.assertEqual(filter_geom, lyr.spatial_filter) feats = [feat for feat in lyr] self.assertEqual(1, len(feats)) self.assertEqual('Houston', feats[0].get('Name')) # Clearing the spatial filter by setting it to None. Now # should indicate that there are 3 features in the Layer. lyr.spatial_filter = None self.assertEqual(3, len(lyr)) def test07_integer_overflow(self): "Testing that OFTReal fields, treated as OFTInteger, do not overflow." # Using *.dbf from Census 2010 TIGER Shapefile for Texas, # which has land area ('ALAND10') stored in a Real field # with no precision. ds = DataSource(os.path.join(TEST_DATA, 'texas.dbf')) feat = ds[0][0] # Reference value obtained using `ogrinfo`. self.assertEqual(676586997978, feat.get('ALAND10'))
47d2cbe9a6771e18abe2c5a12e3d920551c7207dbf33bf74e13979a89626b4e8
from django.contrib.gis import admin from django.contrib.gis.geos import Point from django.test import SimpleTestCase, override_settings from .admin import UnmodifiableAdmin from .models import City, site @override_settings(ROOT_URLCONF='django.contrib.gis.tests.geoadmin.urls') class GeoAdminTest(SimpleTestCase): def test_ensure_geographic_media(self): geoadmin = site._registry[City] admin_js = geoadmin.media.render_js() self.assertTrue(any(geoadmin.openlayers_url in js for js in admin_js)) def test_olmap_OSM_rendering(self): delete_all_btn = """<a href="javascript:geodjango_point.clearFeatures()">Delete all Features</a>""" original_geoadmin = site._registry[City] params = original_geoadmin.get_map_widget(City._meta.get_field('point')).params result = original_geoadmin.get_map_widget(City._meta.get_field('point'))( ).render('point', Point(-79.460734, 40.18476), params) self.assertIn( """geodjango_point.layers.base = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");""", result) self.assertIn(delete_all_btn, result) site.unregister(City) site.register(City, UnmodifiableAdmin) try: geoadmin = site._registry[City] params = geoadmin.get_map_widget(City._meta.get_field('point')).params result = geoadmin.get_map_widget(City._meta.get_field('point'))( ).render('point', Point(-79.460734, 40.18476), params) self.assertNotIn(delete_all_btn, result) finally: site.unregister(City) site.register(City, original_geoadmin.__class__) def test_olmap_WMS_rendering(self): geoadmin = admin.GeoModelAdmin(City, site) result = geoadmin.get_map_widget(City._meta.get_field('point'))( ).render('point', Point(-79.460734, 40.18476)) self.assertIn( """geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", """ """"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic', format: 'image/jpeg'});""", result) def test_olwidget_has_changed(self): """ Changes are accurately noticed by OpenLayersWidget. """ geoadmin = site._registry[City] form = geoadmin.get_changelist_form(None)() has_changed = form.fields['point'].has_changed initial = Point(13.4197458572965953, 52.5194108501149799, srid=4326) data_same = "SRID=3857;POINT(1493879.2754093995 6894592.019687599)" data_almost_same = "SRID=3857;POINT(1493879.2754093990 6894592.019687590)" data_changed = "SRID=3857;POINT(1493884.0527237 6894593.8111804)" self.assertTrue(has_changed(None, data_changed)) self.assertTrue(has_changed(initial, "")) self.assertFalse(has_changed(None, "")) self.assertFalse(has_changed(initial, data_same)) self.assertFalse(has_changed(initial, data_almost_same)) self.assertTrue(has_changed(initial, data_changed)) def test_olwidget_empty_string(self): geoadmin = site._registry[City] form = geoadmin.get_changelist_form(None)({'point': ''}) with self.assertRaisesMessage(AssertionError, 'no logs'): with self.assertLogs('django.contrib.gis', 'ERROR'): output = str(form['point']) self.assertInHTML( '<textarea id="id_point" class="vWKTField required" cols="150"' ' rows="10" name="point"></textarea>', output ) def test_olwidget_invalid_string(self): geoadmin = site._registry[City] form = geoadmin.get_changelist_form(None)({'point': 'INVALID()'}) with self.assertLogs('django.contrib.gis', 'ERROR') as cm: output = str(form['point']) self.assertInHTML( '<textarea id="id_point" class="vWKTField required" cols="150"' ' rows="10" name="point"></textarea>', output ) self.assertEqual(len(cm.records), 1) self.assertEqual( cm.records[0].getMessage(), "Error creating geometry from value 'INVALID()' (String input " "unrecognized as WKT EWKT, and HEXEWKB.)" )
cf7aea23ee4690db17c417dab357ae39ca52deb078a200586a9e6022c5f2b852
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', include(admin.site.urls)), ]
12aa7ecde3e11ec2267a41ea71828d23e96357fe59363b4fbd359f7c9ac97be2
from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("--list", action="store_true", help="Print all options") def handle(self, *args, **options): pass
cb5e19c0dc0ffe9ec56da8872b329f8eed4522e0df57207f89c24756830a9888
from django.db import models class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() class Meta: app_label = 'fixtures_model_package' ordering = ('-pub_date', 'headline') def __str__(self): return self.headline
9d78a5b61d44a6626debe3a95a77a55a93cbe92308d216b8db65515e444fb336
from django.db import models from django.db.models.fields.related import ForwardManyToOneDescriptor from django.utils.translation import get_language class ArticleTranslationDescriptor(ForwardManyToOneDescriptor): """ The set of articletranslation should not set any local fields. """ def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.field.name) self.field.set_cached_value(instance, value) if value is not None and not self.field.remote_field.multiple: self.field.remote_field.set_cached_value(value, instance) class ColConstraint: # Anything with as_sql() method works in get_extra_restriction(). def __init__(self, alias, col, value): self.alias, self.col, self.value = alias, col, value def as_sql(self, compiler, connection): qn = compiler.quote_name_unless_alias return '%s.%s = %%s' % (qn(self.alias), qn(self.col)), [self.value] class ActiveTranslationField(models.ForeignObject): """ This field will allow querying and fetching the currently active translation for Article from ArticleTranslation. """ requires_unique_target = False def get_extra_restriction(self, where_class, alias, related_alias): return ColConstraint(alias, 'lang', get_language()) def get_extra_descriptor_filter(self, instance): return {'lang': get_language()} def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) setattr(cls, self.name, ArticleTranslationDescriptor(self)) class ActiveTranslationFieldWithQ(ActiveTranslationField): def get_extra_descriptor_filter(self, instance): return models.Q(lang=get_language()) class Article(models.Model): active_translation = ActiveTranslationField( 'ArticleTranslation', from_fields=['id'], to_fields=['article'], related_name='+', on_delete=models.CASCADE, null=True, ) active_translation_q = ActiveTranslationFieldWithQ( 'ArticleTranslation', from_fields=['id'], to_fields=['article'], related_name='+', on_delete=models.CASCADE, null=True, ) pub_date = models.DateField() def __str__(self): try: return self.active_translation.title except ArticleTranslation.DoesNotExist: return '[No translation found]' class NewsArticle(Article): pass class ArticleTranslation(models.Model): article = models.ForeignKey(Article, models.CASCADE) lang = models.CharField(max_length=2) title = models.CharField(max_length=100) body = models.TextField() abstract = models.TextField(null=True) class Meta: unique_together = ('article', 'lang') class ArticleTag(models.Model): article = models.ForeignKey( Article, models.CASCADE, related_name='tags', related_query_name='tag', ) name = models.CharField(max_length=255) class ArticleIdea(models.Model): articles = models.ManyToManyField( Article, related_name='ideas', related_query_name='idea_things', ) name = models.CharField(max_length=255)
a65db5dff34b97fe0356923b9c997632bc25bb763794592515141d42efede179
from unittest import mock from django.db import migrations try: from django.contrib.postgres.operations import CryptoExtension except ImportError: CryptoExtension = mock.Mock() class Migration(migrations.Migration): # Required for the SHA database functions. operations = [CryptoExtension()]
ccecdbc6cca78ce2e98ffd2264650eedb59e959268e4db7419cb7c022f151a0b
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('db_functions', '0001_setup_extensions'), ] operations = [ migrations.CreateModel( name='Author', fields=[ ('name', models.CharField(max_length=50)), ('alias', models.CharField(max_length=50, null=True, blank=True)), ('goes_by', models.CharField(max_length=50, null=True, blank=True)), ('age', models.PositiveSmallIntegerField(default=30)), ], ), migrations.CreateModel( name='Article', fields=[ ('authors', models.ManyToManyField('db_functions.Author', related_name='articles')), ('title', models.CharField(max_length=50)), ('summary', models.CharField(max_length=200, null=True, blank=True)), ('text', models.TextField()), ('written', models.DateTimeField()), ('published', models.DateTimeField(null=True, blank=True)), ('updated', models.DateTimeField(null=True, blank=True)), ('views', models.PositiveIntegerField(default=0)), ], ), migrations.CreateModel( name='Fan', fields=[ ('name', models.CharField(max_length=50)), ('age', models.PositiveSmallIntegerField(default=30)), ('author', models.ForeignKey('db_functions.Author', models.CASCADE, related_name='fans')), ('fan_since', models.DateTimeField(null=True, blank=True)), ], ), migrations.CreateModel( name='DTModel', fields=[ ('name', models.CharField(max_length=32)), ('start_datetime', models.DateTimeField(null=True, blank=True)), ('end_datetime', models.DateTimeField(null=True, blank=True)), ('start_date', models.DateField(null=True, blank=True)), ('end_date', models.DateField(null=True, blank=True)), ('start_time', models.TimeField(null=True, blank=True)), ('end_time', models.TimeField(null=True, blank=True)), ('duration', models.DurationField(null=True, blank=True)), ], ), migrations.CreateModel( name='DecimalModel', fields=[ ('n1', models.DecimalField(decimal_places=2, max_digits=6)), ('n2', models.DecimalField(decimal_places=2, max_digits=6)), ], ), migrations.CreateModel( name='IntegerModel', fields=[ ('big', models.BigIntegerField(null=True, blank=True)), ('normal', models.IntegerField(null=True, blank=True)), ('small', models.SmallIntegerField(null=True, blank=True)), ], ), migrations.CreateModel( name='FloatModel', fields=[ ('f1', models.FloatField(null=True, blank=True)), ('f2', models.FloatField(null=True, blank=True)), ], ), ]
1a9a43b6df640fbe6645bb0d881a940965c7c92846e8fa765ffda348717d6b30
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA512 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA512Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create([ Author(alias='John Smith'), Author(alias='Jordan Élena'), Author(alias='皇帝'), Author(alias=''), Author(alias=None), ]) def test_basic(self): authors = Author.objects.annotate( sha512_alias=SHA512('alias'), ).values_list('sha512_alias', flat=True).order_by('pk') self.assertSequenceEqual( authors, [ 'ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd803f33cf' '3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055efff040a3fc091518', 'b09c449f3ba49a32ab44754982d4749ac938af293e4af2de28858858080a1611' '2b719514b5e48cb6ce54687e843a4b3e69a04cdb2a9dc99c3b99bdee419fa7d0', 'b554d182e25fb487a3f2b4285bb8672f98956b5369138e681b467d1f079af116' '172d88798345a3a7666faf5f35a144c60812d3234dcd35f444624f2faee16857', 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce' '47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e', 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce' '47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e' if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA512): authors = Author.objects.filter( alias__sha512=( 'ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd8' '03f33cf3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055eff' 'f040a3fc091518' ), ).values_list('alias', flat=True) self.assertSequenceEqual(authors, ['John Smith'])
38e50f37c4db6bde9fef55ff5aec16f87791d866f495a7e6fa2648bc3cba1b3e
from django.db.models import Value from django.db.models.functions import StrIndex from django.test import TestCase from django.utils import timezone from ..models import Article, Author class StrIndexTests(TestCase): def test_annotate_charfield(self): Author.objects.create(name='George. R. R. Martin') Author.objects.create(name='J. R. R. Tolkien') Author.objects.create(name='Terry Pratchett') authors = Author.objects.annotate(fullstop=StrIndex('name', Value('R.'))) self.assertQuerysetEqual(authors.order_by('name'), [9, 4, 0], lambda a: a.fullstop) def test_annotate_textfield(self): Article.objects.create( title='How to Django', text='This is about How to Django.', written=timezone.now(), ) Article.objects.create( title='How to Tango', text="Won't find anything here.", written=timezone.now(), ) articles = Article.objects.annotate(title_pos=StrIndex('text', 'title')) self.assertQuerysetEqual(articles.order_by('title'), [15, 0], lambda a: a.title_pos) def test_order_by(self): Author.objects.create(name='Terry Pratchett') Author.objects.create(name='J. R. R. Tolkien') Author.objects.create(name='George. R. R. Martin') self.assertQuerysetEqual( Author.objects.order_by(StrIndex('name', Value('R.')).asc()), [ 'Terry Pratchett', 'J. R. R. Tolkien', 'George. R. R. Martin', ], lambda a: a.name ) self.assertQuerysetEqual( Author.objects.order_by(StrIndex('name', Value('R.')).desc()), [ 'George. R. R. Martin', 'J. R. R. Tolkien', 'Terry Pratchett', ], lambda a: a.name ) def test_unicode_values(self): Author.objects.create(name='ツリー') Author.objects.create(name='皇帝') Author.objects.create(name='皇帝 ツリー') authors = Author.objects.annotate(sb=StrIndex('name', Value('リ'))) self.assertQuerysetEqual(authors.order_by('name'), [2, 0, 5], lambda a: a.sb) def test_filtering(self): Author.objects.create(name='George. R. R. Martin') Author.objects.create(name='Terry Pratchett') self.assertQuerysetEqual( Author.objects.annotate(middle_name=StrIndex('name', Value('R.'))).filter(middle_name__gt=0), ['George. R. R. Martin'], lambda a: a.name )
21c557048050c6e79e3f9837e08bf79be075518f27cfe8a4374cce401263b66b
from django.db import connection from django.db.models import CharField from django.db.models.functions import Length, Reverse, Trim from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class ReverseTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name='John Smith', alias='smithj') cls.elena = Author.objects.create(name='Élena Jordan', alias='elena') cls.python = Author.objects.create(name='パイソン') def test_null(self): author = Author.objects.annotate(backward=Reverse('alias')).get(pk=self.python.pk) self.assertEqual(author.backward, '' if connection.features.interprets_empty_strings_as_nulls else None) def test_basic(self): authors = Author.objects.annotate(backward=Reverse('name')) self.assertQuerysetEqual( authors, [ ('John Smith', 'htimS nhoJ'), ('Élena Jordan', 'nadroJ anelÉ'), ('パイソン', 'ンソイパ'), ], lambda a: (a.name, a.backward), ordered=False, ) def test_transform(self): with register_lookup(CharField, Reverse): authors = Author.objects.all() self.assertCountEqual(authors.filter(name__reverse=self.john.name[::-1]), [self.john]) self.assertCountEqual(authors.exclude(name__reverse=self.john.name[::-1]), [self.elena, self.python]) def test_expressions(self): author = Author.objects.annotate(backward=Reverse(Trim('name'))).get(pk=self.john.pk) self.assertEqual(author.backward, self.john.name[::-1]) with register_lookup(CharField, Reverse), register_lookup(CharField, Length): authors = Author.objects.all() self.assertCountEqual(authors.filter(name__reverse__length__gt=7), [self.john, self.elena]) self.assertCountEqual(authors.exclude(name__reverse__length__gt=7), [self.python])
57b9a4c5efc7be302cf290ebe5482053ec32f648fc2899cc298b25822b38a81f
from django.db.models import IntegerField from django.db.models.functions import Chr, Left, Ord from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class ChrTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name='John Smith', alias='smithj') cls.elena = Author.objects.create(name='Élena Jordan', alias='elena') cls.rhonda = Author.objects.create(name='Rhonda') def test_basic(self): authors = Author.objects.annotate(first_initial=Left('name', 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord('J'))), [self.john]) self.assertCountEqual(authors.exclude(first_initial=Chr(ord('J'))), [self.elena, self.rhonda]) def test_non_ascii(self): authors = Author.objects.annotate(first_initial=Left('name', 1)) self.assertCountEqual(authors.filter(first_initial=Chr(ord('É'))), [self.elena]) self.assertCountEqual(authors.exclude(first_initial=Chr(ord('É'))), [self.john, self.rhonda]) def test_transform(self): with register_lookup(IntegerField, Chr): authors = Author.objects.annotate(name_code_point=Ord('name')) self.assertCountEqual(authors.filter(name_code_point__chr=Chr(ord('J'))), [self.john]) self.assertCountEqual(authors.exclude(name_code_point__chr=Chr(ord('J'))), [self.elena, self.rhonda])
a7e136d8dbfdd4e76b341ddc60eef223e0660b93f4085a741ea7b5c0f144462d
from django.db import connection from django.db.models import CharField, Value from django.db.models.functions import Length, Repeat from django.test import TestCase from ..models import Author class RepeatTests(TestCase): def test_basic(self): Author.objects.create(name='John', alias='xyz') none_value = '' if connection.features.interprets_empty_strings_as_nulls else None tests = ( (Repeat('name', 0), ''), (Repeat('name', 2), 'JohnJohn'), (Repeat('name', Length('alias'), output_field=CharField()), 'JohnJohnJohn'), (Repeat(Value('x'), 3, output_field=CharField()), 'xxx'), (Repeat('name', None), none_value), (Repeat('goes_by', 1), none_value), ) for function, repeated_text in tests: with self.subTest(function=function): authors = Author.objects.annotate(repeated_text=function) self.assertQuerysetEqual(authors, [repeated_text], lambda a: a.repeated_text, ordered=False) def test_negative_number(self): with self.assertRaisesMessage(ValueError, "'number' must be greater or equal to 0."): Repeat('name', -1)
cc25fe53a9ba14cdf8bc04707d7f186d76dd6412b2d546c32c724bc9fe6bc597
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA256 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA256Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create([ Author(alias='John Smith'), Author(alias='Jordan Élena'), Author(alias='皇帝'), Author(alias=''), Author(alias=None), ]) def test_basic(self): authors = Author.objects.annotate( sha256_alias=SHA256('alias'), ).values_list('sha256_alias', flat=True).order_by('pk') self.assertSequenceEqual( authors, [ 'ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a', '6e4cce20cd83fc7c202f21a8b2452a68509cf24d1c272a045b5e0cfc43f0d94e', '3ad2039e3ec0c88973ae1c0fce5a3dbafdd5a1627da0a92312c54ebfcf43988e', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA256): authors = Author.objects.filter( alias__sha256='ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a', ).values_list('alias', flat=True) self.assertSequenceEqual(authors, ['John Smith'])
341cf8ea6e819eb28b5a5bea606206ceca98e8a0ad0fab03bd1468d34e26046c
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA384 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA384Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create([ Author(alias='John Smith'), Author(alias='Jordan Élena'), Author(alias='皇帝'), Author(alias=''), Author(alias=None), ]) def test_basic(self): authors = Author.objects.annotate( sha384_alias=SHA384('alias'), ).values_list('sha384_alias', flat=True).order_by('pk') self.assertSequenceEqual( authors, [ '9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e53b9967b80d77d4f5c2982cbc8', '72202c8005492016cc670219cce82d47d6d2d4273464c742ab5811d691b1e82a7489549e3a73ffa119694f90678ba2e3', 'eda87fae41e59692c36c49e43279c8111a00d79122a282a944e8ba9a403218f049a48326676a43c7ba378621175853b0', '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b', '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b' if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA384): authors = Author.objects.filter( alias__sha384=( '9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e53b9967b80d77d4f5c2982cbc8' ), ).values_list('alias', flat=True) self.assertSequenceEqual(authors, ['John Smith'])
8c3f8374d076fe89d816e65b5a0e803481654ae599bec4b759b7cd5526ae19d0
import unittest from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA224 from django.db.utils import NotSupportedError from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA224Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create([ Author(alias='John Smith'), Author(alias='Jordan Élena'), Author(alias='皇帝'), Author(alias=''), Author(alias=None), ]) @unittest.skipIf(connection.vendor == 'oracle', "Oracle doesn't support SHA224.") def test_basic(self): authors = Author.objects.annotate( sha224_alias=SHA224('alias'), ).values_list('sha224_alias', flat=True).order_by('pk') self.assertSequenceEqual( authors, [ 'a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70', '2297904883e78183cb118fc3dc21a610d60daada7b6ebdbc85139f4d', 'eba942746e5855121d9d8f79e27dfdebed81adc85b6bf41591203080', 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f', 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f' if connection.features.interprets_empty_strings_as_nulls else None, ], ) @unittest.skipIf(connection.vendor == 'oracle', "Oracle doesn't support SHA224.") def test_transform(self): with register_lookup(CharField, SHA224): authors = Author.objects.filter( alias__sha224='a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70', ).values_list('alias', flat=True) self.assertSequenceEqual(authors, ['John Smith']) @unittest.skipUnless(connection.vendor == 'oracle', "Oracle doesn't support SHA224.") def test_unsupported(self): msg = 'SHA224 is not supported on Oracle.' with self.assertRaisesMessage(NotSupportedError, msg): Author.objects.annotate(sha224_alias=SHA224('alias')).first()
d75ad24052c7c9b948176f2d14527b8fa41b7e75bc155ef811c72c4fc3249a63
from django.db.models import CharField from django.db.models.functions import Lower from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class LowerTests(TestCase): def test_basic(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(lower_name=Lower('name')) self.assertQuerysetEqual( authors.order_by('name'), ['john smith', 'rhonda'], lambda a: a.lower_name ) Author.objects.update(name=Lower('name')) self.assertQuerysetEqual( authors.order_by('name'), [ ('john smith', 'john smith'), ('rhonda', 'rhonda'), ], lambda a: (a.lower_name, a.name) ) def test_num_args(self): with self.assertRaisesMessage(TypeError, "'Lower' takes exactly 1 argument (2 given)"): Author.objects.update(name=Lower('name', 'name')) def test_transform(self): with register_lookup(CharField, Lower): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.filter(name__lower__exact='john smith') self.assertQuerysetEqual( authors.order_by('name'), ['John Smith'], lambda a: a.name )
fe6e95c7ab632c92880e42348f648a0d26a924308c1c6068a24a9ed504199879
from django.db.models import CharField, Value from django.db.models.functions import Lower, Right from django.test import TestCase from ..models import Author class RightTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') def test_basic(self): authors = Author.objects.annotate(name_part=Right('name', 5)) self.assertQuerysetEqual(authors.order_by('name'), ['Smith', 'honda'], lambda a: a.name_part) # If alias is null, set it to the first 2 lower characters of the name. Author.objects.filter(alias__isnull=True).update(alias=Lower(Right('name', 2))) self.assertQuerysetEqual(authors.order_by('name'), ['smithj', 'da'], lambda a: a.alias) def test_invalid_length(self): with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): Author.objects.annotate(raises=Right('name', 0)) def test_expressions(self): authors = Author.objects.annotate(name_part=Right('name', Value(3), output_field=CharField())) self.assertQuerysetEqual(authors.order_by('name'), ['ith', 'nda'], lambda a: a.name_part)
082e1de45c30be8057ab702cff7390f468bbfd889e94c14868c6f06f1f85feff
from django.db.models import F, Value from django.db.models.functions import Concat, Replace from django.test import TestCase from ..models import Author class ReplaceTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name='George R. R. Martin') Author.objects.create(name='J. R. R. Tolkien') def test_replace_with_empty_string(self): qs = Author.objects.annotate( without_middlename=Replace(F('name'), Value('R. R. '), Value('')), ) self.assertQuerysetEqual(qs, [ ('George R. R. Martin', 'George Martin'), ('J. R. R. Tolkien', 'J. Tolkien'), ], transform=lambda x: (x.name, x.without_middlename), ordered=False) def test_case_sensitive(self): qs = Author.objects.annotate(same_name=Replace(F('name'), Value('r. r.'), Value(''))) self.assertQuerysetEqual(qs, [ ('George R. R. Martin', 'George R. R. Martin'), ('J. R. R. Tolkien', 'J. R. R. Tolkien'), ], transform=lambda x: (x.name, x.same_name), ordered=False) def test_replace_expression(self): qs = Author.objects.annotate(same_name=Replace( Concat(Value('Author: '), F('name')), Value('Author: '), Value('')), ) self.assertQuerysetEqual(qs, [ ('George R. R. Martin', 'George R. R. Martin'), ('J. R. R. Tolkien', 'J. R. R. Tolkien'), ], transform=lambda x: (x.name, x.same_name), ordered=False) def test_update(self): Author.objects.update( name=Replace(F('name'), Value('R. R. '), Value('')), ) self.assertQuerysetEqual(Author.objects.all(), [ ('George Martin'), ('J. Tolkien'), ], transform=lambda x: x.name, ordered=False) def test_replace_with_default_arg(self): # The default replacement is an empty string. qs = Author.objects.annotate(same_name=Replace(F('name'), Value('R. R. '))) self.assertQuerysetEqual(qs, [ ('George R. R. Martin', 'George Martin'), ('J. R. R. Tolkien', 'J. Tolkien'), ], transform=lambda x: (x.name, x.same_name), ordered=False)
ccf44c113276a55b3fb396985eb8bf467dfe15da449b0ca77f8abbf186e833e3
from django.db.models import CharField, Value from django.db.models.functions import Left, Lower from django.test import TestCase from ..models import Author class LeftTests(TestCase): @classmethod def setUpTestData(cls): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') def test_basic(self): authors = Author.objects.annotate(name_part=Left('name', 5)) self.assertQuerysetEqual(authors.order_by('name'), ['John ', 'Rhond'], lambda a: a.name_part) # If alias is null, set it to the first 2 lower characters of the name. Author.objects.filter(alias__isnull=True).update(alias=Lower(Left('name', 2))) self.assertQuerysetEqual(authors.order_by('name'), ['smithj', 'rh'], lambda a: a.alias) def test_invalid_length(self): with self.assertRaisesMessage(ValueError, "'length' must be greater than 0"): Author.objects.annotate(raises=Left('name', 0)) def test_expressions(self): authors = Author.objects.annotate(name_part=Left('name', Value(3), output_field=CharField())) self.assertQuerysetEqual(authors.order_by('name'), ['Joh', 'Rho'], lambda a: a.name_part)
e877ebe530474390b2fa99b1efeff1307a86b9ef9032ad779127acc929510754
from unittest import skipUnless from django.db import connection from django.db.models import CharField, TextField, Value as V from django.db.models.functions import Concat, ConcatPair, Upper from django.test import TestCase from django.utils import timezone from ..models import Article, Author lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class ConcatTests(TestCase): def test_basic(self): Author.objects.create(name='Jayden') Author.objects.create(name='John Smith', alias='smithj', goes_by='John') Author.objects.create(name='Margaret', goes_by='Maggie') Author.objects.create(name='Rhonda', alias='adnohR') authors = Author.objects.annotate(joined=Concat('alias', 'goes_by')) self.assertQuerysetEqual( authors.order_by('name'), [ '', 'smithjJohn', 'Maggie', 'adnohR', ], lambda a: a.joined ) def test_gt_two_expressions(self): with self.assertRaisesMessage(ValueError, 'Concat must take at least two expressions'): Author.objects.annotate(joined=Concat('alias')) def test_many(self): Author.objects.create(name='Jayden') Author.objects.create(name='John Smith', alias='smithj', goes_by='John') Author.objects.create(name='Margaret', goes_by='Maggie') Author.objects.create(name='Rhonda', alias='adnohR') authors = Author.objects.annotate( joined=Concat('name', V(' ('), 'goes_by', V(')'), output_field=CharField()), ) self.assertQuerysetEqual( authors.order_by('name'), [ 'Jayden ()', 'John Smith (John)', 'Margaret (Maggie)', 'Rhonda ()', ], lambda a: a.joined ) def test_mixed_char_text(self): Article.objects.create(title='The Title', text=lorem_ipsum, written=timezone.now()) article = Article.objects.annotate( title_text=Concat('title', V(' - '), 'text', output_field=TextField()), ).get(title='The Title') self.assertEqual(article.title + ' - ' + article.text, article.title_text) # Wrap the concat in something else to ensure that text is returned # rather than bytes. article = Article.objects.annotate( title_text=Upper(Concat('title', V(' - '), 'text', output_field=TextField())), ).get(title='The Title') expected = article.title + ' - ' + article.text self.assertEqual(expected.upper(), article.title_text) @skipUnless(connection.vendor == 'sqlite', "sqlite specific implementation detail.") def test_coalesce_idempotent(self): pair = ConcatPair(V('a'), V('b')) # Check nodes counts self.assertEqual(len(list(pair.flatten())), 3) self.assertEqual(len(list(pair.coalesce().flatten())), 7) # + 2 Coalesce + 2 Value() self.assertEqual(len(list(pair.flatten())), 3) def test_sql_generation_idempotency(self): qs = Article.objects.annotate(description=Concat('title', V(': '), 'summary')) # Multiple compilations should not alter the generated query. self.assertEqual(str(qs.query), str(qs.all().query))
4b48a7a138f0da7e2d7b3aed8adfbd326079926748af3827fcc12bdd53f4ffd3
from django.db import connection from django.db.models import CharField from django.db.models.functions import SHA1 from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class SHA1Tests(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create([ Author(alias='John Smith'), Author(alias='Jordan Élena'), Author(alias='皇帝'), Author(alias=''), Author(alias=None), ]) def test_basic(self): authors = Author.objects.annotate( sha1_alias=SHA1('alias'), ).values_list('sha1_alias', flat=True).order_by('pk') self.assertSequenceEqual( authors, [ 'e61a3587b3f7a142b8c7b9263c82f8119398ecb7', '0781e0745a2503e6ded05ed5bc554c421d781b0c', '198d15ea139de04060caf95bc3e0ec5883cba881', 'da39a3ee5e6b4b0d3255bfef95601890afd80709', 'da39a3ee5e6b4b0d3255bfef95601890afd80709' if connection.features.interprets_empty_strings_as_nulls else None, ], ) def test_transform(self): with register_lookup(CharField, SHA1): authors = Author.objects.filter( alias__sha1='e61a3587b3f7a142b8c7b9263c82f8119398ecb7', ).values_list('alias', flat=True) self.assertSequenceEqual(authors, ['John Smith'])
1267fac7d5a675090a25597cef7fcda1277a08631c9b196d2cb55e93e064d5b4
from django.db.models import CharField, Value from django.db.models.functions import Left, Ord from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class OrdTests(TestCase): @classmethod def setUpTestData(cls): cls.john = Author.objects.create(name='John Smith', alias='smithj') cls.elena = Author.objects.create(name='Élena Jordan', alias='elena') cls.rhonda = Author.objects.create(name='Rhonda') def test_basic(self): authors = Author.objects.annotate(name_part=Ord('name')) self.assertCountEqual(authors.filter(name_part__gt=Ord(Value('John'))), [self.elena, self.rhonda]) self.assertCountEqual(authors.exclude(name_part__gt=Ord(Value('John'))), [self.john]) def test_transform(self): with register_lookup(CharField, Ord): authors = Author.objects.annotate(first_initial=Left('name', 1)) self.assertCountEqual(authors.filter(first_initial__ord=ord('J')), [self.john]) self.assertCountEqual(authors.exclude(first_initial__ord=ord('J')), [self.elena, self.rhonda])
52bb9f005283a9621cded296eb5b9623768f6b0c04f2134572749c0899465c8e
from django.db.models import CharField from django.db.models.functions import Length from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class LengthTests(TestCase): def test_basic(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate( name_length=Length('name'), alias_length=Length('alias'), ) self.assertQuerysetEqual( authors.order_by('name'), [(10, 6), (6, None)], lambda a: (a.name_length, a.alias_length) ) self.assertEqual(authors.filter(alias_length__lte=Length('name')).count(), 1) def test_ordering(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='John Smith', alias='smithj1') Author.objects.create(name='Rhonda', alias='ronny') authors = Author.objects.order_by(Length('name'), Length('alias')) self.assertQuerysetEqual( authors, [ ('Rhonda', 'ronny'), ('John Smith', 'smithj'), ('John Smith', 'smithj1'), ], lambda a: (a.name, a.alias) ) def test_transform(self): with register_lookup(CharField, Length): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.filter(name__length__gt=7) self.assertQuerysetEqual( authors.order_by('name'), ['John Smith'], lambda a: a.name )
ad3e390c28207f385bc2c1b9f63545049e32b81b34c34bab51a54dd405aeaf5b
from django.db.models import CharField from django.db.models.functions import Upper from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class UpperTests(TestCase): def test_basic(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(upper_name=Upper('name')) self.assertQuerysetEqual( authors.order_by('name'), [ 'JOHN SMITH', 'RHONDA', ], lambda a: a.upper_name ) Author.objects.update(name=Upper('name')) self.assertQuerysetEqual( authors.order_by('name'), [ ('JOHN SMITH', 'JOHN SMITH'), ('RHONDA', 'RHONDA'), ], lambda a: (a.upper_name, a.name) ) def test_transform(self): with register_lookup(CharField, Upper): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.filter(name__upper__exact='JOHN SMITH') self.assertQuerysetEqual( authors.order_by('name'), [ 'John Smith', ], lambda a: a.name )
2c5ab6e3f14bba5e144a11f7f9a3d5bf6686f52109c456f0d0e0b4db931c6339
from django.db.models import CharField, Value as V from django.db.models.functions import Lower, StrIndex, Substr, Upper from django.test import TestCase from ..models import Author class SubstrTests(TestCase): def test_basic(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(name_part=Substr('name', 5, 3)) self.assertQuerysetEqual( authors.order_by('name'), [' Sm', 'da'], lambda a: a.name_part ) authors = Author.objects.annotate(name_part=Substr('name', 2)) self.assertQuerysetEqual( authors.order_by('name'), ['ohn Smith', 'honda'], lambda a: a.name_part ) # If alias is null, set to first 5 lower characters of the name. Author.objects.filter(alias__isnull=True).update( alias=Lower(Substr('name', 1, 5)), ) self.assertQuerysetEqual( authors.order_by('name'), ['smithj', 'rhond'], lambda a: a.alias ) def test_start(self): Author.objects.create(name='John Smith', alias='smithj') a = Author.objects.annotate( name_part_1=Substr('name', 1), name_part_2=Substr('name', 2), ).get(alias='smithj') self.assertEqual(a.name_part_1[1:], a.name_part_2) def test_pos_gt_zero(self): with self.assertRaisesMessage(ValueError, "'pos' must be greater than 0"): Author.objects.annotate(raises=Substr('name', 0)) def test_expressions(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') substr = Substr(Upper('name'), StrIndex('name', V('h')), 5, output_field=CharField()) authors = Author.objects.annotate(name_part=substr) self.assertQuerysetEqual( authors.order_by('name'), ['HN SM', 'HONDA'], lambda a: a.name_part )
cc4c3215376fae98f15b609622ab3bcd55b9e09c2b64e27769b3806cbd1d7fa6
from django.db.models import CharField from django.db.models.functions import LTrim, RTrim, Trim from django.test import TestCase from django.test.utils import register_lookup from ..models import Author class TrimTests(TestCase): def test_trim(self): Author.objects.create(name=' John ', alias='j') Author.objects.create(name='Rhonda', alias='r') authors = Author.objects.annotate( ltrim=LTrim('name'), rtrim=RTrim('name'), trim=Trim('name'), ) self.assertQuerysetEqual( authors.order_by('alias'), [ ('John ', ' John', 'John'), ('Rhonda', 'Rhonda', 'Rhonda'), ], lambda a: (a.ltrim, a.rtrim, a.trim) ) def test_trim_transform(self): Author.objects.create(name=' John ') Author.objects.create(name='Rhonda') tests = ( (LTrim, 'John '), (RTrim, ' John'), (Trim, 'John'), ) for transform, trimmed_name in tests: with self.subTest(transform=transform): with register_lookup(CharField, transform): authors = Author.objects.filter(**{'name__%s' % transform.lookup_name: trimmed_name}) self.assertQuerysetEqual(authors, [' John '], lambda a: a.name)